from __future__ import annotations

from datetime import datetime, timezone
from typing import Any

from pydantic import BaseModel, Field


class OutputMeta(BaseModel):
    trace_id: str
    duration_ms: int = Field(ge=0)
    platform: str | None = None
    account_uid: str | None = None


class SuccessOutput(BaseModel):
    ok: bool = True
    command: str
    timestamp: str
    data: Any
    meta: OutputMeta


class ErrorDetail(BaseModel):
    code: str
    message: str
    details: dict[str, Any] | None = None


class ErrorOutput(BaseModel):
    ok: bool = False
    command: str
    timestamp: str
    error: ErrorDetail
    meta: OutputMeta


def _now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def build_success_output(
    *,
    command: str,
    data: Any,
    trace_id: str,
    duration_ms: int,
    platform: str | None = None,
    account_uid: str | None = None,
) -> SuccessOutput:
    return SuccessOutput(
        command=command,
        timestamp=_now_iso(),
        data=data,
        meta=OutputMeta(
            trace_id=trace_id,
            duration_ms=duration_ms,
            platform=platform,
            account_uid=account_uid,
        ),
    )


def build_error_output(
    *,
    command: str,
    code: str,
    message: str,
    trace_id: str,
    duration_ms: int,
    details: dict[str, Any] | None = None,
) -> ErrorOutput:
    return ErrorOutput(
        command=command,
        timestamp=_now_iso(),
        error=ErrorDetail(code=code, message=message, details=details),
        meta=OutputMeta(trace_id=trace_id, duration_ms=duration_ms),
    )
