#!/usr/bin/env python3
"""
Video Segment Extractor (with viewer + frame extraction)
Good for precise work on smaller/medium videos.
"""
import sys
import os
import subprocess
import time
import traceback
import threading
import signal

sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)

print("=== Video Segment Extractor starting ===")
print(f"Python: {sys.version}")
print(f"Arguments: {sys.argv}")

import cv2
import pygame
import numpy as np

print("Imports OK")

# ---------- Configuration ----------
WINDOW_W, WINDOW_H = 1200, 720
VIDEO_DISPLAY_H = 450
TIMELINE_Y = 500
TIMELINE_H = 30
BUTTON_Y = 560
FONT_SIZE = 26
SMALL_FONT_SIZE = 20
BG_COLOR = (30, 30, 30)
TIMELINE_BG = (60, 60, 60)
TIMELINE_FG = (0, 180, 255)
HANDLE_COLOR = (255, 80, 80)
IN_COLOR = (0, 200, 0)
OUT_COLOR = (200, 0, 0)
TEXT_COLOR = (230, 230, 230)
BUTTON_COLOR = (70, 70, 70)
BUTTON_HOVER = (100, 100, 100)

SCRUB_MIN_INTERVAL = 0.05   # ~20 fps max during drag / held-arrow


class VideoPlayer:
    def __init__(self, video_path=None):
        print("Initializing pygame...")
        pygame.init()
        pygame.font.init()
        print("Creating window...")
        self.screen = pygame.display.set_mode((WINDOW_W, WINDOW_H))
        pygame.display.set_caption("Video Segment Extractor")
        print("Window created.")
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, FONT_SIZE)
        self.small_font = pygame.font.Font(None, SMALL_FONT_SIZE)

        self.video_path = None
        self.cap = None
        self.fps = 30.0
        self.duration = 0.0
        self.frame_count = 0
        self.current_time = 0.0
        self.last_decoded_time = -1.0
        self.playing = False
        self.last_frame_time = 0.0
        self.status = "No video"
        self.extracting = False
        self.extract_progress = 0.0

        self.in_time = None
        self.out_time = None
        self.in_frame = None
        self.out_frame = None

        self.frame_fps = 1.0

        self.dragging = False
        self.precise_drag = False
        self.video_surface = None
        self.video_rect = None

        # Continuous arrow-key seeking
        self.left_held = False
        self.right_held = False
        self.arrow_speed = 1.0          # seconds of video per real second while held
        self.arrow_start_time = 0.0     # when the key was first pressed (for delay)

        self.buttons = {}
        self.setup_buttons()
        self.should_quit = False

        signal.signal(signal.SIGTERM, self._signal_quit)
        signal.signal(signal.SIGINT, self._signal_quit)

        if video_path and os.path.isfile(video_path):
            self.load_video(video_path)
        else:
            self.prompt_load_video()

    def setup_buttons(self):
        bw, bh = 130, 46
        labels = [
            ("Load", 15),
            ("Play/Stop", 155),
            ("In", 295),
            ("Out", 435),
            ("Extract Video", 575),
            ("Extract Frames", 715),
            ("QUIT", 1015),
        ]
        for label, x in labels:
            self.buttons[label] = pygame.Rect(x, BUTTON_Y, bw, bh)

    def _signal_quit(self, signum, frame):
        print(f"Received signal {signum}, quitting...")
        self.should_quit = True
        try:
            pygame.event.post(pygame.event.Event(pygame.QUIT))
        except Exception:
            pass

    def prompt_load_video(self):
        print("No video loaded. Use the Load button or run with a video path.")

    def load_video(self, path):
        print(f"Trying to open: {path}")
        if self.cap:
            self.cap.release()
        self.video_path = path
        self.cap = cv2.VideoCapture(path)
        if not self.cap.isOpened():
            print(f"ERROR: OpenCV could not open the video: {path}")
            self.video_surface = None
            self.duration = 0
            self.status = "Failed to open video"
            return

        self.fps = self.cap.get(cv2.CAP_PROP_FPS) or 30.0
        self.frame_count = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        self.duration = self.frame_count / self.fps if self.fps > 0 else 0
        self.frame_fps = round(self.fps, 1)
        print(f"Opened OK | Duration: {self.duration:.2f}s | FPS: {self.fps:.2f} | Frames: {self.frame_count}")

        self.current_time = 0.0
        self.last_decoded_time = -1.0
        self.in_time = None
        self.out_time = None
        self.in_frame = None
        self.out_frame = None
        self.playing = False
        self.video_surface = None
        self.status = "Video loaded"
        self.left_held = False
        self.right_held = False

        print("Reading first frame...")
        ret, frame = self.cap.read()
        if not ret or frame is None:
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
            ret, frame = self.cap.read()
        if not ret or frame is None:
            for offset in (1, 5, 10, 30):
                self.cap.set(cv2.CAP_PROP_POS_FRAMES, offset)
                ret, frame = self.cap.read()
                if ret and frame is not None:
                    break

        if ret and frame is not None:
            self.update_frame(frame)
            self.current_time = self.cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
            self.last_decoded_time = self.current_time
            print("First frame OK.")
        else:
            self.status = "No frames readable"

        pygame.display.set_caption(f"Video Segment Extractor - {os.path.basename(path)}")

    def seek(self, t, force=False):
        t = max(0.0, min(t, self.duration))
        self.current_time = t
        if force:
            self._decode_at(t)

    def _decode_at(self, t):
        if not self.cap or self.duration <= 0:
            return
        frame_idx = int(round(t * self.fps))
        self.cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
        ret, frame = self.cap.read()
        if ret and frame is not None:
            self.update_frame(frame)
            self.current_time = t
            self.last_decoded_time = t
        else:
            for delta in (1, -1, 2, -2):
                self.cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, frame_idx + delta))
                ret, frame = self.cap.read()
                if ret and frame is not None:
                    self.update_frame(frame)
                    self.current_time = t
                    self.last_decoded_time = t
                    break

    def update_frame(self, frame):
        if frame is None:
            return
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w = frame.shape[:2]
        display_w = WINDOW_W - 40
        display_h = VIDEO_DISPLAY_H
        scale = min(display_w / w, display_h / h)
        new_w, new_h = int(w * scale), int(h * scale)
        frame = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
        self.video_surface = pygame.surfarray.make_surface(frame.swapaxes(0, 1))
        self.video_rect = self.video_surface.get_rect(center=(WINDOW_W // 2, VIDEO_DISPLAY_H // 2 + 20))

    def format_time(self, t):
        if t is None:
            return "--:--.--"
        mins = int(t // 60)
        secs = t % 60
        return f"{mins:02d}:{secs:05.2f}"

    def draw(self):
        self.screen.fill(BG_COLOR)

        if self.video_surface:
            self.screen.blit(self.video_surface, self.video_rect)
        else:
            txt = self.font.render("Could not read video frames", True, TEXT_COLOR)
            self.screen.blit(txt, (WINDOW_W//2 - txt.get_width()//2, 160))

        timeline_rect = pygame.Rect(20, TIMELINE_Y, WINDOW_W - 40, TIMELINE_H)
        pygame.draw.rect(self.screen, TIMELINE_BG, timeline_rect, border_radius=4)

        if self.duration > 0:
            progress = self.current_time / self.duration
            prog_w = int((WINDOW_W - 40) * progress)
            pygame.draw.rect(self.screen, TIMELINE_FG, (20, TIMELINE_Y, prog_w, TIMELINE_H), border_radius=4)

            if self.in_time is not None:
                ix = 20 + int((self.in_time / self.duration) * (WINDOW_W - 40))
                pygame.draw.line(self.screen, IN_COLOR, (ix, TIMELINE_Y - 5), (ix, TIMELINE_Y + TIMELINE_H + 5), 3)

            if self.out_time is not None:
                ox = 20 + int((self.out_time / self.duration) * (WINDOW_W - 40))
                pygame.draw.line(self.screen, OUT_COLOR, (ox, TIMELINE_Y - 5), (ox, TIMELINE_Y + TIMELINE_H + 5), 3)

            hx = 20 + int(progress * (WINDOW_W - 40))
            pygame.draw.circle(self.screen, HANDLE_COLOR, (hx, TIMELINE_Y + TIMELINE_H // 2), 8)

        time_txt = self.font.render(
            f"Time: {self.format_time(self.current_time)} / {self.format_time(self.duration)}",
            True, TEXT_COLOR
        )
        self.screen.blit(time_txt, (20, TIMELINE_Y - 30))

        in_frame_str = str(self.in_frame) if self.in_frame is not None else "--"
        out_frame_str = str(self.out_frame) if self.out_frame is not None else "--"
        all_frames = abs(self.frame_fps - self.fps) < 0.1
        fps_note = " (all frames)" if all_frames else ""
        in_out_txt = self.small_font.render(
            f"In: {self.format_time(self.in_time)} (f{in_frame_str})   Out: {self.format_time(self.out_time)} (f{out_frame_str})   Extract FPS: {self.frame_fps:.1f}{fps_note}",
            True, TEXT_COLOR
        )
        self.screen.blit(in_out_txt, (20, TIMELINE_Y + TIMELINE_H + 10))

        help_txt = self.small_font.render(
            "Drag timeline (Shift+drag = precise)   Arrows = step / hold to scan   I/O = In/Out   Space = Play   [ / ] = extract rate   N = native FPS",
            True, (140, 140, 140)
        )
        self.screen.blit(help_txt, (20, WINDOW_H - 25))

        status = self.small_font.render(self.status, True, (180, 220, 180))
        self.screen.blit(status, (WINDOW_W - status.get_width() - 20, TIMELINE_Y - 30))

        mouse_pos = pygame.mouse.get_pos()
        for label, rect in self.buttons.items():
            color = BUTTON_HOVER if rect.collidepoint(mouse_pos) else BUTTON_COLOR
            pygame.draw.rect(self.screen, color, rect, border_radius=6)
            pygame.draw.rect(self.screen, (150, 150, 150), rect, 1, border_radius=6)
            txt = self.small_font.render(label, True, TEXT_COLOR)
            self.screen.blit(txt, (rect.centerx - txt.get_width()//2, rect.centery - txt.get_height()//2))

        if self.extracting or self.extract_progress > 0:
            bar_y = BUTTON_Y + 55
            bar_w = WINDOW_W - 40
            pygame.draw.rect(self.screen, (40, 40, 40), (20, bar_y, bar_w, 24), border_radius=5)

            if self.extract_progress > 0.01:
                fill_w = int(bar_w * self.extract_progress)
                pygame.draw.rect(self.screen, (0, 170, 90), (20, bar_y, fill_w, 24), border_radius=5)
                label = f"Extracting… {int(self.extract_progress * 100)}%"
            else:
                elapsed = time.time() - getattr(self, "extract_started", time.time())
                pos = int((elapsed * 140) % (bar_w + 100)) - 50
                hi_x = 20 + max(0, min(pos, bar_w - 50))
                pygame.draw.rect(self.screen, (0, 140, 70), (hi_x, bar_y, 50, 24))
                label = "Working…"

            prog_txt = self.small_font.render(label, True, (255, 255, 255))
            self.screen.blit(prog_txt, (WINDOW_W // 2 - prog_txt.get_width() // 2, bar_y + 2))

        pygame.display.flip()

    def handle_key(self, event):
        if not self.cap or self.duration <= 0:
            if event.key == pygame.K_LEFTBRACKET:
                self.frame_fps = max(0.1, round(self.frame_fps - 0.5, 1))
            elif event.key == pygame.K_RIGHTBRACKET:
                self.frame_fps = min(60.0, round(self.frame_fps + 0.5, 1))
            return

        mods = pygame.key.get_mods()
        shift = mods & pygame.KMOD_SHIFT
        step = 10 if shift else 1

        if event.key == pygame.K_LEFT:
            if self.playing:
                self.playing = False
            # Single step on press
            new_t = max(0, self.current_time - step / self.fps)
            self.seek(new_t, force=True)
            self.left_held = True
            self.arrow_start_time = time.time()
        elif event.key == pygame.K_RIGHT:
            if self.playing:
                self.playing = False
            new_t = min(self.duration, self.current_time + step / self.fps)
            self.seek(new_t, force=True)
            self.right_held = True
            self.arrow_start_time = time.time()
        elif event.key == pygame.K_i:
            self.in_time = self.current_time
            self.in_frame = int(round(self.current_time * self.fps)) if self.fps else 0
            print(f"In point set: {self.format_time(self.in_time)} (frame {self.in_frame})")
        elif event.key == pygame.K_o:
            self.out_time = self.current_time
            self.out_frame = int(round(self.current_time * self.fps)) if self.fps else 0
            print(f"Out point set: {self.format_time(self.out_time)} (frame {self.out_frame})")
        elif event.key == pygame.K_SPACE:
            self.on_button("Play/Stop")
        elif event.key == pygame.K_LEFTBRACKET:
            self.frame_fps = max(0.1, round(self.frame_fps - 0.5, 1))
            print(f"Frame extraction FPS: {self.frame_fps}")
        elif event.key == pygame.K_RIGHTBRACKET:
            self.frame_fps = min(60.0, round(self.frame_fps + 0.5, 1))
            print(f"Frame extraction FPS: {self.frame_fps}")
        elif event.key == pygame.K_n:
            if self.fps > 0:
                self.frame_fps = round(self.fps, 1)
                print(f"Frame extraction FPS reset to native: {self.frame_fps}")

    def handle_keyup(self, event):
        if event.key == pygame.K_LEFT:
            self.left_held = False
        elif event.key == pygame.K_RIGHT:
            self.right_held = False

    def handle_click(self, pos):
        timeline_rect = pygame.Rect(20, TIMELINE_Y, WINDOW_W - 40, TIMELINE_H)
        if timeline_rect.collidepoint(pos) and self.duration > 0:
            rel = (pos[0] - 20) / (WINDOW_W - 40)
            self.seek(max(0, min(1, rel)) * self.duration, force=True)
            self.dragging = True
            self.precise_drag = bool(pygame.key.get_mods() & pygame.KMOD_SHIFT)
            if self.playing:
                self.playing = False
            return

        for label, rect in self.buttons.items():
            if rect.collidepoint(pos):
                self.on_button(label)
                return

    def on_button(self, label):
        if label == "Load":
            self.load_dialog()
        elif label == "Play/Stop":
            self.playing = not self.playing
            if self.playing:
                self.last_frame_time = time.time()
                self._decode_at(self.current_time)
                self.status = "Playing"
            else:
                self.status = "Paused"
        elif label == "In":
            self.in_time = self.current_time
            self.in_frame = int(round(self.current_time * self.fps)) if self.fps else 0
            print(f"In point set: {self.format_time(self.in_time)} (frame {self.in_frame})")
        elif label == "Out":
            self.out_time = self.current_time
            self.out_frame = int(round(self.current_time * self.fps)) if self.fps else 0
            print(f"Out point set: {self.format_time(self.out_time)} (frame {self.out_frame})")
        elif label == "Extract Video":
            self.extract()
        elif label == "Extract Frames":
            self.extract_frames()
        elif label == "QUIT":
            self.should_quit = True

    def load_dialog(self):
        print("\n--- Load Video ---")
        print("Enter the full path to the video file and press Enter.")
        print("Or just press Enter to cancel:")
        try:
            path = input("> ").strip().strip('"').strip("'")
        except Exception:
            path = None

        if path and os.path.isfile(path):
            self.load_video(path)
        elif path:
            print(f"File not found: {path}")
        else:
            print("Cancelled.")

    def extract(self):
        if not self.video_path:
            print("No video loaded.")
            return
        if self.in_time is None or self.out_time is None:
            print("Please set both In and Out points first.")
            return
        if self.in_time >= self.out_time:
            print("In point must be before Out point.")
            return

        start = self.in_time
        end = self.out_time

        base = os.path.splitext(os.path.basename(self.video_path))[0]
        out_name = f"{base}_video_{start:.1f}-{end:.1f}.mp4"
        out_path = os.path.join(os.path.dirname(self.video_path) or ".", out_name)
        counter = 1
        orig = out_path
        while os.path.exists(out_path):
            name, ext = os.path.splitext(orig)
            out_path = f"{name}_{counter}{ext}"
            counter += 1

        print(f"Extracting video from {start:.2f}s to {end:.2f}s -> {out_path}")
        self.status = "Extracting video…"
        self.extracting = True
        self.extract_progress = 0.0
        self.extract_started = time.time()

        threading.Thread(
            target=self._run_ffmpeg,
            args=(start, end, out_path),
            daemon=True
        ).start()

    def extract_frames(self):
        if not self.video_path:
            print("No video loaded.")
            return
        if self.in_time is None or self.out_time is None:
            print("Please set both In and Out points first.")
            return
        if self.in_time >= self.out_time:
            print("In point must be before Out point.")
            return

        start = self.in_time
        end = self.out_time
        fps = self.frame_fps

        base = os.path.splitext(os.path.basename(self.video_path))[0]
        frames_dir = os.path.join(
            os.path.dirname(self.video_path) or ".",
            f"{base}_frames_{start:.1f}-{end:.1f}_{fps:.1f}fps"
        )
        os.makedirs(frames_dir, exist_ok=True)
        pattern = os.path.join(frames_dir, "frame_%04d.png")

        print(f"Extracting frames at {fps} fps from {start:.2f}s to {end:.2f}s")
        print(f"Output directory: {frames_dir}")
        self.status = "Extracting frames…"
        self.extracting = True
        self.extract_progress = 0.0
        self.extract_started = time.time()

        threading.Thread(
            target=self._run_ffmpeg_frames,
            args=(start, end, fps, pattern, frames_dir),
            daemon=True
        ).start()

    def _run_ffmpeg(self, start, end, out_path):
        duration = max(0.1, end - start)
        pre_seek = max(0, start - 1.0)
        fine_trim = start - pre_seek
        cmd = [
            "ffmpeg", "-y",
            "-ss", str(pre_seek),
            "-i", self.video_path,
            "-ss", str(fine_trim),
            "-t", str(duration),
            "-progress", "pipe:1",
            "-an", "-c:v", "libx264", "-crf", "23", "-preset", "fast", "-pix_fmt", "yuv420p",
            out_path
        ]

        try:
            proc = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1,
                universal_newlines=True
            )
            for line in proc.stdout:
                line = line.strip()
                if line.startswith("out_time_ms="):
                    try:
                        ms = int(line.split("=")[1])
                        elapsed = ms / 1_000_000.0
                        self.extract_progress = min(0.99, elapsed / duration)
                    except Exception:
                        pass
                elif "time=" in line and "bitrate=" in line:
                    try:
                        tpart = line.split("time=")[1].split()[0]
                        h, m, s = tpart.split(":")
                        elapsed = int(h)*3600 + int(m)*60 + float(s)
                        self.extract_progress = min(0.99, elapsed / duration)
                    except Exception:
                        pass
                elif line == "progress=end":
                    self.extract_progress = 1.0
            proc.wait()
            if proc.returncode == 0:
                self.extract_progress = 1.0
                print(f"Success! Saved to: {out_path}")
                self.status = "Clip saved"
            else:
                print("FFmpeg failed")
                self.status = "Extract failed"
        except FileNotFoundError:
            print("ffmpeg not found.")
            self.status = "ffmpeg missing"
        except Exception as e:
            print(f"Extract error: {e}")
            self.status = "Extract error"
        finally:
            self.extracting = False
            time.sleep(0.4)
            self.extract_progress = 0.0

    def _run_ffmpeg_frames(self, start, end, fps, pattern, frames_dir):
        duration = max(0.1, end - start)
        pre_seek = max(0, start - 1.0)
        fine_trim = start - pre_seek
        cmd = [
            "ffmpeg", "-y",
            "-ss", str(pre_seek),
            "-i", self.video_path,
            "-ss", str(fine_trim),
            "-t", str(duration),
            "-vf", f"fps={fps}",
            "-progress", "pipe:1",
            pattern
        ]

        try:
            proc = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1,
                universal_newlines=True
            )
            for line in proc.stdout:
                line = line.strip()
                if line.startswith("out_time_ms="):
                    try:
                        ms = int(line.split("=")[1])
                        elapsed = ms / 1_000_000.0
                        self.extract_progress = min(0.99, elapsed / duration)
                    except Exception:
                        pass
                elif "time=" in line and "bitrate=" in line:
                    try:
                        tpart = line.split("time=")[1].split()[0]
                        h, m, s = tpart.split(":")
                        elapsed = int(h)*3600 + int(m)*60 + float(s)
                        self.extract_progress = min(0.99, elapsed / duration)
                    except Exception:
                        pass
                elif line == "progress=end":
                    self.extract_progress = 1.0
            proc.wait()
            if proc.returncode == 0:
                self.extract_progress = 1.0
                try:
                    count = len([f for f in os.listdir(frames_dir) if f.startswith("frame_") and f.endswith(".png")])
                except Exception:
                    count = "?"
                print(f"Success! {count} frames saved to: {frames_dir}")
                self.status = f"Frames saved ({count})"
            else:
                print("FFmpeg failed")
                self.status = "Frame extract failed"
        except FileNotFoundError:
            print("ffmpeg not found.")
            self.status = "ffmpeg missing"
        except Exception as e:
            print(f"Frame extract error: {e}")
            self.status = "Frame extract error"
        finally:
            self.extracting = False
            time.sleep(0.4)
            self.extract_progress = 0.0

    def run(self):
        running = True
        last_scrub_decode = 0.0

        while running and not self.should_quit:
            dt = self.clock.tick(60) / 1000.0

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.KEYDOWN:
                    self.handle_key(event)
                elif event.type == pygame.KEYUP:
                    self.handle_keyup(event)
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                    self.handle_click(event.pos)
                elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                    if self.dragging and self.duration > 0:
                        self._decode_at(self.current_time)
                    self.dragging = False
                    self.precise_drag = False
                elif event.type == pygame.MOUSEMOTION and self.dragging and self.duration > 0:
                    rel = (event.pos[0] - 20) / (WINDOW_W - 40)
                    rel = max(0.0, min(1.0, rel))
                    if self.precise_drag:
                        current_rel = self.current_time / self.duration if self.duration else 0
                        rel = current_rel + (rel - current_rel) * 0.25
                    self.current_time = rel * self.duration

            # Continuous seeking while arrow keys are held
            # (after a short delay so a quick tap still just steps one frame)
            now = time.time()
            if (self.left_held or self.right_held) and self.duration > 0 and not self.playing:
                if now - self.arrow_start_time > 0.25:   # hold for 250 ms before continuous scan starts
                    direction = -1 if self.left_held else 1
                    # Shift = faster scan
                    speed = self.arrow_speed * (4.0 if pygame.key.get_mods() & pygame.KMOD_SHIFT else 1.0)
                    self.current_time = max(0.0, min(self.duration, self.current_time + direction * speed * dt))

            # Throttled frame decode while dragging or scanning with arrows
            if (self.duration > 0 and
                    abs(self.current_time - self.last_decoded_time) > 0.001 and
                    now - last_scrub_decode >= SCRUB_MIN_INTERVAL and
                    (self.dragging or self.left_held or self.right_held)):
                self._decode_at(self.current_time)
                last_scrub_decode = now

            # Playback
            if self.playing and self.cap and self.duration > 0:
                frame_duration = 1.0 / self.fps if self.fps > 0 else 1/30
                if now - self.last_frame_time >= frame_duration:
                    self.last_frame_time = now
                    ret, frame = self.cap.read()
                    if ret and frame is not None:
                        self.update_frame(frame)
                        self.current_time = self.cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
                        self.last_decoded_time = self.current_time
                        if self.current_time >= self.duration:
                            self.playing = False
                            self.status = "Finished"
                    else:
                        self.playing = False
                        self.status = "Finished"

            self.draw()

        if self.cap:
            self.cap.release()
        pygame.quit()


if __name__ == "__main__":
    try:
        print("=== Video Segment Extractor ===")
        if len(sys.argv) < 2:
            print("Need a video file.")
            print("Example: python3 video_extract_with_frames.py file.mp4")
            print("Exiting.")
            sys.exit(0)

        video = sys.argv[1]
        if not os.path.isfile(video):
            print(f"Error: File not found: {video}")
            print("Example: python3 video_extract_with_frames.py file.mp4")
            sys.exit(1)

        print(f"Opening: {video}")
        player = VideoPlayer(video)
        print("Entering main loop...")
        player.run()
    except Exception as e:
        print("\n=== FATAL ERROR ===")
        traceback.print_exc()
        print("===================")
        input("Press Enter to exit...")
    finally:
        print("Exiting.")
