"""One-call setup: TracerProvider + FilePerTraceExporter + auto-instrumentation."""

from __future__ import annotations

import os

from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor

from minitrail._exporter import FilePerTraceExporter
from minitrail._markdown_exporter import MarkdownTraceExporter


def setup(
    service_name: str = "minitrail",
    logs_dir: str = "logs",
    markdown: bool = False,
    frameworks: list[str] | None = None,
    instrument: bool = True,
    pricing: str | None = None,
) -> TracerProvider:
    """Initialise OTel tracing with file-per-trace export and framework auto-instrumentation.

    Must be called **before** any framework imports so the instrumentor can
    patch them.

    Directory layout::

        logs/
          json/          <- machine-readable JSON traces (always)
          human_readable/<- Markdown traces + images     (when markdown=True)
            images/

    Args:
        service_name: Value written into the ``service.name`` OTel resource attribute.
        logs_dir: Root directory for trace output.
        markdown: If ``True``, also write human-readable ``.md`` files with
            extracted images.  Content is appended live as spans complete;
            the summary header is prepended on ``force_flush()`` / ``shutdown()``.
        frameworks: List of framework names to instrument (e.g. ``["langchain"]``).
            If ``None``, auto-detect all installed frameworks.
        instrument: If ``False``, skip framework instrumentation entirely.
        pricing: Optional path to a ``minitrail_pricing.toml`` file with custom
            model prices.  Models defined there override or extend the defaults.

    Returns:
        The configured ``TracerProvider`` — call ``provider.force_flush()``
        and ``provider.shutdown()`` at the end of your script to ensure all
        spans are written.
    """
    from minitrail._pricing import set_user_pricing

    set_user_pricing(pricing)
    json_dir = os.path.join(logs_dir, "json")

    resource = Resource.create({"service.name": service_name})
    provider = TracerProvider(resource=resource)
    provider.add_span_processor(SimpleSpanProcessor(FilePerTraceExporter(json_dir)))

    if markdown:
        md_dir = os.path.join(logs_dir, "human_readable")
        provider.add_span_processor(SimpleSpanProcessor(MarkdownTraceExporter(md_dir)))

    trace.set_tracer_provider(provider)

    if instrument:
        from minitrail._detect import auto_instrument

        auto_instrument(frameworks)

    return provider
