from __future__ import annotations

from typing import Optional

import typer

from dattos_cli.client import ApiError
from dattos_cli.main import get_client, handle_api_error
from dattos_cli.output import print_json

app = typer.Typer(help="Query matching/reconciliation results.", no_args_is_help=True)

BASE = "/api/Analysis/{aid}/matching-executions/{lid}/{did}"


@app.command("get")
def get_execution(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    load_id: int = typer.Argument(help="Analysis load ID"),
    dataset_id: int = typer.Argument(help="Dataset ID"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Get matching execution info."""
    client = get_client(folder_id)
    path = BASE.format(aid=analysis_id, lid=load_id, did=dataset_id)
    try:
        result = client.get(path)
        print_json(result)
    except ApiError as e:
        handle_api_error(e)


@app.command("status")
def totals_by_status(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    load_id: int = typer.Argument(help="Analysis load ID"),
    dataset_id: int = typer.Argument(help="Dataset ID"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Get matching totals by status (matched, unmatched, etc.)."""
    client = get_client(folder_id)
    path = BASE.format(aid=analysis_id, lid=load_id, did=dataset_id) + "/totals-by-status"
    try:
        result = client.post(path, json={"filterIds": []})
        print_json(result)
    except ApiError as e:
        handle_api_error(e)


@app.command("summary")
def summarize(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    load_id: int = typer.Argument(help="Analysis load ID"),
    dataset_id: int = typer.Argument(help="Dataset ID"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Get matching summary report."""
    client = get_client(folder_id)
    path = BASE.format(aid=analysis_id, lid=load_id, did=dataset_id) + "/summarize"
    try:
        result = client.post(path, json={"filterIds": []})
        print_json(result)
    except ApiError as e:
        handle_api_error(e)
