import sys
from typing import Optional
import typer

from yt_brief.transcript import fetch_transcript
from yt_brief.summarizer import summarize

app = typer.Typer(add_completion=False)


@app.command()
def main(
    url: str = typer.Argument(..., help="YouTube video URL"),
    provider: str = typer.Option("openai", "--provider", help="LLM provider: openai or anthropic"),
    output: Optional[str] = typer.Option(None, "--output", "-o", help="Save output to file"),
):
    if provider not in ("openai", "anthropic"):
        typer.echo(f"Error: provider must be 'openai' or 'anthropic', got '{provider}'", err=True)
        raise typer.Exit(1)

    typer.echo("Fetching transcript...", err=True)
    try:
        title, transcript, duration_seconds = fetch_transcript(url)
    except Exception as e:
        typer.echo(f"Error fetching transcript: {e}", err=True)
        raise typer.Exit(1)

    duration_min = duration_seconds // 60

    typer.echo(f"Summarizing with {provider}...", err=True)
    try:
        body = summarize(transcript, provider)
    except Exception as e:
        typer.echo(f"Error summarizing: {e}", err=True)
        raise typer.Exit(1)

    result = f"# {title}\n**Duration:** {duration_min} min\n\n{body}\n"

    if output:
        with open(output, "w", encoding="utf-8") as f:
            f.write(result)
        typer.echo(f"Saved to {output}", err=True)
    else:
        typer.echo(result)
