"""Module 2: turning raw examples into a clean, validated chat dataset."""
from __future__ import annotations

import hashlib
import json
import random
import re
from dataclasses import dataclass, field
from pathlib import Path

ROLES = {"system", "user", "assistant"}


@dataclass
class Report:
    total: int = 0
    converted: int = 0
    invalid: list[tuple[int, str]] = field(default_factory=list)
    exact_duplicates: int = 0
    near_duplicates: int = 0
    redactions: int = 0
    too_long: int = 0
    train: int = 0
    valid: int = 0
    leaked: int = 0


def load_jsonl(path: str | Path) -> list[dict]:
    rows = []
    for n, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), start=1):
        if line.strip():
            try:
                rows.append(json.loads(line))
            except json.JSONDecodeError as exc:
                raise ValueError(f"line {n}: invalid JSON ({exc.msg})") from exc
    return rows


def write_jsonl(rows: list[dict], path: str | Path) -> None:
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    Path(path).write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows), encoding="utf-8")


def to_messages(row: dict, system_prompt: str | None = None) -> dict:
    """Convert common formats to {"messages": [...]}.

    Supported: {"messages": [...]}, Alpaca-style {"instruction", "input", "output"},
    and {"prompt", "completion"} strings.
    """
    if "messages" in row:
        msgs = list(row["messages"])
    elif "instruction" in row and "output" in row:
        user = row["instruction"].strip()
        if row.get("input", "").strip():
            user += "\n\n" + row["input"].strip()
        msgs = [{"role": "user", "content": user}, {"role": "assistant", "content": row["output"].strip()}]
    elif isinstance(row.get("prompt"), str) and isinstance(row.get("completion"), str):
        msgs = [{"role": "user", "content": row["prompt"].strip()},
                {"role": "assistant", "content": row["completion"].strip()}]
    else:
        raise ValueError("unrecognized format: expected messages, instruction/output, or prompt/completion")
    if system_prompt and not (msgs and msgs[0].get("role") == "system"):
        msgs = [{"role": "system", "content": system_prompt}] + msgs
    return {"messages": msgs}


def validate(example: dict) -> str | None:
    """Return a problem description, or None if the example is a valid chat transcript."""
    msgs = example.get("messages")
    if not isinstance(msgs, list) or len(msgs) < 2:
        return "needs at least a user and an assistant message"
    for i, m in enumerate(msgs):
        if not isinstance(m, dict) or m.get("role") not in ROLES:
            return f"message {i} has an invalid role"
        if not isinstance(m.get("content"), str) or not m["content"].strip():
            return f"message {i} is empty"
        if m["role"] == "system" and i != 0:
            return "system message must come first"
    turns = [m["role"] for m in msgs if m["role"] != "system"]
    if turns[0] != "user":
        return "first non-system message must be from the user"
    if any(a == b for a, b in zip(turns, turns[1:])):
        return "user and assistant turns must alternate"
    if turns[-1] != "assistant":
        return "last message must be from the assistant (that is what the model learns)"
    return None


_PII = [
    (re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"), "[EMAIL]"),
    (re.compile(r"(?<!\w)\+?\d{1,3}[ .-]?\(?\d{3}\)?[ .-]?\d{3}[ .-]?\d{4}\b"), "[PHONE]"),
    (re.compile(r"\b(?:sk|pk|ghp|xox[bp])[-_][A-Za-z0-9_-]{16,}\b"), "[SECRET]"),
]


def scrub(text: str) -> tuple[str, int]:
    count = 0
    for pattern, repl in _PII:
        text, n = pattern.subn(repl, text)
        count += n
    return text, count


def fingerprint(example: dict) -> str:
    text = " ".join(m["content"] for m in example["messages"] if m["role"] != "system")
    norm = " ".join(re.findall(r"\w+", text.lower()))
    return hashlib.sha256(norm.encode()).hexdigest()


def shingles(text: str, k: int = 1) -> set[str]:
    """Word k-grams. k=1 (word sets) works well for short texts; use k=3 to 5 for long documents."""
    words = re.findall(r"\w+", text.lower())
    return {" ".join(words[i:i + k]) for i in range(max(1, len(words) - k + 1))}


def jaccard(a: set, b: set) -> float:
    return len(a & b) / len(a | b) if a | b else 1.0


def user_text(example: dict) -> str:
    return " ".join(m["content"] for m in example["messages"] if m["role"] == "user")


def common_prefix_words(texts: list[str]) -> int:
    """Number of leading words shared by all texts (e.g. a fixed instruction in every prompt)."""
    split = [t.split() for t in texts]
    if len(split) < 2:
        return 0
    n = 0
    for words in zip(*split):
        if len(set(words)) != 1:
            break
        n += 1
    return n


def varying_part(text: str, skip_words: int) -> str:
    return " ".join(text.split()[skip_words:])


def approx_tokens(example: dict) -> int:
    """Rough token estimate (about 4 characters per token for English). Use the real tokenizer for limits."""
    return sum(len(m["content"]) for m in example["messages"]) // 4 + 4 * len(example["messages"])


def prepare(rows: list[dict], *, system_prompt: str | None = None, valid_fraction: float = 0.1,
            max_tokens: int = 2048, near_dup_threshold: float = 0.8, seed: int = 0) -> tuple[list[dict], list[dict], Report]:
    rep = Report(total=len(rows))
    clean: list[dict] = []
    for n, row in enumerate(rows, start=1):
        try:
            ex = to_messages(row, system_prompt)
        except ValueError as exc:
            rep.invalid.append((n, str(exc)))
            continue
        problem = validate(ex)
        if problem:
            rep.invalid.append((n, problem))
            continue
        for m in ex["messages"]:
            m["content"], c = scrub(m["content"])
            rep.redactions += c
        if approx_tokens(ex) > max_tokens:
            rep.too_long += 1
            continue
        clean.append(ex)
    rep.converted = len(clean)

    seen: set[str] = set()
    unique: list[dict] = []
    for ex in clean:
        fp = fingerprint(ex)
        if fp in seen:
            rep.exact_duplicates += 1
            continue
        seen.add(fp)
        unique.append(ex)

    # Compare only the part of the prompt that varies: a shared instruction would make
    # every pair look similar.
    skip = common_prefix_words([user_text(ex) for ex in unique])
    kept: list[dict] = []
    kept_sh: list[set] = []
    for ex in unique:
        sh = shingles(varying_part(user_text(ex), skip))
        if any(jaccard(sh, other) >= near_dup_threshold for other in kept_sh):
            rep.near_duplicates += 1
            continue
        kept.append(ex)
        kept_sh.append(sh)

    rng = random.Random(seed)
    order = list(range(len(kept)))
    rng.shuffle(order)
    n_valid = max(1, round(len(kept) * valid_fraction)) if len(kept) > 1 else 0
    valid = [kept[i] for i in order[:n_valid]]
    train = [kept[i] for i in order[n_valid:]]
    rep.train, rep.valid = len(train), len(valid)
    return train, valid, rep


def leakage(train: list[dict], evaluation: list[dict], threshold: float = 0.8) -> list[int]:
    """Indexes of evaluation examples whose user text is (nearly) identical to a training example."""
    skip = common_prefix_words([user_text(x) for x in train + evaluation])
    train_sh = [shingles(varying_part(user_text(t), skip)) for t in train]
    return [i for i, ex in enumerate(evaluation)
            if any(jaccard(shingles(varying_part(user_text(ex), skip)), s) >= threshold for s in train_sh)]


def length_stats(examples: list[dict]) -> dict:
    lengths = sorted(approx_tokens(e) for e in examples)
    if not lengths:
        return {"count": 0}
    pick = lambda q: lengths[min(len(lengths) - 1, int(q * len(lengths)))]  # noqa: E731
    return {"count": len(lengths), "min": lengths[0], "median": pick(0.5), "p95": pick(0.95), "max": lengths[-1],
            "total": sum(lengths)}
