from __future__ import annotations

import re
from dataclasses import dataclass

from .knowledge import get_paths, read_text


BLOCK_RE = re.compile(
    r"(?P<header>\d{4}-\d{2}-\d{2}\s+[-—]\s+[^\n]+)\n\nFILE_UPDATE_PROPOSAL\n"
    r"Fichier cible\s*:\s*(?P<target>[^\n]+)\n\n"
    r"Pourquoi\s*:\s*\n(?P<why>.*?)\n\n"
    r"Proposition\s*:\s*\n(?P<proposal>.*?)(?=\n\n\d{4}-\d{2}-\d{2}\s+[-—]|\Z)",
    re.DOTALL,
)


@dataclass
class CapitalisationEntry:
    header: str
    target: str
    why: str
    proposal: str


def parse_capitalisation_entries(raw: str) -> list[CapitalisationEntry]:
    entries: list[CapitalisationEntry] = []
    for match in BLOCK_RE.finditer(raw):
        entries.append(
            CapitalisationEntry(
                header=match.group("header").strip(),
                target=match.group("target").strip(),
                why=match.group("why").strip(),
                proposal=match.group("proposal").strip(),
            )
        )
    return entries


def novelty_level(entry: CapitalisationEntry) -> str:
    root = get_paths().root
    target_file = (root / entry.target).resolve()
    if target_file.exists():
        target_text = read_text(target_file).lower()
        proposal_text = entry.proposal.lower()
        if proposal_text and proposal_text in target_text:
            return "DOUBLON_EXACT"

        shared = [word for word in re.findall(r"[a-zA-Z]{5,}", proposal_text) if word in target_text]
        if len(shared) >= 5:
            return "DOUBLON_SEMANTIQUE"

    return "NOUVEAU"


def scope_level(entry: CapitalisationEntry) -> str:
    low = f"{entry.why} {entry.proposal}".lower()
    project_markers = ["route", "screen", "component", "module", "label", "copy"]
    score = sum(1 for marker in project_markers if marker in low)
    return "PROJET" if score >= 2 else "GLOBAL"
