"""
Timeline Planner Agent – calculates exact timestamps and cut points.

This agent is DETERMINISTIC: it does not call the LLM. Timing is derived
from word count in the narration text, which gives reproducible results
and avoids unnecessary API costs.
"""

from __future__ import annotations

from models import (
    AllSceneTTS,
    PipelineConfig,
    SceneTimeline,
    Timeline,
)


def _format_time(seconds: float) -> str:
    """Format seconds as MM:SS."""
    minutes = int(seconds) // 60
    secs = seconds - minutes * 60
    return f"{minutes:02d}:{secs:05.2f}"


class TimelinePlannerAgent:
    """Calculates the production timeline from TTS scripts."""

    def __init__(self, config: PipelineConfig):
        self.wps = config.speaking_rate_wps
        self.min_duration = config.min_scene_duration
        self.transition = config.transition_duration

    def plan(self, tts: AllSceneTTS) -> Timeline:
        current_time = 0.0
        scene_timelines: list[SceneTimeline] = []

        for scene_tts in tts.scenes:
            word_count = len(scene_tts.tts_text.split())
            narration_duration = word_count / self.wps
            # Ensure minimum duration and add a small breathing buffer
            scene_duration = max(narration_duration, self.min_duration) + 0.5

            time_start = current_time
            time_end = current_time + scene_duration
            cut_point = time_end  # where the editor should cut

            scene_timelines.append(
                SceneTimeline(
                    scene_number=scene_tts.scene_number,
                    time_start=_format_time(time_start),
                    time_end=_format_time(time_end),
                    duration_seconds=round(scene_duration, 2),
                    cut_point=_format_time(cut_point),
                    transition=(
                        "crossfade 0.3s"
                        if scene_tts.scene_number < len(tts.scenes)
                        else "fade to black 0.5s"
                    ),
                )
            )
            current_time = time_end

        total = current_time
        return Timeline(
            total_duration_seconds=round(total, 2),
            total_duration_formatted=_format_time(total),
            scenes=scene_timelines,
        )
