from __future__ import annotations

import os
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="Generate and download reports.", no_args_is_help=True)


@app.command("generate")
def generate(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    load_id: int = typer.Option(..., "--load-id", help="Analysis load ID"),
    dataset_id: int = typer.Option(..., "--dataset-id", help="Dataset ID"),
    format: str = typer.Option("csv", "--format", "-f", help="Export format: csv or xlsx"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Generate a report export (async — returns report ID to poll)."""
    client = get_client(folder_id)
    ext_map = {"csv": 0, "xlsx": 1}
    ext = ext_map.get(format.lower(), 0)
    body = {
        "AnalysisLoadId": load_id,
        "AnalysisDatasetId": dataset_id,
        "ExportFileExtension": ext,
        "SearchCommand": {"offsetInfo": {"page": 1, "pageSize": 1000000}},
    }
    try:
        result = client.post(f"/api/Analysis/{analysis_id}/reports/generate", json=body)
        print_json(result)
    except ApiError as e:
        handle_api_error(e)


@app.command("status")
def status(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    load_id: int = typer.Option(..., "--load-id", help="Analysis load ID"),
    dataset_id: int = typer.Option(..., "--dataset-id", help="Dataset ID"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Check the status of a report generation."""
    client = get_client(folder_id)
    try:
        result = client.get(
            f"/api/Analysis/{analysis_id}/reports/by-load/{load_id}/{dataset_id}"
        )
        print_json(result)
    except ApiError as e:
        handle_api_error(e)


@app.command("download")
def download(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    report_id: int = typer.Argument(help="Report ID"),
    output: str = typer.Option("report_output", "--output", "-o", help="Output file path"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Download a generated report file."""
    client = get_client(folder_id)
    try:
        response = client.download(
            f"/api/Analysis/{analysis_id}/reports/{report_id}/download"
        )
        content_disp = response.headers.get("content-disposition", "")
        filename = output
        if "filename=" in content_disp:
            raw_name = content_disp.split("filename=")[-1].strip('"')
            # Sanitize: strip path components to prevent path traversal
            sanitized = os.path.basename(raw_name)
            if sanitized:
                filename = sanitized
        with open(filename, "wb") as f:
            f.write(response.content)
        print_json({"status": "downloaded", "file": filename})
    except ApiError as e:
        handle_api_error(e)
