"""High-level one-shot pipeline helpers.

Provides a convenience function to ingest a YouTube URL (or ID), dissect,
optionally enrich atoms, expand to a microlearning unit, and prepare a
single composite JSON-safe structure for UI / API consumers.
"""
from __future__ import annotations
from datetime import timedelta
from typing import Any, Dict, Optional
from .api import ingest, dissect, expand
from .models.core import GranularitySpec, StructuredDoc, AtomGraph
from .config import settings
from .process.segment_v2 import improved_segments, batch_summarize_segments
from .models.insight import analyze_transcript
try:  # optional LLM enrichment for insight
    from .llm.insight_extract import llm_analyze_transcript
except Exception:  # pragma: no cover
    llm_analyze_transcript = None  # type: ignore
try:
    from .llm.enrich import enrich_atoms
except Exception:  # pragma: no cover
    enrich_atoms = None  # type: ignore


def process_youtube(
    url_or_id: str,
    max_tokens_per_atom: int = 80,
    atom_types: Optional[list[str]] = None,
    target_seconds: float = 90.0,
    enrich: bool = True,
    enrich_limit: int = 25,
) -> Dict[str, Any]:
    """Run end-to-end pipeline for a YouTube video.

    Returns dict with keys: doc, graph, unit, enrichment_meta, segments, segment_summaries, insight_card.
    Enrichment is optional and side-channel; original atoms are unmodified.
    """
    doc: StructuredDoc = ingest(url_or_id, kind="youtube")
    dissect_spec = GranularitySpec(max_tokens_per_atom=max_tokens_per_atom, atom_types=atom_types)
    graph: AtomGraph = dissect(doc, dissect_spec)
    unit_spec = GranularitySpec(target_duration=timedelta(seconds=target_seconds))
    unit = expand(graph, unit_spec)

    enrichment_payload: list[dict] = []
    if enrich and settings.llm_enabled and enrich_atoms:
        try:
            enrichment_payload = enrich_atoms(graph.atoms[:enrich_limit], limit=enrich_limit)
        except Exception:  # pragma: no cover
            enrichment_payload = []

    # Improved segmentation & summaries (independent of atom enrichment)
    segs = improved_segments(doc.text)
    seg_summaries = batch_summarize_segments(segs)

    # Lightweight insight card (heuristic for now)
    # Prefer LLM insight if enabled, else heuristic
    insight_card_obj = None
    if llm_analyze_transcript:
        try:
            insight_card_obj = llm_analyze_transcript(
                doc.text,
                video_title=getattr(doc.meta, 'title', None) if hasattr(doc, 'meta') else None,
                channel_name=None,
            )
        except Exception:  # pragma: no cover
            insight_card_obj = None
    if not insight_card_obj:
        insight_card_obj = analyze_transcript(
            doc.text,
            video_title=getattr(doc.meta, 'title', None) if hasattr(doc, 'meta') else None,
        )

    return {
        "doc": doc.model_dump(),
        "graph": graph.model_dump(),
        "unit": getattr(unit, "model_dump", lambda: unit)(),
        "enrichment_meta": enrichment_payload,
        "segments": [s.model_dump() for s in segs],
        "segment_summaries": [s.model_dump() for s in seg_summaries],
    "insight_card": insight_card_obj.to_card(),
        "params": {
            "max_tokens_per_atom": max_tokens_per_atom,
            "atom_types": atom_types,
            "target_seconds": target_seconds,
            "enrich": enrich,
            "enrich_limit": enrich_limit,
        },
    }
