"""Public contract export for the Mais Humana platform."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Sequence

from .catalog import HUMAN_NEEDS, HUMAN_PROFILES, PLATFORMS
from .models import PlatformHumanReport, ReportBundle, as_plain_data, utc_now


@dataclass(slots=True)
class ContractSurface:
    surface_id: str
    title: str
    description: str
    output_files: tuple[str, ...]
    consumers: tuple[str, ...]

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


@dataclass(slots=True)
class MaisHumanaContract:
    contract_version: str
    generated_at: str
    platform_id: str
    mission: str
    surfaces: tuple[ContractSurface, ...]
    profile_ids: tuple[str, ...]
    platform_ids: tuple[str, ...]
    need_ids: tuple[str, ...]
    report_count: int
    matrix_cells: int
    total_code_lines: int

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


def default_surfaces() -> tuple[ContractSurface, ...]:
    return (
        ContractSurface(
            surface_id="ecosystem_report",
            title="Relatorio geral humano",
            description="Leitura executiva do ecossistema por pessoas, plataformas, lacunas e riscos.",
            output_files=(
                "ecossistema/RELATORIO-GERAL-DO-ECOSSISTEMA-humana.md",
                "relatorios-docx/RELATORIO-GERAL-DO-ECOSSISTEMA-humana.docx",
            ),
            consumers=("CEO", "planejamento estrategico", "central de OS"),
        ),
        ContractSurface(
            surface_id="platform_reports",
            title="Relatorios por plataforma",
            description="Leitura por plataforma com perfis atendidos, gaps, evidencias e recomendacoes.",
            output_files=("plataformas/*.md", "relatorios-docx/plataformas/*.docx"),
            consumers=("gestor operacional", "suporte", "juridico", "financeiro"),
        ),
        ContractSurface(
            surface_id="human_matrix",
            title="Matriz plataforma x perfil",
            description="Tabela de score que mostra quem e atendido por qual plataforma.",
            output_files=("matrizes/matriz-plataforma-perfil.csv", "graficos/matriz-plataforma-perfil.svg"),
            consumers=("planejamento estrategico", "MCP", "UI Platform"),
        ),
        ContractSurface(
            surface_id="quality_gate",
            title="Quality Gate Mais Humano",
            description="Separacao entre readiness tecnico e prontidao para leitura humana.",
            output_files=("ecossistema/QUALITY-GATE-MAIS-HUMANO.md", "dados/quality-gates.json"),
            consumers=("gestor operacional", "auditoria", "central de OS"),
        ),
        ContractSurface(
            surface_id="service_orders",
            title="Ordens orientadoras",
            description="Ordens executivas e gerenciais criadas a partir de lacunas reais.",
            output_files=("os-orientadoras/ordens-de-saida.json", "central/orders/**/*.md"),
            consumers=("Codex", "nucleo de gestao operacional"),
        ),
    )


def build_contract(bundle: ReportBundle, reports: Sequence[PlatformHumanReport]) -> MaisHumanaContract:
    return MaisHumanaContract(
        contract_version="mais-humana.contract.v1",
        generated_at=utc_now(),
        platform_id="tudo-para-ia-mais-humana",
        mission=(
            "Traduzir o estado tecnico do ecossistema Tudo Para IA em compreensao humana, "
            "metas de atendimento, visao por perfil, relatorios executivos e orientacao de OS."
        ),
        surfaces=default_surfaces(),
        profile_ids=tuple(profile.profile_id for profile in HUMAN_PROFILES),
        platform_ids=tuple(platform.platform_id for platform in PLATFORMS),
        need_ids=tuple(need.need_id for need in HUMAN_NEEDS),
        report_count=len(reports),
        matrix_cells=bundle.matrix_cells,
        total_code_lines=bundle.total_code_lines_analyzed,
    )


def contract_markdown(contract: MaisHumanaContract) -> str:
    lines = [
        "# Contrato publico - tudo-para-ia-mais-humana",
        "",
        f"- contract_version: `{contract.contract_version}`",
        f"- generated_at: `{contract.generated_at}`",
        f"- platform_id: `{contract.platform_id}`",
        f"- report_count: `{contract.report_count}`",
        f"- matrix_cells: `{contract.matrix_cells}`",
        f"- total_code_lines: `{contract.total_code_lines}`",
        "",
        "## Missao",
        "",
        contract.mission,
        "",
        "## Surfaces",
        "",
    ]
    for surface in contract.surfaces:
        lines.append(f"### {surface.title}")
        lines.append("")
        lines.append(f"- surface_id: `{surface.surface_id}`")
        lines.append("")
        lines.append(surface.description)
        lines.append("")
        lines.append("Arquivos:")
        for output in surface.output_files:
            lines.append(f"- `{output}`")
        lines.append("")
        lines.append("Consumidores:")
        for consumer in surface.consumers:
            lines.append(f"- {consumer}")
        lines.append("")
    return "\n".join(lines).strip() + "\n"
