"""CLI for acta-sql: load, query, and summarize Acta receipt DAGs."""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path

from . import create_db, load_receipts, query


DEFAULT_DB = "acta.duckdb"


def cmd_load(args: argparse.Namespace) -> None:
    """Load receipts from a file into a DuckDB database."""
    receipts = load_receipts(args.file)
    db_path = args.db or DEFAULT_DB
    conn = create_db(receipts, db_path=db_path)
    count = conn.execute("SELECT COUNT(*) FROM receipts").fetchone()[0]
    edge_count = conn.execute("SELECT COUNT(*) FROM edges").fetchone()[0]
    conn.close()
    print(f"Loaded {count} receipts and {edge_count} edges into {db_path}")


def cmd_query(args: argparse.Namespace) -> None:
    """Run a SQL query against an existing acta.duckdb."""
    import duckdb

    db_path = args.db or DEFAULT_DB
    if not Path(db_path).exists():
        print(f"Error: {db_path} not found. Run 'acta-sql load <file>' first.", file=sys.stderr)
        sys.exit(1)

    conn = duckdb.connect(db_path, read_only=True)
    try:
        result = conn.execute(args.sql)
        columns = [desc[0] for desc in result.description]
        rows = result.fetchall()
    finally:
        conn.close()

    if not rows:
        print("(no results)")
        return

    # Simple table output
    col_widths = [len(c) for c in columns]
    for row in rows:
        for i, val in enumerate(row):
            col_widths[i] = max(col_widths[i], len(str(val)))

    header = " | ".join(c.ljust(col_widths[i]) for i, c in enumerate(columns))
    separator = "-+-".join("-" * w for w in col_widths)
    print(header)
    print(separator)
    for row in rows:
        print(" | ".join(str(v).ljust(col_widths[i]) for i, v in enumerate(row)))


def cmd_summary(args: argparse.Namespace) -> None:
    """Print a summary of the receipt database."""
    import duckdb

    db_path = args.db or DEFAULT_DB
    if not Path(db_path).exists():
        print(f"Error: {db_path} not found. Run 'acta-sql load <file>' first.", file=sys.stderr)
        sys.exit(1)

    conn = duckdb.connect(db_path, read_only=True)
    try:
        total = conn.execute("SELECT COUNT(*) FROM receipts").fetchone()[0]
        deny_count = conn.execute(
            "SELECT COUNT(*) FROM receipts WHERE decision = 'deny'"
        ).fetchone()[0]
        tools = conn.execute(
            "SELECT COUNT(DISTINCT tool_name) FROM receipts WHERE tool_name IS NOT NULL"
        ).fetchone()[0]
        time_range = conn.execute(
            "SELECT MIN(timestamp), MAX(timestamp) FROM receipts WHERE timestamp != ''"
        ).fetchone()
    finally:
        conn.close()

    print(f"Receipts:     {total}")
    print(f"Denied:       {deny_count}")
    print(f"Unique tools: {tools}")
    if time_range and time_range[0]:
        print(f"Time range:   {time_range[0]} to {time_range[1]}")
    else:
        print("Time range:   (no timestamps)")


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="acta-sql",
        description="Query Veritas Acta receipt DAGs with SQL",
    )
    parser.add_argument(
        "--db", default=None, help=f"Path to DuckDB file (default: {DEFAULT_DB})"
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    # load
    p_load = subparsers.add_parser("load", help="Load receipts into DuckDB")
    p_load.add_argument("file", help="Path to .json or .jsonl receipt file")

    # query
    p_query = subparsers.add_parser("query", help="Run a SQL query")
    p_query.add_argument("sql", help="SQL query string")

    # summary
    subparsers.add_parser("summary", help="Print receipt summary")

    args = parser.parse_args()

    if args.command == "load":
        cmd_load(args)
    elif args.command == "query":
        cmd_query(args)
    elif args.command == "summary":
        cmd_summary(args)


if __name__ == "__main__":
    main()
