from __future__ import annotations
"""Simplified one-shot: YouTube URL -> transcript text -> LLM summary (optional)."""
from typing import Optional
from .ingest.youtube import ingest_youtube
from .models.simple import SimpleGranule
from .llm.card_extract import llm_card_json_from_transcript
from .llm.video_card import llm_video_insight_from_transcript
from .models.video_insight import VideoInsightCardPayload
from .config import settings

SUMMARY_PROMPT = (
    "You are a concise summarizer. Provide a clear 3-5 sentence summary of the transcript focusing on key ideas. "
    "Keep under 120 words. Output only the summary text."
)

def summarize_text_llm(text: str) -> tuple[Optional[str], Optional[str], Optional[str]]:
    if not settings.llm_enabled:
        return None, None, None
    try:
        from .llm.base import get_provider, LLMRequest  # type: ignore
    except Exception:
        return None, None, "provider_import_error"
    provider = get_provider(settings.llm_provider)
    if not provider:
        return None, None, "no_provider"
    req = LLMRequest(prompt=f"{SUMMARY_PROMPT}\nTranscript:\n{text[:32000]}")
    try:
        resp = provider.complete(req)
        return resp.text.strip(), req.model or settings.llm_model, None
    except Exception as e:  # pragma: no cover
        return None, None, str(e)


def simple_youtube_summary(url_or_id: str) -> SimpleGranule:
    doc = ingest_youtube(url_or_id)
    # If transcript placeholder, skip LLM
    placeholder = doc.text.startswith('[NO TRANSCRIPT AVAILABLE')
    summary, model_used, err = ("No transcript is available to summarize.", None, None) if placeholder else summarize_text_llm(doc.text)
    return SimpleGranule(
        source=url_or_id,
        transcript=doc.text,
        text_chars=len(doc.text),
        summary=summary,
        model_used=model_used,
        error=err,
    )

def simple_youtube_card(url_or_id: str):
    """Return a transcript insight card JSON (LLM if enabled, else heuristic)."""
    doc = ingest_youtube(url_or_id)
    return llm_card_json_from_transcript(doc.text, title=getattr(doc.meta, 'title', None) if hasattr(doc, 'meta') else None)


def video_insight_card(url_or_id: str, title: str | None = None) -> VideoInsightCardPayload:
    """High-level: YouTube URL/ID -> VideoInsightCardPayload (LLM or fallback).

    User can optionally supply a title; otherwise we attempt to auto-fetch via oEmbed.
    """
    doc = ingest_youtube(url_or_id, title=title)
    if "youtube.com" in url_or_id or "youtu.be" in url_or_id:
        url = url_or_id
    else:
        url = f"https://www.youtube.com/watch?v={url_or_id}"
    # StructuredDoc has source meta
    title = getattr(doc.source, 'title', None) if hasattr(doc, 'source') else None
    return llm_video_insight_from_transcript(
        doc.text,
        url=url,
        title=title,
    )


def text_video_insight_card(text: str, *, title: str | None = None, url: str | None = None) -> VideoInsightCardPayload:
    """Generate a VideoInsightCardPayload from raw transcript text (no fetch).

    Useful when you already have a transcript file or arbitrary notes. A synthetic
    URL and ID are created if none supplied.
    """
    synthetic_url = url or "local://text"
    synthetic_id = "LOCALTXT1234"  # 11 chars not required but keep style
    return llm_video_insight_from_transcript(
        text,
        url=synthetic_url,
        title=title or "Transcript",
        video_id=synthetic_id,
    )
