"""Scoring ICP — score /100 avec poids configurables depuis niches.yaml."""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path

import structlog

from src.config import DATA_DIR, get_niches_config
from src.enrichment import EnrichedLead

log = structlog.get_logger()

REJECTED_FILE = DATA_DIR / "rejected.jsonl"


@dataclass(frozen=True)
class ScoringResult:
    """Résultat du scoring ICP."""
    score: int
    matched_criteria: list[str]
    qualified: bool


def score_lead(lead: EnrichedLead) -> ScoringResult:
    """Calcule le score ICP d'un lead enrichi.

    Score sur 100. Chaque critère matché ajoute ses points.
    Plus le score est élevé, plus le prospect est un bon candidat
    (= son site a des problèmes qu'on peut résoudre).
    """
    config = get_niches_config()
    weights = config.scoring_weights
    threshold = config.scoring_threshold

    score = 0
    matched: list[str] = []

    # Performance sous 80%
    if lead.perf_score is not None and lead.perf_score < 0.80:
        points = weights.get("perf_under_80", 20)
        score += points
        matched.append(f"perf_under_80 (+{points})")

    # SEO sous 90%
    if lead.seo_score is not None and lead.seo_score < 0.90:
        points = weights.get("seo_under_90", 20)
        score += points
        matched.append(f"seo_under_90 (+{points})")

    # LCP > 2500ms
    if lead.lcp_ms is not None and lead.lcp_ms > 2500:
        points = weights.get("lcp_over_2500", 15)
        score += points
        matched.append(f"lcp_over_2500 (+{points})")

    # LCP > 4000ms — bonus supplémentaire
    if lead.lcp_ms is not None and lead.lcp_ms > 4000:
        points = weights.get("lcp_over_4s", 10)
        score += points
        matched.append(f"lcp_over_4s (+{points})")

    # Core Web Vitals != FAST
    if lead.cwv_category and lead.cwv_category.upper() != "FAST":
        points = weights.get("cwv_not_fast", 15)
        score += points
        matched.append(f"cwv_not_fast (+{points})")

    # Pas de HTTPS
    if lead.url.startswith("http://"):
        points = weights.get("no_https", 10)
        score += points
        matched.append(f"no_https (+{points})")

    # WordPress détecté
    if lead.technology and "wordpress" in lead.technology.lower():
        points = weights.get("wordpress", 10)
        score += points
        matched.append(f"wordpress (+{points})")

    # --- Intent scoring ---

    # Dirigeant trouvé = on sait à qui s'adresser
    if lead.director_first_name or lead.director_last_name:
        points = weights.get("has_director", 15)
        score += points
        matched.append(f"has_director (+{points})")

    qualified = score >= threshold

    if qualified:
        log.info("scoring.qualified", domain=lead.domain, score=score, criteria=matched)
    else:
        log.info("scoring.rejected", domain=lead.domain, score=score, criteria=matched)

    return ScoringResult(score=score, matched_criteria=matched, qualified=qualified)


def log_rejected(lead: EnrichedLead, scoring: ScoringResult) -> None:
    """Ajoute un lead rejeté dans data/rejected.jsonl."""
    REJECTED_FILE.parent.mkdir(parents=True, exist_ok=True)
    entry = {
        "domain": lead.domain,
        "url": lead.url,
        "score": scoring.score,
        "criteria": scoring.matched_criteria,
        "niche": lead.niche,
        "region": lead.region,
    }
    with open(REJECTED_FILE, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry, ensure_ascii=False) + "\n")
