"""Run the shipped SQLite cases with real SQL/tools and an offline model."""

import importlib.util
import json
from pathlib import Path

import pytest
from conftest import ScriptedModel, call
from langchain_core.messages import AIMessage

from dataagent import create_agent

EXAMPLES = Path(__file__).resolve().parents[1] / "examples/sqlite-tutorial"
SQL = (
    "SELECT region, SUM(amount_cents) AS total_cents FROM orders "
    "GROUP BY region ORDER BY total_cents DESC, region ASC"
)
REPORT = "# Regional sales\n\nNorth leads with 4500 cents; south has 2300 and east 800.\n"


@pytest.mark.parametrize("script_name", ["run.py", "run_parent.py"])
async def test_sqlite_case_runs_query_and_verifies_real_outputs(
    tmp_path, monkeypatch, capsys, script_name
):
    monkeypatch.syspath_prepend(str(EXAMPLES))
    import run as sample_data

    parent = script_name == "run_parent.py"
    spec = importlib.util.spec_from_file_location("sqlite_tutorial_example", EXAMPLES / script_name)
    tutorial = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(tutorial)
    directory = tmp_path / "sample"
    directory.mkdir()
    monkeypatch.setattr(sample_data, "mkdtemp", lambda **kwargs: str(directory))
    if not parent:
        monkeypatch.setattr(tutorial, "mkdtemp", lambda **kwargs: str(directory))
    for key in ("DATAAGENT_TUTORIAL_SQLITE", "DATAAGENT_TUTORIAL_SCHEMA"):
        monkeypatch.setenv(key, "unused-before-example")
    monkeypatch.setenv("LLM_MODEL", "offline-tutorial-model")
    monkeypatch.setenv("LLM_BASE_URL", "https://example.invalid/v1")
    monkeypatch.setenv("LLM_API_KEY", "offline-example-key")
    thread = "sqlite-parent-tutorial" if parent else "sqlite-tutorial"
    outputs = directory / "home/outputs/default" / thread

    class TutorialModel(ScriptedModel):
        def _generate(self, messages, *args, **kwargs):
            if parent and self.cursor == 2:
                (csv_file,) = (outputs / "nl2sql").glob("*.csv")
                self.responses[2] = call("read_file", {"file_path": str(csv_file)})
            return super()._generate(messages, *args, **kwargs)

    responses = [AIMessage(content=f"```sql\n{SQL}\n```")]
    if parent:
        responses = [
            call("task", {"subagent_type": "nl2sql", "description": sample_data.QUESTION}),
            *responses,
            AIMessage(content="replaced with the generated CSV read"),
            call(
                "write_file", {"file_path": str(outputs / "regional-sales.md"), "content": REPORT}
            ),
            AIMessage(content="North leads. See the CSV and regional-sales.md for the analysis."),
        ]
    model = TutorialModel(responses=responses)
    monkeypatch.setattr(
        tutorial, "create_agent", lambda runtime: create_agent(runtime, model=model)
    )
    await tutorial.main(None)

    stdout = capsys.readouterr().out
    assert f"Thread: {thread}" in stdout
    assert "Verified: 3 region totals" in stdout
    assert model.cursor == len(responses)
    (csv_file,) = (outputs / "nl2sql").glob("*.csv")
    metadata = json.loads(csv_file.with_suffix(".meta.json").read_text())
    assert metadata["sql"] == SQL and metadata["row_count"] == 3
    assert csv_file.read_text().splitlines() == [",".join(row) for row in sample_data.EXPECTED_CSV]
    assert not (directory / "home/runtime/checkpoints.sqlite").exists()
    trace_files = list(
        (directory / "home/runtime/users/default/sessions" / thread / "traces").glob("*.json")
    )
    assert trace_files
    spans = [
        span
        for path in trace_files
        for resource in json.loads(path.read_text())["resourceSpans"]
        for scope in resource["scopeSpans"]
        for span in scope["spans"]
    ]
    names = {span["name"] for span in spans}
    if parent:
        assert {"task", "nl2sql", "read_file", "write_file"} <= names
        assert (outputs / "regional-sales.md").read_text() == REPORT
        assert "Verified: analysis report is nonempty" in stdout
        # The parent receives the actual CSV tool output before writing its report.
        assert "north,4500" in str(model.requests[3][-1].content)
    else:
        assert "nl2sql" in names and "task" not in names
        assert not (outputs / "regional-sales.md").exists()