"""Data export/delete CLI commands — complyform config export-data/delete-data.

GDPR Art. 17/20 data management via hosted API.
"""

from __future__ import annotations

import sys
from pathlib import Path
from typing import Annotated

import typer


def export_data_cmd(
    ctx: typer.Context,
    api_key: Annotated[
        str | None,
        typer.Option("--api-key", help="API key override"),
    ] = None,
    output: Annotated[
        Path,
        typer.Option("--output", help="Local directory for export ZIP"),
    ] = Path("./export"),
    wait: Annotated[
        bool,
        typer.Option("--wait", help="Block until ready and download"),
    ] = False,
) -> None:
    """Request export of all hosted data (Team+)."""
    import httpx

    resolved_key = api_key or _resolve_api_key()
    if not resolved_key:
        typer.echo(
            "API key required. Use --api-key or set COMPLYFORM_API_KEY.",
            err=True,
        )
        raise typer.Exit(code=1)

    try:
        with httpx.Client(timeout=30) as client:
            resp = client.post(
                "https://api.complyform.dev/v1/data/export",
                headers={"X-API-Key": resolved_key},
            )
            resp.raise_for_status()
            data = resp.json()

        typer.echo(f"Export started. Status: {data.get('status')}", err=True)
        if data.get("estimated_minutes"):
            typer.echo(
                f"Estimated time: {data['estimated_minutes']} minutes",
                err=True,
            )

        if wait:
            typer.echo(
                "Waiting for export to complete... (check email for download link)",
                err=True,
            )

    except httpx.HTTPStatusError as exc:
        if exc.response.status_code == 429:
            typer.echo(
                "Export rate limited — try again in 24 hours.",
                err=True,
            )
        else:
            typer.echo(
                f"Export request failed: {exc.response.status_code}",
                err=True,
            )
        raise typer.Exit(code=1) from exc
    except Exception as exc:
        typer.echo(f"Export request failed: {exc}", err=True)
        raise typer.Exit(code=1) from exc


def delete_data_cmd(
    ctx: typer.Context,
    api_key: Annotated[
        str | None,
        typer.Option("--api-key", help="API key override"),
    ] = None,
    confirm: Annotated[
        bool,
        typer.Option("--confirm", help="Skip interactive confirmation"),
    ] = False,
) -> None:
    """Request deletion of all hosted data. Irreversible."""
    import httpx

    resolved_key = api_key or _resolve_api_key()
    if not resolved_key:
        typer.echo(
            "API key required. Use --api-key or set COMPLYFORM_API_KEY.",
            err=True,
        )
        raise typer.Exit(code=1)

    if not confirm:
        if not sys.stdin.isatty():
            typer.echo(
                "Use --confirm in non-interactive mode.",
                err=True,
            )
            raise typer.Exit(code=1)

        typer.echo(
            "WARNING: This will permanently delete all your hosted data.",
            err=True,
        )
        typed = typer.prompt("Type DELETE to confirm")
        if typed != "DELETE":
            typer.echo("Aborted.", err=True)
            raise typer.Exit(code=0)

    try:
        with httpx.Client(timeout=60) as client:
            resp = client.post(
                "https://api.complyform.dev/v1/data/delete",
                headers={"X-API-Key": resolved_key},
                json={"confirm": True},
            )
            resp.raise_for_status()
            data = resp.json()

        typer.echo(
            f"Deletion started. Status: {data.get('status')}",
            err=True,
        )

    except httpx.HTTPStatusError as exc:
        typer.echo(
            f"Delete request failed: {exc.response.status_code}",
            err=True,
        )
        raise typer.Exit(code=1) from exc
    except Exception as exc:
        typer.echo(f"Delete request failed: {exc}", err=True)
        raise typer.Exit(code=1) from exc


def _resolve_api_key() -> str | None:
    """Resolve API key from environment or config."""
    import os

    key = os.environ.get("COMPLYFORM_API_KEY")
    if key:
        return key

    try:
        from complyform.core.config import load_config, resolve_config_path

        config = load_config(resolve_config_path())
        return config.api_key
    except Exception:
        return None
