"""Transcription stage: extract word-level timestamps from video audio."""

import json
import subprocess
from dataclasses import dataclass
from pathlib import Path

from .cache import resolve_with_cache
from .errors import GnommoError
from typing import Optional


@dataclass
class TranscribedWord:
    """A word with its timestamp from transcription."""

    word: str
    start: float
    end: float


class TranscriptionError(GnommoError):
    """Error during transcription."""

    pass


def transcribe_video(video_path: Path, model: str = "base") -> list[TranscribedWord]:
    """
    Transcribe video audio using Whisper and return word-level timestamps.

    Args:
        video_path: Path to video file
        model: Whisper model size (tiny, base, small, medium, large)

    Returns:
        List of TranscribedWord with timestamps
    """
    try:
        import whisper
    except ImportError:
        raise TranscriptionError(
            "Whisper not installed. Run: pip install openai-whisper"
        )

    if not video_path.exists():
        raise TranscriptionError(f"Video file not found: {video_path}")

    print(f"  Loading Whisper model '{model}'...")
    whisper_model = whisper.load_model(model)

    print(f"  Transcribing {video_path.name}...")
    result = whisper_model.transcribe(
        str(video_path),
        word_timestamps=True,
        verbose=False,
    )

    # Extract word-level timestamps
    words: list[TranscribedWord] = []

    for segment in result.get("segments", []):
        for word_info in segment.get("words", []):
            words.append(
                TranscribedWord(
                    word=word_info["word"].strip(),
                    start=word_info["start"],
                    end=word_info["end"],
                )
            )

    return words


def save_transcript(words: list[TranscribedWord], output_path: Path) -> None:
    """Save transcribed words to a JSON file."""
    data = [{"word": w.word, "start": w.start, "end": w.end} for w in words]

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)


def load_transcript(
    transcript_path: Path, project_path: Optional[Path] = None
) -> list[TranscribedWord]:
    """Load transcribed words from a JSON file.

    Args:
        transcript_path: Path to the transcript JSON file
        project_path: Optional project path for cache fallback
    """
    # Try cache fallback if project_path provided
    if project_path:
        transcript_path, _ = resolve_with_cache(transcript_path, project_path)

    if not transcript_path.exists():
        raise TranscriptionError(f"Transcript file not found: {transcript_path}")

    with open(transcript_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    return [
        TranscribedWord(word=w["word"], start=w["start"], end=w["end"]) for w in data
    ]
