"""
Admin API for Domain Family Management
=======================================
"""

from fastapi import APIRouter, Depends, HTTPException, status
from typing import Dict, Any, Optional
from pydantic import BaseModel
import logging

from ...auth_core import require_admin
from ...services.domain_family import get_registry, DomainRelation

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v2/admin", tags=["admin"])


class DomainFamilyAddRequest(BaseModel):
    """Request to add a domain to a family"""

    domain: str
    family_id: str
    account_id: Optional[str] = None


class DomainRelationTestRequest(BaseModel):
    """Request to test relation between two domains"""

    domain1: str
    domain2: str


# COMMENTED OUT - Duplicate route exists in admin_domain_families.py
# @router.get("/domain-families")
# async def get_domain_families(
#     _admin = Depends(require_admin)
# ) -> Dict[str, Any]:
#     """
#     Get the effective domain family registry.
#
#     Returns:
#         Registry contents including families, domains, and metadata
#     """
#     registry = get_registry()
#     return registry.to_dict()


@router.post("/domain-families")
async def add_domain_family_override(
    request: DomainFamilyAddRequest, _admin=Depends(require_admin)
) -> Dict[str, Any]:
    """
    Add a domain family override.

    Args:
        request: Domain, family_id, and optional account_id

    Returns:
        Success status and updated family info
    """
    registry = get_registry()

    # Validate domain
    from ...services.domain_family import domain_normalize

    normalized = domain_normalize(request.domain)
    if not normalized:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Invalid domain: {request.domain}",
        )

    # Add override
    registry.add_override(
        domain=request.domain,
        family_id=request.family_id,
        account_id=request.account_id,
    )

    # Return updated family
    family_domains = registry.get_family_domains(request.family_id)

    return {
        "status": "success",
        "domain": normalized,
        "family_id": request.family_id,
        "family_domains": sorted(family_domains),
        "account_id": request.account_id,
    }


# COMMENTED OUT - Duplicate route exists in admin_domain_families.py
# @router.post("/reload-domain-families")
# async def reload_domain_families(
#     _admin = Depends(require_admin)
# ) -> Dict[str, Any]:
#     """
#     Force reload of domain family registry (bypass TTL).
#
#     Returns:
#         Reload status and updated counts
#     """
#     registry = get_registry()
#     reloaded = registry.reload(force=True)
#
#     if not reloaded:
#         return {
#             "status": "skipped",
#             "message": "Registry is currently reloading"
#         }
#
#     stats = registry.to_dict()
#     return {
#         "status": "success",
#         "message": "Domain families reloaded",
#         "total_families": stats["total_families"],
#         "total_domains": stats["total_domains"],
#         "last_updated": stats["last_updated"]
#     }


@router.post("/test-domain-relation")
async def test_domain_relation(
    request: DomainRelationTestRequest, _admin=Depends(require_admin)
) -> Dict[str, Any]:
    """
    Test the relationship between two domains.

    Args:
        request: Two domains to test

    Returns:
        Relation type, family_id if applicable, and normalized forms
    """
    from ...services.domain_family import domain_normalize

    registry = get_registry()

    # Normalize both domains
    norm1 = domain_normalize(request.domain1)
    norm2 = domain_normalize(request.domain2)

    # Get relation
    relation, family_id = registry.relation(request.domain1, request.domain2)

    return {
        "domain1": {
            "input": request.domain1,
            "normalized": norm1,
            "family": registry.get_domain_family(request.domain1) if norm1 else None,
        },
        "domain2": {
            "input": request.domain2,
            "normalized": norm2,
            "family": registry.get_domain_family(request.domain2) if norm2 else None,
        },
        "relation": relation.value,
        "family_id": family_id,
        "interpretation": _interpret_relation(relation, family_id),
    }


def _interpret_relation(relation: DomainRelation, family_id: Optional[str]) -> str:
    """Provide human-readable interpretation of relation"""
    if relation == DomainRelation.EXACT:
        return "Same domain (exact match)"
    elif relation == DomainRelation.FAMILY:
        return f"Same corporate family ({family_id})"
    elif relation == DomainRelation.SUBDOMAIN:
        return "Subdomain relationship"
    elif relation == DomainRelation.NONE:
        return "No relationship (different domains)"
    else:
        return "Unknown relationship"
