from datetime import timedelta
from .models.core import StructuredDoc, GranularitySpec, AtomGraph
from .models.tiers import MicroLearning
from .ingest.article import ingest_article
from .ingest.youtube import ingest_youtube
from .process.atoms import dissect_text_to_atoms
from .validate.dedup import dedup
from .compose.pack import pack_to_duration
from .compose.map_tiers import to_micro

def ingest(source:str, kind:str) -> StructuredDoc:
    if kind == "youtube":
        return ingest_youtube(source)
    return ingest_article(source)

def dissect(doc: StructuredDoc, spec: GranularitySpec) -> AtomGraph:
    graph = dissect_text_to_atoms(doc.text, spec)
    graph.atoms = dedup(graph.atoms)
    return graph

def expand(graph: AtomGraph, spec: GranularitySpec) -> MicroLearning:
    target = spec.target_duration or timedelta(seconds=55)
    chosen = pack_to_duration(graph.atoms, target)
    return to_micro(chosen, name="Auto Unit", target=target)

def stream(graph: AtomGraph, pace: float, until: float):
    total = 0.0; i = 0
    while total < until and i < len(graph.atoms):
        yield {"index": i, "text": graph.atoms[i].text[:200]}
        total += pace; i += 1
