"""Reconcile central status pages with governance, lifecycle, and assurance."""

from __future__ import annotations

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

from .governance_models import EcosystemGovernancePortfolio, RoundExecutionPackage
from .human_readiness_registry import ReadinessRegistry, registry_gap_actions
from .models import as_plain_data, merge_unique
from .round_assurance import AssuranceSuite, assurance_pending_items
from .runtime_budget import RoundLineBudget, budget_pending_items
from .workflow_registry import WorkflowPortfolio, workflow_action_items
from .governance_scenarios import ScenarioPortfolio, scenario_action_items


@dataclass(slots=True)
class ReconciledStatus:
    project_id: str
    status_label: str
    current_state_lines: tuple[str, ...]
    pending_lines: tuple[str, ...]
    index_lines: tuple[str, ...]
    release_lines: tuple[str, ...]

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


def status_label(portfolio: EcosystemGovernancePortfolio, assurance: AssuranceSuite | None) -> str:
    if assurance is not None and assurance.blocker_count:
        return "parcial-com-blockers-de-assurance"
    if portfolio.blocked_platforms:
        return "parcial-com-blockers-de-governanca"
    if portfolio.average_governance_score >= 82:
        return "controlado"
    if portfolio.average_governance_score >= 62:
        return "explicavel"
    return "fundacao"


def build_current_state_lines(
    portfolio: EcosystemGovernancePortfolio,
    registry: ReadinessRegistry,
    workflows: WorkflowPortfolio,
    scenarios: ScenarioPortfolio,
    lifecycle: RoundExecutionPackage | None,
    budget: RoundLineBudget | None,
    assurance: AssuranceSuite | None,
) -> tuple[str, ...]:
    lines = [
        "- project_id: `tudo-para-ia-mais-humana`",
        "- papel: plataforma de traducao humana, governanca operacional e continuidade por evidencias",
        f"- status: `{status_label(portfolio, assurance)}`",
        f"- score_governanca_medio: `{portfolio.average_governance_score}`",
        f"- plataformas_bloqueadas: `{len(portfolio.blocked_platforms)}`",
        f"- registros_prontidao: `{len(registry.entries)}`",
        f"- workflows: `{len(workflows.evaluations)}`",
        f"- cenarios: `{len(scenarios.evaluations)}`",
    ]
    if lifecycle is not None:
        lines.extend(
            [
                f"- ordens_lidas: `{len(lifecycle.parsed_orders)}`",
                f"- ordens_concluidas: `{lifecycle.completed_count}`",
                f"- ordens_parciais: `{lifecycle.partial_count}`",
                f"- ordens_bloqueadas: `{lifecycle.blocked_count}`",
            ]
        )
    if budget is not None:
        lines.extend(
            [
                f"- linhas_tecnicas_lidas: `{budget.total_technical_lines}`",
                f"- linhas_codigo_total: `{budget.total_code_lines}`",
                f"- minimo_leitura_ok: `{budget.reading_minimum_met}`",
                f"- minimo_producao_ok: `{budget.production_minimum_met}`",
            ]
        )
    if assurance is not None:
        lines.extend(
            [
                f"- assurance_passed: `{assurance.passed}`",
                f"- assurance_blockers: `{assurance.blocker_count}`",
                f"- assurance_warnings: `{assurance.warning_count}`",
            ]
        )
    return tuple(lines)


def build_pending_lines(
    portfolio: EcosystemGovernancePortfolio,
    registry: ReadinessRegistry,
    workflows: WorkflowPortfolio,
    scenarios: ScenarioPortfolio,
    lifecycle: RoundExecutionPackage | None,
    budget: RoundLineBudget | None,
    assurance: AssuranceSuite | None,
) -> tuple[str, ...]:
    lines: list[str] = []
    lines.extend(portfolio.blockers_summary)
    lines.extend(registry_gap_actions(registry, limit=15))
    lines.extend(workflow_action_items(workflows, limit=15))
    lines.extend(scenario_action_items(scenarios, limit=15))
    if lifecycle is not None:
        lines.extend(lifecycle.pending_items)
    if budget is not None:
        lines.extend(budget_pending_items(budget))
    if assurance is not None:
        lines.extend(assurance_pending_items(assurance))
    return merge_unique(lines)[:80]


def build_index_lines(portfolio: EcosystemGovernancePortfolio) -> tuple[str, ...]:
    lines = [
        "- `dados/governanca-operacional.json` - portfolio completo de governanca",
        "- `dados/governanca-operacional-compacta.json` - leitura compacta do estado",
        "- `dados/registro-prontidao-humana.json` - matriz plataforma x perfil x governanca",
        "- `dados/workflows-humanos.json` - workflows humanos avaliados",
        "- `dados/cenarios-governanca.json` - cenarios de aceite",
        "- `dados/grafo-evidencias.json` - grafo de checks, evidencias, workflows e ordens",
        "- `dados/budget-linhas-rodada.json` - leitura e producao de codigo da rodada",
        "- `dados/assurance-rodada.json` - assurance final",
    ]
    for candidate in portfolio.order_candidates[:20]:
        lines.append(f"- candidata `{candidate.candidate_id}` - {candidate.title}")
    return tuple(lines)


def build_release_lines(portfolio: EcosystemGovernancePortfolio, assurance: AssuranceSuite | None) -> tuple[str, ...]:
    if assurance is not None and assurance.blocker_count:
        return (
            "Release operacional nao deve ser promovido sem tratar blockers de assurance.",
            "O codigo e artefatos podem ficar commitados como avanco material, mas a proxima OS deve atacar blockers listados.",
        )
    if portfolio.blocked_platforms:
        return (
            "Release gerencial permitido como registro de avancos, com pendencias materiais explicitas.",
            "Promocao de maturidade do ecossistema deve aguardar resolucao das plataformas bloqueadas.",
        )
    return (
        "Release gerencial apto para continuidade.",
        "Manter regressao de governanca, workflows, cenarios e assurance em toda rodada.",
    )


def build_reconciled_status(
    portfolio: EcosystemGovernancePortfolio,
    registry: ReadinessRegistry,
    workflows: WorkflowPortfolio,
    scenarios: ScenarioPortfolio,
    lifecycle: RoundExecutionPackage | None = None,
    budget: RoundLineBudget | None = None,
    assurance: AssuranceSuite | None = None,
) -> ReconciledStatus:
    return ReconciledStatus(
        project_id="tudo-para-ia-mais-humana",
        status_label=status_label(portfolio, assurance),
        current_state_lines=build_current_state_lines(portfolio, registry, workflows, scenarios, lifecycle, budget, assurance),
        pending_lines=build_pending_lines(portfolio, registry, workflows, scenarios, lifecycle, budget, assurance),
        index_lines=build_index_lines(portfolio),
        release_lines=build_release_lines(portfolio, assurance),
    )


def current_state_markdown(status: ReconciledStatus) -> str:
    lines = ["# Estado atual reconciliado - tudo-para-ia-mais-humana", ""]
    lines.extend(status.current_state_lines)
    lines.extend(["", "## Release", ""])
    lines.extend(f"- {item}" for item in status.release_lines)
    return "\n".join(lines).strip() + "\n"


def pending_index_markdown(status: ReconciledStatus) -> str:
    lines = ["# Indice de pendencias reconciliadas - tudo-para-ia-mais-humana", ""]
    if status.pending_lines:
        lines.extend(f"- {item}" for item in status.pending_lines)
    else:
        lines.append("- Nenhuma pendencia material reconciliada.")
    return "\n".join(lines).strip() + "\n"


def reports_index_markdown(status: ReconciledStatus) -> str:
    lines = ["# Indice reconciliado de artefatos - tudo-para-ia-mais-humana", ""]
    lines.extend(status.index_lines)
    return "\n".join(lines).strip() + "\n"


def released_markdown(status: ReconciledStatus) -> str:
    lines = ["# Status de release gerencial - tudo-para-ia-mais-humana", ""]
    lines.append(f"- status: `{status.status_label}`")
    lines.extend(f"- {item}" for item in status.release_lines)
    return "\n".join(lines).strip() + "\n"


def write_reconciled_status(platform_folder: Path, status: ReconciledStatus) -> tuple[Path, ...]:
    current = platform_folder / "current"
    indexes = platform_folder / "indexes"
    status_dir = platform_folder / "status"
    for folder in (current, indexes, status_dir):
        folder.mkdir(parents=True, exist_ok=True)
    pages = {
        current / "current-project-state.md": current_state_markdown(status),
        indexes / "pending-index.md": pending_index_markdown(status),
        indexes / "reports-index.md": reports_index_markdown(status),
        status_dir / "overview.md": current_state_markdown(status),
        status_dir / "released.md": released_markdown(status),
    }
    written: list[Path] = []
    for path, content in pages.items():
        path.write_text(content, encoding="utf-8")
        written.append(path)
    return tuple(written)
