# Create monitoring module: fmatch/monitoring/dashboard.py
from flask import Flask, jsonify
from datetime import datetime, timedelta
from sqlalchemy import text

from fmatch.telemetry.rule_telemetry import RuleEngineTelemetry

app = Flask(__name__)


@app.route("/api/rule_performance")
def rule_performance():
    """API endpoint for rule performance metrics."""
    telemetry = RuleEngineTelemetry()
    data = telemetry.get_rule_effectiveness(days=7)

    return jsonify(
        {
            "rules": [
                {
                    "name": rule,
                    "hits": stats["hits"],
                    "avg_impact": stats["avg_impact"],
                    "datasets": stats["datasets_affected"],
                }
                for rule, stats in data.items()
            ],
            "timestamp": datetime.now().isoformat(),
        }
    )


@app.route("/api/algorithm_usage")
def algorithm_usage():
    """API endpoint for algorithm usage statistics."""
    telemetry = RuleEngineTelemetry()
    cutoff = datetime.utcnow() - timedelta(days=7)
    with telemetry._engine.begin() as conn:
        results = conn.execute(
            text(
                """
                SELECT
                    chosen_algorithm,
                    COUNT(*) AS usage_count,
                    AVG(confidence_score) AS avg_confidence
                FROM match_results
                WHERE timestamp > :cutoff
                GROUP BY chosen_algorithm
                """
            ),
            {"cutoff": cutoff},
        ).fetchall()

    return jsonify(
        {
            "algorithms": [
                {"name": row[0], "usage": row[1], "avg_confidence": row[2]}
                for row in results
            ]
        }
    )
