"""API endpoints for managing webhooks and external integrations."""

from __future__ import annotations

from typing import Any, Dict, List

from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field

from proxym.dashboard.webhooks import WebhookManager
from proxym.domain.events import (
    WebhookDeleted,
    WebhookRegistered,
    WebhookTested,
    WebhookUpdated,
)
from proxym.domain.setup import get_event_store

router = APIRouter(prefix="/integrations", tags=["integrations"])


class WebhookRegistration(BaseModel):
    """Webhook registration request."""
    system: str = Field(..., description="System name (github, gitlab, jira)")
    url: str = Field(..., description="Webhook URL")


class WebhookInfo(BaseModel):
    """Webhook information."""
    system: str
    url: str
    status: str = "active"  # Could add health checks later


@router.get("/webhooks", response_model=List[WebhookInfo])
async def list_webhooks() -> List[WebhookInfo]:
    """List all registered webhooks."""
    manager = WebhookManager.get()
    webhooks = [
        WebhookInfo(system=system, url=url)
        for system, url in manager._webhooks.items()
    ]
    return webhooks


@router.post("/webhooks", response_model=WebhookInfo)
async def register_webhook(request: WebhookRegistration) -> WebhookInfo:
    """Register a new webhook."""
    if request.system not in ["github", "gitlab", "jira"]:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Unsupported system: {request.system}"
        )

    manager = WebhookManager.get()
    manager.register_webhook(request.system, request.url)

    # Emit event for SSE notifications
    store = get_event_store()
    store.append(WebhookRegistered(
        aggregate_id=request.system,
        data={"system": request.system, "url": request.url}
    ))

    return WebhookInfo(system=request.system, url=request.url)


@router.delete("/webhooks/{system}")
async def delete_webhook(system: str) -> Dict[str, Any]:
    """Delete a webhook registration."""
    manager = WebhookManager.get()
    if system not in manager._webhooks:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"No webhook registered for {system}"
        )

    url = manager._webhooks[system]
    del manager._webhooks[system]

    # Emit event for SSE notifications
    store = get_event_store()
    store.append(WebhookDeleted(
        aggregate_id=system,
        data={"system": system, "url": url}
    ))

    return {"message": f"Webhook for {system} deleted"}


@router.post("/webhooks/test")
async def test_webhook(system: str, url: str) -> Dict[str, Any]:
    """Test a webhook by sending a test event."""
    if system not in ["github", "gitlab", "jira"]:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Unsupported system: {system}"
        )
    
    # Create test payload
    test_payload = {
        "event_type": "ticket_status_changed",
        "ticket_id": "TKT-TEST123",
        "old_status": "todo",
        "new_status": "done",
        "timestamp": 1234567890,
        "trigger": {
            "event": "JobCompleted",
            "job_id": "test-job-123"
        }
    }
    
    try:
        manager = WebhookManager.get()
        await manager._send_webhook(url, test_payload, system)

        # Emit event for SSE notifications
        store = get_event_store()
        store.append(WebhookTested(
            aggregate_id=system,
            data={"system": system, "url": url, "success": True}
        ))

        return {"message": f"Test webhook sent to {system}", "status": "success"}
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Webhook test failed: {str(exc)}"
        )
