"""Acceptance checklist for closing a full operational round."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Sequence

from .models import PlatformHumanReport, ReportBundle, ServiceOrder, as_plain_data


@dataclass(slots=True)
class AcceptanceItem:
    item_id: str
    title: str
    passed: bool
    evidence: str
    required_next_action: str

    def to_dict(self) -> dict[str, object]:
        return as_plain_data(self)


@dataclass(slots=True)
class AcceptanceReport:
    items: tuple[AcceptanceItem, ...]
    passed: bool

    def to_dict(self) -> dict[str, object]:
        return as_plain_data(self)


def item(item_id: str, title: str, passed: bool, evidence: str, action: str) -> AcceptanceItem:
    return AcceptanceItem(
        item_id=item_id,
        title=title,
        passed=passed,
        evidence=evidence,
        required_next_action="nenhuma" if passed else action,
    )


def required_artifacts(project_root: Path) -> tuple[Path, ...]:
    return (
        project_root / "dados" / "snapshot-ecossistema.json",
        project_root / "dados" / "quality-gates.json",
        project_root / "dados" / "insights-operacionais.json",
        project_root / "matrizes" / "matriz-plataforma-perfil.csv",
        project_root / "graficos" / "matriz-plataforma-perfil.svg",
        project_root / "graficos" / "maturidade-por-plataforma.svg",
        project_root / "relatorios-docx" / "RELATORIO-GERAL-DO-ECOSSISTEMA-humana.docx",
        project_root / "ecossistema" / "RELATORIO-GERAL-DO-ECOSSISTEMA-humana.md",
        project_root / "ecossistema" / "QUALITY-GATE-MAIS-HUMANO.md",
        project_root / "ecossistema" / "INSIGHTS-OPERACIONAIS-MAIS-HUMANA.md",
        project_root / "pessoas-e-papeis" / "perguntas-humanas-respondidas.md",
        project_root / "pessoas-e-papeis" / "playbooks-humanos.md",
    )


def build_acceptance_report(
    project_root: Path,
    reports: Sequence[PlatformHumanReport],
    orders: Sequence[ServiceOrder],
    bundle: ReportBundle | None,
) -> AcceptanceReport:
    artifacts = required_artifacts(project_root)
    missing = [path for path in artifacts if not path.exists()]
    total_code = sum(report.scan.code_lines for report in reports)
    items = [
        item(
            "artifacts",
            "Artefatos minimos gerados",
            not missing,
            ", ".join(str(path) for path in missing[:5]) if missing else "todos encontrados",
            "Regenerar relatorios e validar paths esperados.",
        ),
        item(
            "platform_reports",
            "Relatorios por plataforma",
            len(reports) >= 14,
            f"{len(reports)} relatorios",
            "Completar catalogo ou corrigir scanner das plataformas esperadas.",
        ),
        item(
            "code_read",
            "Leitura tecnica minima",
            total_code >= 10_000,
            f"{total_code} linhas de codigo analisadas",
            "Expandir varredura para repositorios reais ou registrar limitacao material.",
        ),
        item(
            "orders",
            "Ordens de saida criadas",
            len(orders) >= 10,
            f"{len(orders)} ordens",
            "Criar 5 executivas e 5 gerenciais de saida com base nas lacunas reais.",
        ),
        item(
            "bundle",
            "Bundle de geracao completo",
            bundle is not None and bundle.matrix_cells >= 14 * 12,
            f"{bundle.matrix_cells if bundle else 0} celulas de matriz",
            "Reexecutar gerador com catalogo de perfis completo.",
        ),
    ]
    return AcceptanceReport(items=tuple(items), passed=all(entry.passed for entry in items))


def acceptance_markdown(report: AcceptanceReport) -> str:
    lines = ["# Acceptance Checklist Mais Humana", ""]
    lines.append(f"- passou: `{report.passed}`")
    lines.append("")
    for item_result in report.items:
        status = "ok" if item_result.passed else "pendente"
        lines.append(f"## {item_result.title}")
        lines.append("")
        lines.append(f"- status: `{status}`")
        lines.append(f"- evidencia: {item_result.evidence}")
        lines.append(f"- proxima acao: {item_result.required_next_action}")
        lines.append("")
    return "\n".join(lines).strip() + "\n"

