import os

PROMPT_TEMPLATE = """\
You are given a YouTube video transcript. Produce a structured summary in this exact markdown format:

## Summary
A concise 2-4 sentence overview of the video.

## Key Points
- Key point 1
- Key point 2
- (up to 7 key points)

## Notable Quotes
- "exact or near-exact quote from transcript"
- (up to 5 quotes)

Transcript:
{transcript}
"""


def summarize_openai(transcript: str) -> str:
    from openai import OpenAI

    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        raise EnvironmentError("OPENAI_API_KEY is not set")

    client = OpenAI(api_key=api_key)
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": PROMPT_TEMPLATE.format(transcript=transcript)}],
        temperature=0.3,
    )
    return response.choices[0].message.content.strip()


def summarize_anthropic(transcript: str) -> str:
    import anthropic

    api_key = os.environ.get("ANTHROPIC_API_KEY")
    if not api_key:
        raise EnvironmentError("ANTHROPIC_API_KEY is not set")

    client = anthropic.Anthropic(api_key=api_key)
    message = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=1024,
        messages=[{"role": "user", "content": PROMPT_TEMPLATE.format(transcript=transcript)}],
    )
    return message.content[0].text.strip()


def summarize(transcript: str, provider: str) -> str:
    if provider == "openai":
        return summarize_openai(transcript)
    elif provider == "anthropic":
        return summarize_anthropic(transcript)
    else:
        raise ValueError(f"Unknown provider: {provider}")
