"""Query commands for QRM CLI."""

from pathlib import Path
import typer
from .client import QrmClient, QrmClientError
from .commands_shared import format_api_datetime, OutputFormat, emit, load_state_or_exit
import datetime

# Typer app for query subcommands
query_app = typer.Typer(help="Query QRM database (read-only SQL queries)")


@query_app.command("results")
def results(
    config_path: Path = typer.Option(
        None,
        "--config-path",
        help="Override the location of the login.json file.",
    ),
    base_url: str = typer.Option(
        None,
        "--base-url",
        help="Override the base URL stored in the config (useful for testing).",
    ),
    insecure: bool = typer.Option(
        False,
        "--insecure",
        help="Disable TLS verification when contacting QRM.",
    ),
    start: str = typer.Option(
        None,
        "--start",
        help="Start datetime (default: today 00:00:00)",
    ),
    stop: str = typer.Option(
        None,
        "--stop",
        help="Stop datetime (default: today 23:59:59)",
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.rich,
        "--output",
        "-o",
        case_sensitive=False,
        help="Choose output format: rich (default) or json.",
    ),
) -> None:
    """Retrieve production test results for a date range (default: today)."""
    state = load_state_or_exit(config_path)
    client = QrmClient(
        base_url=base_url or str(state.base_url),
        verify_tls=not insecure and state.verify_tls,
    )

    now = datetime.datetime.now(datetime.timezone.utc)
    try:
        if start is None:
            start_dt = now.replace(hour=0, minute=0, second=0, microsecond=0)
        else:
            start_dt = datetime.datetime.fromisoformat(start)
        if stop is None:
            stop_dt = now.replace(hour=23, minute=59, second=59, microsecond=0)
        else:
            stop_dt = datetime.datetime.fromisoformat(stop)
    except ValueError as exc:
        typer.secho(f"Invalid date format: {exc}", fg=typer.colors.RED)
        raise typer.Exit(code=1) from exc

    sql = (
        "SELECT "
        "rs.Id, rs.UUID, rs.StartDateTime, rs.StopDateTime, rs.TestSocketIndex, rs.LogFileURL, rs.Comment, rs.IdentifierTag, rs.InsertDateTime, rs.Yield, "
        "uut.SerialNumber, "
        "tp.Name AS TestProgramName, "
        "st.Name AS StationName, "
        "op.Name AS OperatorName, "
        "oc.Outcome, "
        "seq.Name AS SequenceName, "
        "tt.Name AS TestTypeName, "
        "rsn.Name AS ResultSetName, "
        "uutype.Name AS UUTTypeName "
        "FROM tResultSet rs "
        "LEFT JOIN tUUT uut ON rs.tUUT_Id = uut.Id "
        "LEFT JOIN tTestProgram tp ON rs.tTestProgram_Id = tp.Id "
        "LEFT JOIN tStation st ON rs.tStation_Id = st.Id "
        "LEFT JOIN tOperator op ON rs.tOperator_Id = op.Id "
        "LEFT JOIN tOutcome oc ON rs.tOutcome_Id = oc.Id "
        "LEFT JOIN tSequence seq ON rs.tSequence_Id = seq.Id "
        "LEFT JOIN tTestType tt ON rs.tTestType_Id = tt.Id "
        "LEFT JOIN tResultSetName rsn ON rs.tResultSetName_Id = rsn.Id "
        "LEFT JOIN tUUTType uutype ON rs.tUUTTypeId = uutype.Id "
        "WHERE rs.StartDateTime >= :start AND rs.StartDateTime <= :stop "
        "ORDER BY rs.StartDateTime ASC"
    )
    params = {
        "start": format_api_datetime(start_dt),
        "stop": format_api_datetime(stop_dt),
    }

    try:
        payload = client.export_sql(token=state.token, query=sql, format="json", parameters=params)
    except QrmClientError as exc:
        typer.secho(f"query failed: {exc}", fg=typer.colors.RED)
        raise typer.Exit(code=1) from exc

    if output is OutputFormat.rich:
        from .commands_shared import render_results_status, console

        table = render_results_status(payload)
        console.print(table)
    else:
        emit(payload, output)


# Query all test results for a given serial number


@query_app.command("serial")
def serial(
    serial_number: str = typer.Argument(..., help="Serial number to query for."),
    config_path: Path = typer.Option(
        None,
        "--config-path",
        help="Override the location of the login.json file.",
    ),
    base_url: str = typer.Option(
        None,
        "--base-url",
        help="Override the base URL stored in the config (useful for testing).",
    ),
    insecure: bool = typer.Option(
        False,
        "--insecure",
        help="Disable TLS verification when contacting QRM.",
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.rich,
        "--output",
        "-o",
        case_sensitive=False,
        help="Choose output format: rich (default) or json.",
    ),
) -> None:
    """Retrieve all test results for a given serial number."""
    state = load_state_or_exit(config_path)
    client = QrmClient(
        base_url=base_url or str(state.base_url),
        verify_tls=not insecure and state.verify_tls,
    )

    sql = (
        "SELECT "
        "rs.Id, rs.UUID, rs.StartDateTime, rs.StopDateTime, rs.TestSocketIndex, rs.LogFileURL, rs.Comment, rs.IdentifierTag, rs.InsertDateTime, rs.Yield, "
        "uut.SerialNumber, "
        "tp.Name AS TestProgramName, "
        "st.Name AS StationName, "
        "op.Name AS OperatorName, "
        "oc.Outcome, "
        "seq.Name AS SequenceName, "
        "tt.Name AS TestTypeName, "
        "rsn.Name AS ResultSetName, "
        "uutype.Name AS UUTTypeName "
        "FROM tResultSet rs "
        "LEFT JOIN tUUT uut ON rs.tUUT_Id = uut.Id "
        "LEFT JOIN tTestProgram tp ON rs.tTestProgram_Id = tp.Id "
        "LEFT JOIN tStation st ON rs.tStation_Id = st.Id "
        "LEFT JOIN tOperator op ON rs.tOperator_Id = op.Id "
        "LEFT JOIN tOutcome oc ON rs.tOutcome_Id = oc.Id "
        "LEFT JOIN tSequence seq ON rs.tSequence_Id = seq.Id "
        "LEFT JOIN tTestType tt ON rs.tTestType_Id = tt.Id "
        "LEFT JOIN tResultSetName rsn ON rs.tResultSetName_Id = rsn.Id "
        "LEFT JOIN tUUTType uutype ON rs.tUUTTypeId = uutype.Id "
        "WHERE uut.SerialNumber = :serial_number "
        "ORDER BY rs.StartDateTime ASC"
    )
    params = {
        "serial_number": serial_number,
    }

    try:
        payload = client.export_sql(token=state.token, query=sql, format="json", parameters=params)
    except QrmClientError as exc:
        typer.secho(f"query failed: {exc}", fg=typer.colors.RED)
        raise typer.Exit(code=1) from exc

    if output is OutputFormat.rich:
        from .commands_shared import render_serial_status, console

        table = render_serial_status(payload)
        console.print(table)
    else:
        emit(payload, output)


query = results

__all__ = ["query_app", "query"]
