"""docs-copilot: RAG over the learn-with-project lessons, served over HTTP and MCP, fully observable.

    from copilot import build
    copilot = build()                       # offline model unless OPENAI_API_KEY is set
    print(copilot.ask("What is keyset pagination?").text)
"""

from __future__ import annotations

import os
import time
from pathlib import Path

from .answer import Answer, Copilot, ExtractiveModel, OpenAIModel
from .index import HybridIndex, LsaEmbedder
from .ingest import Chunk, load_chunks
from .telemetry import Telemetry

__all__ = ["Answer", "Chunk", "Copilot", "ExtractiveModel", "HybridIndex", "OpenAIModel", "Telemetry",
           "build", "default_model", "load_chunks"]


def default_model():
    """The real model when a key is configured, otherwise the offline stand-in."""
    if os.environ.get("OPENAI_API_KEY"):
        from openai import OpenAI
        return OpenAIModel(OpenAI(timeout=30.0, max_retries=2), model=os.environ.get("COPILOT_MODEL", "gpt-5.6-luna"))
    return ExtractiveModel()


def build(root: Path | None = None, courses: list[str] | None = None, model=None,
          telemetry: Telemetry | None = None) -> Copilot:
    started = time.perf_counter()
    telemetry = telemetry or Telemetry.setup()
    with telemetry.tracer.start_as_current_span("copilot.build_index") as span:
        chunks = load_chunks(root, courses)
        index = HybridIndex(chunks, LsaEmbedder())
        span.set_attributes({"app.index.chunks": len(chunks),
                             "app.index.seconds": round(time.perf_counter() - started, 2)})
    return Copilot(index, model or default_model(), telemetry)
