"""REST endpoints for observability, health events, and repair agent."""
from __future__ import annotations

from typing import Any

from fastapi import APIRouter
from pydantic import BaseModel

from proxym.observability import get_log_buffer, get_error_summary
from proxym.observability.health_events import get_health_store

router = APIRouter(tags=["observability"])


@router.get("/observability/logs")
def obs_logs(limit: int = 100, level: str | None = None) -> list[dict]:
    """Ring buffer logs — ostatnie N wpisów z dekoratorów."""
    return get_log_buffer(limit=limit, level=level)


@router.get("/observability/errors")
def obs_errors() -> dict[str, Any]:
    """Podsumowanie błędów z ring buffer."""
    return get_error_summary()


@router.get("/observability/health-events")
def obs_health_events(limit: int = 50, severity: str | None = None) -> list[dict]:
    """Historia zdarzeń zdrowia systemu."""
    return get_health_store().get_history(limit=limit, severity=severity)


@router.get("/observability/health-summary")
def obs_health_summary() -> dict[str, Any]:
    """Aktywne problemy i podsumowanie."""
    return get_health_store().get_summary()


class RepairRequest(BaseModel):
    error_text: str = ""
    file_path: str = ""
    traceback_text: str = ""
    mode: str = "suggest"  # suggest | apply


@router.post("/observability/repair")
async def obs_repair(req: RepairRequest) -> dict[str, Any]:
    """Uruchom LLM repair agent na wskazanym błędzie."""
    from proxym.config import get_settings
    settings = get_settings()
    if not settings.repair_enabled:
        return {"error": "Repair agent disabled. Set PROXYM_REPAIR_ENABLED=true in .env"}

    from proxym.observability.repair_agent import RepairAgent
    agent = RepairAgent(mode=req.mode or settings.repair_mode)
    return await agent.diagnose_and_repair(
        error_text=req.error_text,
        file_path=req.file_path,
        traceback_text=req.traceback_text,
    )


@router.post("/observability/repair-from-logs")
async def obs_repair_from_logs() -> dict[str, Any]:
    """Auto-diagnozuj najczęstszy błąd z ring buffer."""
    from proxym.config import get_settings
    settings = get_settings()
    if not settings.repair_enabled:
        return {"error": "Repair agent disabled"}

    from proxym.observability.repair_agent import RepairAgent
    agent = RepairAgent(mode=settings.repair_mode)
    return await agent.diagnose_from_logs()


@router.get("/observability/repair-history")
def obs_repair_history(limit: int = 20) -> list[dict]:
    """Historia napraw wykonanych przez repair agent."""
    from proxym.observability.repair_agent import RepairAgent
    agent = RepairAgent()
    return agent.get_history(limit=limit)


# ── Domain Events (CQRS Event Sourcing) ─────────────────

@router.get("/observability/domain-events")
def obs_domain_events(
    limit: int = 100,
    event_type: str | None = None,
    aggregate_id: str | None = None,
) -> dict[str, Any]:
    """Domain events from the CQRS event store — audit trail for all state changes.

    Returns events filtered by type and/or aggregate_id.
    """
    try:
        from proxym.domain.setup import get_event_store
        store = get_event_store()

        if aggregate_id:
            events = store.events_for(aggregate_id)
        else:
            events = store.all_events(event_type=event_type, limit=limit)

        return {
            "total": store.count(),
            "returned": len(events),
            "events": [e.to_dict() for e in events[-limit:]],
        }
    except Exception as exc:
        return {"total": 0, "returned": 0, "events": [], "error": str(exc)}
