"""Status-page markdown writers for the central management dossier."""

from __future__ import annotations

from pathlib import Path
from typing import Sequence

from .models import PlatformHumanReport, ReportBundle, ServiceOrder


def current_project_state_markdown(bundle: ReportBundle, reports: Sequence[PlatformHumanReport]) -> str:
    avg = round(sum(report.average_score for report in reports) / len(reports)) if reports else 0
    lines = [
        "# Estado atual - tudo-para-ia-mais-humana",
        "",
        "## Identidade",
        "",
        "- project_id: `tudo-para-ia-mais-humana`",
        "- repo_name: `tudo-para-ia-mais-humana`",
        "- papel: plataforma de traducao humana do ecossistema",
        "- status: `ativo_em_fundacao`",
        "",
        "## Estado material",
        "",
        f"- plataformas avaliadas: `{bundle.platform_count}`",
        f"- perfis humanos: `{bundle.profile_count}`",
        f"- celulas de matriz: `{bundle.matrix_cells}`",
        f"- linhas de codigo analisadas: `{bundle.total_code_lines_analyzed}`",
        f"- score medio humano: `{avg}`",
        f"- arquivos gerados ou alterados: `{len(bundle.generated_files)}`",
        "",
        "## Plataformas com menor score",
        "",
    ]
    for report in sorted(reports, key=lambda item: item.average_score)[:8]:
        lines.append(f"- {report.platform.platform_id}: `{report.average_score}`")
    lines.append("")
    lines.append("## Proxima acao correta")
    lines.append("")
    lines.append("Executar as ordens de saida ativas e comparar novo snapshot contra esta fundacao.")
    return "\n".join(lines) + "\n"


def orders_index_markdown(orders: Sequence[ServiceOrder]) -> str:
    lines = ["# Indice de ordens - tudo-para-ia-mais-humana", ""]
    for order in orders:
        lines.append(f"- `{order.order_id}` | `{order.order_type.value}` | `{order.status.value}` | {order.title}")
    return "\n".join(lines) + "\n"


def reports_index_markdown(bundle: ReportBundle) -> str:
    lines = ["# Indice de relatorios - tudo-para-ia-mais-humana", ""]
    for file in sorted(bundle.generated_files, key=lambda item: item.path):
        if file.file_type in {"markdown", "docx", "svg", "html"}:
            lines.append(f"- `{file.path}` - {file.description}")
    return "\n".join(lines) + "\n"


def pending_index_markdown(reports: Sequence[PlatformHumanReport]) -> str:
    lines = ["# Indice de pendencias - tudo-para-ia-mais-humana", ""]
    found = False
    for report in sorted(reports, key=lambda item: item.platform.platform_id):
        for warning in report.scan.warnings:
            found = True
            lines.append(f"- `{report.platform.platform_id}` - {warning}")
    if not found:
        lines.append("- Nenhuma pendencia material detectada.")
    return "\n".join(lines) + "\n"


def write_central_status_pages(
    central_folder: Path,
    bundle: ReportBundle,
    reports: Sequence[PlatformHumanReport],
    orders: Sequence[ServiceOrder],
) -> tuple[Path, ...]:
    paths: list[Path] = []
    current = central_folder / "current"
    indexes = central_folder / "indexes"
    status = central_folder / "status"
    for folder in (current, indexes, status):
        folder.mkdir(parents=True, exist_ok=True)
    pages = {
        current / "current-project-state.md": current_project_state_markdown(bundle, reports),
        current / "active-order-queue.md": orders_index_markdown(orders),
        indexes / "orders-index.md": orders_index_markdown(orders),
        indexes / "reports-index.md": reports_index_markdown(bundle),
        indexes / "pending-index.md": pending_index_markdown(reports),
        status / "overview.md": current_project_state_markdown(bundle, reports),
    }
    for path, content in pages.items():
        path.write_text(content, encoding="utf-8")
        paths.append(path)
    return tuple(paths)

