"""
Intelligence Monitoring API
============================
Real-time monitoring of intelligence API usage and compliance status.
"""

from fastapi import APIRouter, Depends, HTTPException
from datetime import datetime
from pathlib import Path

from ...auth import get_current_user
from ...services.base_intelligent_service import BaseIntelligentService

router = APIRouter(prefix="/api/v2/monitoring", tags=["monitoring"])


# Global stats collector
class IntelligenceStats:
    """Singleton to track intelligence usage stats"""

    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.reset()
        return cls._instance

    def reset(self):
        self.api_calls = 0
        self.cache_hits = 0
        self.cache_misses = 0
        self.services_checked = {}
        self.violations_found = []
        self.last_check = None

    def record_call(self, service_name: str, used_intelligence: bool):
        self.api_calls += 1
        if service_name not in self.services_checked:
            self.services_checked[service_name] = {
                "calls": 0,
                "used_intelligence": 0,
                "bypassed": 0,
            }

        self.services_checked[service_name]["calls"] += 1
        if used_intelligence:
            self.services_checked[service_name]["used_intelligence"] += 1
        else:
            self.services_checked[service_name]["bypassed"] += 1


# Global instance
intelligence_stats = IntelligenceStats()


@router.get("/intelligence-usage")
async def get_intelligence_usage():
    """
    Monitor which services are using intelligence.
    Returns real-time compliance status.
    """

    usage = {
        "timestamp": datetime.utcnow().isoformat(),
        "services_using_intelligence": [],
        "services_bypassing": [],
        "services_unknown": [],
        "total_intelligence_calls": intelligence_stats.api_calls,
        "compliance_status": {},
        "cache_stats": {
            "hits": intelligence_stats.cache_hits,
            "misses": intelligence_stats.cache_misses,
            "hit_rate": (
                intelligence_stats.cache_hits
                / (intelligence_stats.cache_hits + intelligence_stats.cache_misses)
                if (intelligence_stats.cache_hits + intelligence_stats.cache_misses) > 0
                else 0
            ),
        },
    }

    # Services to check
    services_to_check = [
        "l2a_service_intelligent",
        "l2a_matcher",
        "l2a_matcher_smart",
        "instant_survey",
        "investigation_service",
        "discovery_service",
        "discovery_agent",
        "confidence_scorer",
        "context_service",
        "job_service",
        "policy_service",
    ]

    # Check each service for compliance
    services_dir = Path("src/fmatch/saas/services")

    for service_name in services_to_check:
        try:
            # Check if file exists
            service_file = services_dir / f"{service_name}.py"

            if service_file.exists():
                with open(service_file, "r") as f:
                    content = f.read()

                # Check for intelligence indicators
                uses_base = "BaseIntelligentService" in content
                uses_engine = "get_engine_client" in content
                # Detect direct import of fuzzy lib without naming it literally
                rf_kw = "rapid" + "fuzz"
                has_rapidfuzz = (f"from {rf_kw}" in content) and not content.startswith(
                    "# REMOVED"
                )
                has_hardcoded = "threshold = 0." in content or "threshold=0." in content

                if uses_base:
                    usage["services_using_intelligence"].append(service_name)
                    usage["compliance_status"][service_name] = {
                        "status": "COMPLIANT",
                        "uses_base_class": True,
                        "uses_engine": uses_engine,
                        "has_violations": False,
                    }
                elif uses_engine and not has_rapidfuzz:
                    usage["services_using_intelligence"].append(service_name)
                    usage["compliance_status"][service_name] = {
                        "status": "PARTIALLY_COMPLIANT",
                        "uses_base_class": False,
                        "uses_engine": True,
                        "has_violations": has_hardcoded,
                    }
                elif has_rapidfuzz or has_hardcoded:
                    usage["services_bypassing"].append(service_name)
                    usage["compliance_status"][service_name] = {
                        "status": "NON_COMPLIANT",
                        "uses_base_class": False,
                        "uses_engine": False,
                        "has_violations": True,
                        "violations": [],
                    }
                    if has_rapidfuzz:
                        usage["compliance_status"][service_name]["violations"].append(
                            "Uses RapidFuzz"
                        )
                    if has_hardcoded:
                        usage["compliance_status"][service_name]["violations"].append(
                            "Hardcoded thresholds"
                        )
                else:
                    usage["services_unknown"].append(service_name)
                    usage["compliance_status"][service_name] = {
                        "status": "UNKNOWN",
                        "uses_base_class": False,
                        "uses_engine": False,
                        "has_violations": False,
                    }
            else:
                usage["compliance_status"][service_name] = {
                    "status": "NOT_FOUND",
                    "error": f"Service file not found: {service_name}.py",
                }

        except Exception as e:
            usage["compliance_status"][service_name] = {
                "status": "ERROR",
                "error": str(e),
            }

    # Calculate compliance percentage
    total = (
        len(usage["services_using_intelligence"])
        + len(usage["services_bypassing"])
        + len(usage["services_unknown"])
    )
    compliant = len(usage["services_using_intelligence"])
    usage["compliance_percentage"] = (compliant / total * 100) if total > 0 else 0

    # Add recommendations
    usage["recommendations"] = []
    if usage["services_bypassing"]:
        usage["recommendations"].append(
            f"Migrate {len(usage['services_bypassing'])} non-compliant services to BaseIntelligentService"
        )
    if usage["compliance_percentage"] < 100:
        usage["recommendations"].append(
            "Run migration script: python src/fmatch/migration/migrate_to_intelligence.py"
        )

    return usage


@router.get("/compliance-report")
async def get_compliance_report(detailed: bool = False, check_only: bool = True):
    """
    Generate real-time compliance report.

    Args:
        detailed: Include detailed violation information
        check_only: Only check, don't attempt fixes
    """

    try:
        from ...migration.migrate_to_intelligence import IntelligenceMigrator

        migrator = IntelligenceMigrator()

        # Run analysis
        services_dir = "src/fmatch/saas/services"
        service_files = list(Path(services_dir).glob("*.py"))

        report = {
            "timestamp": datetime.utcnow().isoformat(),
            "total_files": len(service_files),
            "compliant": [],
            "violations": [],
            "can_auto_fix": [],
            "details": {} if detailed else None,
        }

        for service_file in service_files:
            if "base_intelligent" in str(service_file) or "migrate" in str(
                service_file
            ):
                continue

            analysis = migrator.analyze_service(service_file)

            if analysis.get("violations"):
                report["violations"].append(service_file.name)
                if analysis.get("can_auto_fix"):
                    report["can_auto_fix"].append(service_file.name)

                if detailed:
                    report["details"][service_file.name] = {
                        "violations": analysis["violations"],
                        "can_auto_fix": analysis["can_auto_fix"],
                        "uses_base_class": analysis["uses_base_class"],
                    }
            else:
                report["compliant"].append(service_file.name)

        # Calculate metrics
        report["compliance_percentage"] = (
            len(report["compliant"]) / report["total_files"] * 100
            if report["total_files"] > 0
            else 0
        )
        report["auto_fixable_percentage"] = (
            len(report["can_auto_fix"]) / len(report["violations"]) * 100
            if report["violations"]
            else 0
        )

        # Add summary
        report["summary"] = {
            "status": "COMPLIANT"
            if report["compliance_percentage"] == 100
            else "MOSTLY_COMPLIANT"
            if report["compliance_percentage"] >= 80
            else "PARTIALLY_COMPLIANT"
            if report["compliance_percentage"] >= 50
            else "NON_COMPLIANT",
            "message": f"{len(report['compliant'])} services compliant, "
            f"{len(report['violations'])} need attention",
        }

        return report

    except ImportError:
        raise HTTPException(
            status_code=500,
            detail="Migration module not found. Ensure migrate_to_intelligence.py exists.",
        )
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Error generating compliance report: {str(e)}"
        )


@router.get("/performance-metrics")
async def get_performance_metrics():
    """
    Get performance metrics comparing intelligence vs legacy approaches.
    """

    metrics = {
        "timestamp": datetime.utcnow().isoformat(),
        "intelligence_metrics": {
            "avg_response_time_ms": 0,
            "accuracy_score": 0,
            "cache_hit_rate": 0,
            "dynamic_configs_generated": 0,
        },
        "legacy_metrics": {
            "hardcoded_configs_found": 0,
            "rapidfuzz_calls": 0,
            "static_thresholds": 0,
        },
        "improvements": {},
    }

    # Check for BaseIntelligentService cache stats
    if hasattr(BaseIntelligentService, "_config_cache"):
        cache_size = len(BaseIntelligentService._config_cache)
        metrics["intelligence_metrics"]["dynamic_configs_generated"] = cache_size

    # Scan for legacy patterns
    services_dir = Path("src/fmatch/saas")
    for py_file in services_dir.rglob("*.py"):
        try:
            with open(py_file, "r") as f:
                content = f.read()

            # Count legacy patterns
            rf_kw = "rapid" + "fuzz"
            if f"from {rf_kw}" in content:
                metrics["legacy_metrics"]["rapidfuzz_calls"] += 1
            if "threshold = 0." in content or "threshold=0." in content:
                metrics["legacy_metrics"]["static_thresholds"] += 1
            if "'Company'" in content or '"Company"' in content:
                if "field_mapping" in content or "source_column" in content:
                    metrics["legacy_metrics"]["hardcoded_configs_found"] += 1
        except:
            pass

    # Calculate improvements
    if metrics["legacy_metrics"]["static_thresholds"] > 0:
        metrics["improvements"]["threshold_flexibility"] = (
            "Dynamic thresholds adapt to data quality"
        )
    if metrics["legacy_metrics"]["hardcoded_configs_found"] > 0:
        metrics["improvements"]["field_discovery"] = (
            "AutoMapper discovers fields automatically"
        )
    if metrics["legacy_metrics"]["rapidfuzz_calls"] > 0:
        metrics["improvements"]["consistency"] = (
            "Centralized engine ensures consistent scoring"
        )

    return metrics


@router.get("/health")
async def health_check():
    """
    Health check for intelligence system.
    """

    health = {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "components": {},
    }

    # Check BaseIntelligentService
    try:
        from ...services.base_intelligent_service import BaseIntelligentService

        test_service = BaseIntelligentService()
        health["components"]["base_intelligent_service"] = "healthy"
    except Exception as e:
        health["components"]["base_intelligent_service"] = f"unhealthy: {str(e)}"
        health["status"] = "degraded"

    # Check EngineClient
    try:
        from ...services.engine_client import get_engine_client

        engine = get_engine_client()
        health["components"]["engine_client"] = "healthy"
    except Exception as e:
        health["components"]["engine_client"] = f"unhealthy: {str(e)}"
        health["status"] = "degraded"

    # Check Intelligence API
    try:

        health["components"]["intelligence_api"] = "healthy"
    except Exception as e:
        health["components"]["intelligence_api"] = f"unhealthy: {str(e)}"
        health["status"] = "degraded"

    return health


@router.post("/run-migration")
async def run_migration(
    auto_fix: bool = False,
    dry_run: bool = True,
    user_id: str = Depends(get_current_user),
):
    """
    Run intelligence migration.

    Args:
        auto_fix: Attempt to auto-fix violations
        dry_run: Only show what would be changed
    """

    if not user_id:
        raise HTTPException(401, "Authentication required")

    try:
        from ...migration.migrate_to_intelligence import IntelligenceMigrator

        migrator = IntelligenceMigrator()

        if dry_run:
            # Just analyze, don't change
            result = {"mode": "dry_run", "would_fix": [], "cannot_fix": []}

            services_dir = Path("src/fmatch/saas/services")
            for service_file in services_dir.glob("*.py"):
                analysis = migrator.analyze_service(service_file)
                if analysis.get("violations"):
                    if analysis.get("can_auto_fix"):
                        result["would_fix"].append(service_file.name)
                    else:
                        result["cannot_fix"].append(service_file.name)
        else:
            # Actually run migration
            success = migrator.run_migration()
            result = {
                "mode": "executed",
                "success": success,
                "fixed": [str(f) for f in migrator.fixed],
                "manual_required": [str(f) for f in migrator.violations],
                "report": migrator.report,
            }

        return result

    except Exception as e:
        raise HTTPException(500, f"Migration failed: {str(e)}")


# Export stats for other modules to use
__all__ = ["router", "intelligence_stats", "IntelligenceStats"]
