from __future__ import annotations

from typing import Optional

import typer

from aegro.cli._config import get_client, require_farm
from aegro.cli._errors import handle_error
from aegro.cli._output import OutputFormat, format_output
from aegro.validation import validate_key

maintenances_app = typer.Typer(help="Manutencoes de ativos.")


@maintenances_app.command("get")
def get_maintenance(
    key: str = typer.Argument(help="Chave unica da manutencao."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Retorna os dados de uma manutencao pelo seu identificador.

    EXAMPLES:
      aegro maintenances get abc123
      aegro maintenances get abc123 --output table
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        result = client.get(f"/pub/v1/assets/maintenances/{validate_key(key)}", api_key=api_key)
        if result is None:
            typer.echo("Manutencao nao encontrada.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@maintenances_app.command("list")
def list_maintenances(
    asset_key: Optional[list[str]] = typer.Option(
        None, "--asset-key", help="Chave do ativo (repetivel para multiplos)."
    ),
    start_date: Optional[str] = typer.Option(
        None, "--start-date", help="Data inicial (YYYY-MM-DD)."
    ),
    end_date: Optional[str] = typer.Option(None, "--end-date", help="Data final (YYYY-MM-DD)."),
    page: int = typer.Option(1, "--page", help="Numero da pagina."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Lista manutencoes de ativos com filtros opcionais.

    EXAMPLES:
      aegro maintenances list
      aegro maintenances list --asset-key a1 --asset-key a2
      aegro maintenances list --start-date 2025-01-01 --end-date 2025-12-31 --page 2
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if asset_key:
            body["assetKeys"] = asset_key
        if start_date is not None:
            body["startDate"] = start_date
        if end_date is not None:
            body["endDate"] = end_date
        result = client.post("/pub/v1/assets/maintenances/filter", api_key=api_key, json_body=body)
        if result is None:
            typer.echo("Nenhuma manutencao encontrada.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@maintenances_app.command("create")
def create_maintenance(
    asset_key: str = typer.Option(..., "--asset-key", help="Chave do ativo."),
    date: str = typer.Option(..., "--date", help="Data da ocorrencia (YYYY-MM-DD)."),
    hourmeter: Optional[float] = typer.Option(
        None, "--hourmeter", help="Horimetro no momento da manutencao."
    ),
    observations: Optional[str] = typer.Option(
        None, "--observations", help="Observacoes opcionais."
    ),
    stock_location_key: Optional[str] = typer.Option(
        None, "--stock-location-key", help="Chave do local de estoque."
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Cria uma nova manutencao de ativo.

    EXAMPLES:
      aegro maintenances create --asset-key a1 --date 2025-06-01
      aegro maintenances create --asset-key a1 --date 2025-06-01 --hourmeter 2000 --observations "Troca de oleo"
    """
    try:
        farm_name, api_key = require_farm()
        client = get_client()
        body: dict = {
            "assetKey": asset_key,
            "occurrenceDate": date,
        }
        if hourmeter is not None:
            body["hourmeterAtOccurrence"] = hourmeter
        if observations is not None:
            body["observations"] = observations
        if stock_location_key is not None:
            body["stockLocationKey"] = stock_location_key
        result = client.post("/pub/v1/assets/maintenances", api_key=api_key, json_body=body)
        if result is None:
            typer.echo(f"Manutencao criada na fazenda '{farm_name}'.")
        else:
            typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@maintenances_app.command("update")
def update_maintenance(
    key: str = typer.Argument(help="Chave unica da manutencao."),
    asset_key: Optional[str] = typer.Option(None, "--asset-key", help="Chave do ativo."),
    date: Optional[str] = typer.Option(None, "--date", help="Data da ocorrencia (YYYY-MM-DD)."),
    hourmeter: Optional[float] = typer.Option(
        None, "--hourmeter", help="Horimetro no momento da manutencao."
    ),
    observations: Optional[str] = typer.Option(
        None, "--observations", help="Observacoes opcionais."
    ),
    stock_location_key: Optional[str] = typer.Option(
        None, "--stock-location-key", help="Chave do local de estoque."
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Atualiza uma manutencao de ativo existente.

    EXAMPLES:
      aegro maintenances update abc123 --date 2025-06-02
      aegro maintenances update abc123 --hourmeter 2100 --observations "Correcao"
    """
    try:
        farm_name, api_key = require_farm()
        client = get_client()
        body: dict = {}
        if asset_key is not None:
            body["assetKey"] = asset_key
        if date is not None:
            body["occurrenceDate"] = date
        if hourmeter is not None:
            body["hourmeterAtOccurrence"] = hourmeter
        if observations is not None:
            body["observations"] = observations
        if stock_location_key is not None:
            body["stockLocationKey"] = stock_location_key
        result = client.put(
            f"/pub/v1/assets/maintenances/{validate_key(key)}",
            api_key=api_key,
            json_body=body,
        )
        if result is None:
            typer.echo(f"Manutencao atualizada na fazenda '{farm_name}'.")
        else:
            typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
