"""Delegate sample SQL to NL2SQL, read its CSV, and write an analysis report."""

import argparse
import asyncio
from pathlib import Path

from run import QUESTION, prepare_case, verify_result_file

from dataagent import create_agent


async def main(env_file: Path | None) -> None:
    thread_id = "sqlite-parent-tutorial"
    runtime, session = prepare_case(env_file, config_name="config.parent.yaml", thread_id=thread_id)
    report_file = session.outputs / "regional-sales.md"
    question = QUESTION + (
        " Delegate this database query once to the nl2sql subagent through the task tool. "
        "Read its resulting CSV file, then explain which region leads and how the regions compare. "
        "Use amount_cents as cents throughout. "
        f"Write the analysis as a Markdown report to {report_file}. "
        "Do not query the database through shell commands or generate a replacement CSV yourself. "
        "Finally summarize your findings and give the CSV and report paths."
    )
    async with create_agent(runtime) as agent:
        result = await agent.ainvoke(
            {"messages": [("user", question)]},
            config={"configurable": {"thread_id": thread_id}},
        )
    files = list((session.outputs / "nl2sql").glob("*.csv"))
    if len(files) != 1:
        raise SystemExit(
            f"Expected one NL2SQL query result, found {len(files)} in {session.outputs}"
        )
    verify_result_file(files[0])
    if not report_file.is_file() or not report_file.read_text(encoding="utf-8").strip():
        raise SystemExit(f"DataAgent did not write a nonempty analysis report: {report_file}")
    print(f"Report: {report_file}")
    print(f"Analysis: {result['messages'][-1].content}")
    print("Verified: analysis report is nonempty")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--env-file", type=Path, help="Env file containing LLM_* settings")
    asyncio.run(main(parser.parse_args().env_file))