"""Pipeline orchestrator: LLM → validate → render SQL → return results.

Architecture: the LLM generates structured JSON via Structured Outputs,
Python validates business rules, then deterministically renders SQL.
No LLM involvement in SQL generation.
"""

import json
import time

from models import MantaraSchema
from llm_client import generate_schema
from business_validator import validate_all
from renderer import render_sql


def generate(user_input: str, model: str | None = None) -> dict:
    """Full pipeline: call LLM → validate JSON → render SQL → return results.

    Returns dict with keys:
        schema: MantaraSchema object
        json_str: pretty-printed JSON string (with $schema marker)
        sql_str: deterministically rendered PostgreSQL DDL
        validation: {errors: list[str], is_valid: bool}
        elapsed_seconds: float
    """
    start = time.time()

    # Step 1: LLM generates structured JSON via Structured Outputs
    schema = generate_schema(user_input, model=model)

    # Step 2: Validate business rules
    validation = validate_all(schema)

    # Step 3: Deterministically render SQL from validated JSON
    sql_str = render_sql(schema)

    # Step 4: Serialize JSON for output (with $schema marker)
    json_str = json.dumps(schema.to_json_dict(), indent=2)

    elapsed = round(time.time() - start, 1)

    return {
        "schema": schema,
        "json_str": json_str,
        "sql_str": sql_str,
        "validation": validation,
        "elapsed_seconds": elapsed,
    }
