import logging
from typing import Any, Dict, List

logger = logging.getLogger(__name__)

def create_metrics_entries(run_id: str, project_id: str, metrics: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Create metrics entries for local run submission."""
    return [
        {
            "metric_type": "drift_detection",
            "metric_name": "p_value",
            "value": metrics["drift_detection"]["p_value"],
            "status": metrics["drift_detection"]["status"],
        },
        {
            "metric_type": "robustness",
            "metric_name": "robust_ai_score",
            "value": metrics["robustness"]["robust_ai_score"],
            "status": metrics["robustness"]["status"],
        },
        {
            "metric_type": "bias",
            "metric_name": "bias_score",
            "value": metrics["bias"]["bias_score"],
            "status": metrics["bias"]["status"],
        },
    ]

def create_run_metadata(run_id: str, metrics: Dict[str, Any], thresholds: Dict[str, Any]) -> Dict[str, Any]:
    """Create run metadata for local run submission."""
    drift_threshold = thresholds.get("drift", {}).get("alert_threshold", 0.05)
    robustness_threshold = thresholds.get("robustness", {}).get("alert_threshold", 75)

    return {
        "name": "Local Run",
        "score": "pass" if all(m["status"] == "pass" for m in metrics.values()) else "fail",
        "metrics": {
            "drift_detection": {
                "value": metrics["drift_detection"]["p_value"],
                "threshold": drift_threshold,
                "status": metrics["drift_detection"]["status"],
            },
            "robustness": {
                "value": metrics["robustness"]["robust_ai_score"],
                "threshold": robustness_threshold,
                "status": metrics["robustness"]["status"],
            },
            "bias": {
                "value": metrics["bias"]["bias_score"],
                "p_value": metrics["bias"]["p_value"],
                "status": metrics["bias"]["status"],
            },
        },
    }

def create_alerts(run_id: str, project: Dict[str, Any], metrics: Dict[str, Any], thresholds: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Create alerts for local run submission."""
    alerts = []

    if metrics["drift_detection"]["status"] == "fail":
        drift_threshold = thresholds.get("drift", {}).get("alert_threshold", 0.05)
        current_value = metrics["drift_detection"]["p_value"]
        alerts.append({
            "rule_type": "CUSTOM_ALERT",
            "metric_name": "p_value",
            "current_value": current_value,
            "threshold": drift_threshold,
            "operator": "<",
            "title": "Drift Detected",
            "description": f"Data drift detected. P-value of {current_value} is below the threshold of {drift_threshold}.",
            "severity": thresholds.get("drift", {}).get("sensitivity", "medium").lower(),
            "status": "active",
            "triggered_by": {"value": current_value, "threshold": drift_threshold},
        })

    if metrics["robustness"]["status"] == "fail":
        robustness_threshold = thresholds.get("robustness", {}).get("alert_threshold", 75)
        current_value = metrics["robustness"]["robust_ai_score"]
        alerts.append({
            "rule_type": "CUSTOM_ALERT",
            "metric_name": "robustness_ai_score",
            "current_value": current_value,
            "threshold": robustness_threshold,
            "operator": "<",
            "title": "Low Robustness Score",
            "description": f"Robustness score of {current_value} is below the threshold of {robustness_threshold}.",
            "severity": thresholds.get("robustness", {}).get("sensitivity", "medium").lower(),
            "status": "active",
            "triggered_by": {"value": current_value, "threshold": robustness_threshold},
        })

    return alerts
