"""Admin endpoints for activations and integration usage."""

from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any, Dict, List

from fastapi import APIRouter, Depends, Query
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession

from ...auth_security import AdminContext, require_admin
from ...db import get_session
from ...models import WorkspaceSecret, Integration

log = logging.getLogger(__name__)

router = APIRouter(tags=["Admin Activations"])


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


def _dt_iso(value: Any) -> Any:
    if value is None:
        return None
    if isinstance(value, datetime):
        return value.isoformat()
    return str(value)


@router.get("/overview")
async def get_activations_overview(
    admin_ctx: AdminContext = Depends(require_admin),
    db: AsyncSession = Depends(get_session),
) -> Dict[str, Any]:
    workspace_table = WorkspaceSecret.__tablename__
    integration_table = Integration.__tablename__

    byo_query = text(
        f"""
        SELECT integration,
               COUNT(*) AS connections,
               COUNT(DISTINCT workspace_id) AS workspaces,
               COUNT(*) FILTER (WHERE validated_at IS NOT NULL) AS validated,
               MAX(created_at) AS most_recent
        FROM {workspace_table}
        GROUP BY integration
        ORDER BY connections DESC
        """
    )
    oauth_query = text(
        f"""
        SELECT provider,
               COUNT(*) AS connections,
               COUNT(DISTINCT account_id) AS accounts,
               COUNT(*) FILTER (WHERE status IN ('connected','active')) AS active,
               MAX(created_at) AS most_recent
        FROM {integration_table}
        GROUP BY provider
        ORDER BY connections DESC
        """
    )

    byo_totals_query = text(
        f"""
        SELECT COUNT(DISTINCT workspace_id) AS workspaces,
               COUNT(*) AS connections,
               COUNT(*) FILTER (WHERE validated_at IS NOT NULL) AS validated
        FROM {workspace_table}
        """
    )
    oauth_totals_query = text(
        f"""
        SELECT COUNT(DISTINCT account_id) AS accounts,
               COUNT(*) AS connections,
               COUNT(*) FILTER (WHERE status IN ('connected','active')) AS active
        FROM {integration_table}
        """
    )

    byo_rows = (await db.execute(byo_query)).mappings().all()
    oauth_rows = (await db.execute(oauth_query)).mappings().all()
    byo_totals = (await db.execute(byo_totals_query)).mappings().one_or_none() or {}
    oauth_totals = (await db.execute(oauth_totals_query)).mappings().one_or_none() or {}

    byo_providers = []
    for row in byo_rows:
        connections = row.get("connections") or 0
        validated = row.get("validated") or 0
        byo_providers.append(
            {
                "integration": row.get("integration"),
                "workspaces": row.get("workspaces") or 0,
                "connections": connections,
                "validated": validated,
                "most_recent": _dt_iso(row.get("most_recent")),
                "validation_rate": (validated / connections) if connections else 0,
            }
        )

    oauth_providers = []
    for row in oauth_rows:
        connections = row.get("connections") or 0
        active = row.get("active") or 0
        oauth_providers.append(
            {
                "provider": row.get("provider"),
                "accounts": row.get("accounts") or 0,
                "connections": connections,
                "active": active,
                "most_recent": _dt_iso(row.get("most_recent")),
                "activation_rate": (active / connections) if connections else 0,
            }
        )

    total_connections = (byo_totals.get("connections") or 0) + (
        oauth_totals.get("connections") or 0
    )

    summary = {
        "byo_providers": len(byo_providers),
        "byo_workspaces": byo_totals.get("workspaces") or 0,
        "byo_connections": byo_totals.get("connections") or 0,
        "byo_validated": byo_totals.get("validated") or 0,
        "oauth_providers": len(oauth_providers),
        "oauth_accounts": oauth_totals.get("accounts") or 0,
        "oauth_connections": oauth_totals.get("connections") or 0,
        "oauth_active": oauth_totals.get("active") or 0,
        "total_connections": total_connections,
        "generated_at": _now_iso(),
    }

    return {
        "summary": summary,
        "byo_providers": byo_providers,
        "oauth_providers": oauth_providers,
    }


@router.get("/recent-connections")
async def get_recent_connections(
    days: int = Query(30, ge=1, le=365),
    limit: int = Query(50, ge=1, le=200),
    admin_ctx: AdminContext = Depends(require_admin),
    db: AsyncSession = Depends(get_session),
) -> Dict[str, Any]:
    workspace_table = WorkspaceSecret.__tablename__
    integration_table = Integration.__tablename__

    byo_recent_query = text(
        f"""
        SELECT integration, workspace_id, key_name, created_at, updated_at, validated_at
        FROM {workspace_table}
        WHERE created_at >= (now() - (:days * interval '1 day'))
        ORDER BY created_at DESC
        LIMIT :limit
        """
    )
    oauth_recent_query = text(
        f"""
        SELECT provider, account_id, status, created_at, updated_at
        FROM {integration_table}
        WHERE created_at >= (now() - (:days * interval '1 day'))
        ORDER BY created_at DESC
        LIMIT :limit
        """
    )

    params = {"days": days, "limit": limit}
    byo_rows = (await db.execute(byo_recent_query, params)).mappings().all()
    oauth_rows = (await db.execute(oauth_recent_query, params)).mappings().all()

    items: List[Dict[str, Any]] = []
    for row in byo_rows:
        items.append(
            {
                "source": "byo",
                "provider": row.get("integration"),
                "workspace_id": row.get("workspace_id"),
                "account_id": None,
                "status": None,
                "key_name": row.get("key_name"),
                "validated_at": _dt_iso(row.get("validated_at")),
                "created_at": _dt_iso(row.get("created_at")),
                "updated_at": _dt_iso(row.get("updated_at")),
            }
        )
    for row in oauth_rows:
        items.append(
            {
                "source": "oauth",
                "provider": row.get("provider"),
                "workspace_id": None,
                "account_id": row.get("account_id"),
                "status": row.get("status"),
                "key_name": None,
                "validated_at": None,
                "created_at": _dt_iso(row.get("created_at")),
                "updated_at": _dt_iso(row.get("updated_at")),
            }
        )

    _epoch = datetime.min.replace(tzinfo=timezone.utc)

    def _sort_key(item: Dict[str, Any]):
        value = item.get("created_at")
        if isinstance(value, str):
            try:
                dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
                if dt.tzinfo is None:
                    dt = dt.replace(tzinfo=timezone.utc)
                return dt
            except ValueError:
                return _epoch
        if isinstance(value, datetime):
            if value.tzinfo is None:
                return value.replace(tzinfo=timezone.utc)
            return value
        return _epoch

    items.sort(key=_sort_key, reverse=True)
    if len(items) > limit:
        items = items[:limit]

    return {
        "items": items,
        "days": days,
        "limit": limit,
        "generated_at": _now_iso(),
    }


@router.get("/usage-by-provider")
async def get_usage_by_provider(
    days: int = Query(30, ge=1, le=365),
    admin_ctx: AdminContext = Depends(require_admin),
    db: AsyncSession = Depends(get_session),
) -> Dict[str, Any]:
    totals_query = text(
        """
        SELECT source,
               COUNT(*) AS events,
               COUNT(DISTINCT org_id) AS unique_orgs,
               COALESCE(SUM(rows), 0) AS total_rows
        FROM saas_events
        WHERE ts >= (now() - (:days * interval '1 day'))
        GROUP BY source
        ORDER BY events DESC
        """
    )
    actions_query = text(
        """
        SELECT source, action, COUNT(*) AS events
        FROM saas_events
        WHERE ts >= (now() - (:days * interval '1 day'))
        GROUP BY source, action
        ORDER BY source, events DESC
        """
    )

    params = {"days": days}
    totals_rows = (await db.execute(totals_query, params)).mappings().all()
    actions_rows = (await db.execute(actions_query, params)).mappings().all()

    actions_by_source: Dict[str, List[Dict[str, Any]]] = {}
    for row in actions_rows:
        source = row.get("source") or "unknown"
        actions_by_source.setdefault(source, []).append(
            {"action": row.get("action"), "events": row.get("events") or 0}
        )

    sources: List[Dict[str, Any]] = []
    for row in totals_rows:
        source = row.get("source") or "unknown"
        actions = actions_by_source.get(source, [])
        actions_sorted = sorted(actions, key=lambda x: x["events"], reverse=True)
        sources.append(
            {
                "source": source,
                "events": row.get("events") or 0,
                "unique_orgs": row.get("unique_orgs") or 0,
                "total_rows": row.get("total_rows") or 0,
                "top_actions": actions_sorted[:6],
            }
        )

    return {
        "sources": sources,
        "days": days,
        "generated_at": _now_iso(),
    }


@router.get("/validation-status")
async def get_validation_status(
    admin_ctx: AdminContext = Depends(require_admin),
    db: AsyncSession = Depends(get_session),
) -> Dict[str, Any]:
    workspace_table = WorkspaceSecret.__tablename__
    stale_days = 30

    status_query = text(
        f"""
        SELECT integration,
               COUNT(*) AS total,
               COUNT(*) FILTER (
                    WHERE validated_at IS NOT NULL
                      AND validated_at >= (now() - (:stale_days * interval '1 day'))
               ) AS validated,
               COUNT(*) FILTER (WHERE validated_at IS NULL) AS unvalidated,
               COUNT(*) FILTER (
                    WHERE validated_at IS NOT NULL
                      AND validated_at < (now() - (:stale_days * interval '1 day'))
               ) AS stale,
               MAX(created_at) AS most_recent
        FROM {workspace_table}
        GROUP BY integration
        ORDER BY total DESC
        """
    )

    rows = (await db.execute(status_query, {"stale_days": stale_days})).mappings().all()
    providers: List[Dict[str, Any]] = []
    for row in rows:
        total = row.get("total") or 0
        validated = row.get("validated") or 0
        providers.append(
            {
                "integration": row.get("integration"),
                "total": total,
                "validated": validated,
                "unvalidated": row.get("unvalidated") or 0,
                "stale": row.get("stale") or 0,
                "most_recent": _dt_iso(row.get("most_recent")),
                "validation_rate": (validated / total) if total else 0,
            }
        )

    return {
        "providers": providers,
        "stale_days": stale_days,
        "generated_at": _now_iso(),
    }
