from __future__ import annotations

"""Analyse d'utilisation basée sur l'historique des scans Web Sentinel."""

import json
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional


def compute_history_metrics(history_path: Optional[Path] = None) -> Dict[str, object]:
    """
    Calculer des métriques à partir du fichier d'historique (~/.web-sentinel/history.json).

    Returns:
        Dictionnaire avec différentes métriques (scans, domaines, findings, etc.).
    """
    path = history_path or (Path.home() / ".web-sentinel" / "history.json")
    if not path.exists():
        return {
            "history_path": str(path),
            "available": False,
            "total_domains": 0,
            "total_scans": 0,
            "total_findings": 0,
            "average_findings_per_scan": 0.0,
            "severity_counts": {},
            "last_scan_at": None,
        }

    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {
            "history_path": str(path),
            "available": False,
            "total_domains": 0,
            "total_scans": 0,
            "total_findings": 0,
            "average_findings_per_scan": 0.0,
            "severity_counts": {},
            "last_scan_at": None,
        }

    total_scans = 0
    total_findings = 0
    severity_counter: Counter[str] = Counter()
    last_scan_timestamp: Optional[str] = None

    for domain_entries in data.values():
        for entry in domain_entries:
            total_scans += 1
            findings = entry.get("findings", [])
            total_findings += len(findings)
            for finding in findings:
                severity = finding.get("severity", "unknown").lower()
                severity_counter[severity] += 1
            generated_at = entry.get("generated_at")
            if generated_at:
                if last_scan_timestamp is None or generated_at > last_scan_timestamp:
                    last_scan_timestamp = generated_at

    average_findings = (total_findings / total_scans) if total_scans else 0.0

    return {
        "history_path": str(path),
        "available": True,
        "total_domains": len(data),
        "total_scans": total_scans,
        "total_findings": total_findings,
        "average_findings_per_scan": round(average_findings, 2),
        "severity_counts": dict(severity_counter),
        "last_scan_at": last_scan_timestamp,
    }


__all__ = ["compute_history_metrics"]
