from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path


@dataclass
class ImportReport:
    context: str
    dry_run: bool = False
    created: list[str] = field(default_factory=list)
    updated: list[str] = field(default_factory=list)
    skipped: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    errors: list[str] = field(default_factory=list)

    def add_created(self, msg: str) -> None:
        self.created.append(msg)

    def add_warning(self, msg: str) -> None:
        self.warnings.append(msg)

    def add_error(self, msg: str) -> None:
        self.errors.append(msg)

    def add_skipped(self, msg: str) -> None:
        self.skipped.append(msg)

    def merge(self, other: "ImportReport") -> None:
        self.created.extend(other.created)
        self.updated.extend(other.updated)
        self.skipped.extend(other.skipped)
        self.warnings.extend(other.warnings)
        self.errors.extend(other.errors)

    def summary_line(self) -> str:
        return (
            f"{self.context}: +{len(self.created)} créés, "
            f"{len(self.warnings)} avert., {len(self.errors)} erreur(s)"
        )

    def print_report(self) -> None:
        prefix = "[simulation] " if self.dry_run else ""
        print(f"\n=== {prefix}{self.context.upper()} ===")
        if self.created:
            print(f"  Créés ({len(self.created)}):")
            for line in self.created[:30]:
                print(f"    + {line}")
            if len(self.created) > 30:
                print(f"    … (+{len(self.created) - 30})")
        if self.warnings:
            print(f"  Avertissements ({len(self.warnings)}):")
            for line in self.warnings:
                print(f"    ! {line}")
        if self.errors:
            print(f"  Erreurs ({len(self.errors)}):")
            for line in self.errors:
                print(f"    x {line}")
        if self.skipped:
            print(f"  Ignorés ({len(self.skipped)}):")
            for line in self.skipped[:10]:
                print(f"    - {line}")
        print(f"  -> {self.summary_line()}")

    def save(self, directory: Path) -> Path:
        directory.mkdir(parents=True, exist_ok=True)
        ts = datetime.now().strftime("%Y%m%d-%H%M%S")
        path = directory / f"import-{self.context}-{ts}.txt"
        lines = [
            f"Contexte: {self.context}",
            f"Simulation: {self.dry_run}",
            f"Créés: {len(self.created)}",
            f"Avertissements: {len(self.warnings)}",
            f"Erreurs: {len(self.errors)}",
            "",
        ]
        for title, items in (
            ("CRÉÉS", self.created),
            ("AVERTISSEMENTS", self.warnings),
            ("ERREURS", self.errors),
            ("IGNORÉS", self.skipped),
        ):
            if items:
                lines.append(title)
                lines.extend(f"  {x}" for x in items)
                lines.append("")
        path.write_text("\n".join(lines), encoding="utf-8")
        return path
