# src/dattos_cli/commands/loads.py
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, validate_date

app = typer.Typer(help="Query analysis loads and reference dates.", no_args_is_help=True)


@app.command("get")
def get_load(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    reference_date: str = typer.Argument(help="Reference date (YYYY-MM-DD)"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Get the analysis load for a specific reference date."""
    client = get_client(folder_id)
    try:
        result = client.get(f"/api/Analysis/{analysis_id}/load/{validate_date(reference_date)}")
        print_json(result)
    except ApiError as e:
        handle_api_error(e)


@app.command("list-dates")
def list_dates(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    date_from: str = typer.Option(..., "--from", help="Start date (YYYY-MM-DD)"),
    date_to: str = typer.Option(..., "--to", help="End date (YYYY-MM-DD)"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """List reference dates that have loaded data."""
    client = get_client(folder_id)
    try:
        result = client.get(
            f"/api/Analysis/{analysis_id}/load/LoadedDates/{validate_date(date_from, 'from')}/{validate_date(date_to, 'to')}"
        )
        print_json(result)
    except ApiError as e:
        handle_api_error(e)


@app.command("views")
def get_views(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    load_id: int = typer.Argument(help="Analysis load ID"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """List available views for a load."""
    client = get_client(folder_id)
    try:
        result = client.get(f"/api/Analysis/{analysis_id}/load/{load_id}/views")
        print_json(result)
    except ApiError as e:
        handle_api_error(e)
