from __future__ import annotations

import unittest
from pathlib import Path

from mais_humana.router000_exit_orders import (
    Router000PlatformTarget,
    build_platform_order_batch,
    render_order_markdown,
    run_router000_exit_orders,
)
from mais_humana.storage import table_counts
from tests.helpers import make_tmp


class Router000ExitOrderTests(unittest.TestCase):
    def target(self, root: Path) -> Router000PlatformTarget:
        return Router000PlatformTarget(
            central_folder_name="01_repo_sample-platform",
            project_id="sample-plataform",
            repo_name="sample-plataform",
            real_repo=str(root / "sample-plataform"),
            owner_role="sample_owner",
            primary_focus=("docs_full", "mcp_acceptance"),
        )

    def test_order_batch_has_five_executive_and_five_managerial_orders(self) -> None:
        root = make_tmp()
        central = root / "central"
        target = self.target(root)
        existing_dir = central / target.central_folder_name / "orders" / "executivas"
        existing_dir.mkdir(parents=True)
        (existing_dir / "0007_EXECUTIVA__existing.md").write_text("existing\n", encoding="utf-8")

        orders = build_platform_order_batch(target, central)

        self.assertEqual(len(orders), 10)
        self.assertEqual(sum(1 for order in orders if order.order_type == "EXECUTIVA"), 5)
        self.assertEqual(sum(1 for order in orders if order.order_type == "GERENCIAL"), 5)
        self.assertEqual(orders[0].sequence, 8)
        self.assertTrue(orders[0].order_id.startswith("0008_EXECUTIVA__router000-"))
        managerial = [order for order in orders if order.order_type == "GERENCIAL"][0]
        self.assertEqual(managerial.sequence, 1)

    def test_rendered_order_contains_five_fronts_with_five_themes_each(self) -> None:
        root = make_tmp()
        central = root / "central"
        order = build_platform_order_batch(self.target(root), central)[0]

        markdown = render_order_markdown(order)

        self.assertIn("# ORDEM DE SERVICO:", markdown)
        self.assertEqual(markdown.count("## Frente "), 5)
        self.assertIn("Temas:\n1.", markdown)
        self.assertIn("5. Criar pendencia automatica quando a resposta documental nao existir.", markdown)
        self.assertIn("workspace-write", markdown)
        self.assertIn("Nao vazar valor de token", markdown)

    def test_run_writes_orders_summary_and_semantic_records(self) -> None:
        root = make_tmp()
        ecosystem = root / "ecosystem"
        project_root = root / "mais-humana"
        central = root / "central"
        target = self.target(ecosystem)
        (central / target.central_folder_name).mkdir(parents=True)
        project_root.mkdir(parents=True)

        report, records = run_router000_exit_orders(
            ecosystem_root=ecosystem,
            project_root=project_root,
            central_projects_root=central,
            targets=(target,),
        )

        self.assertEqual(report.platforms_written, 1)
        self.assertEqual(report.executive_orders, 5)
        self.assertEqual(report.managerial_orders, 5)
        self.assertTrue((project_root / "dados" / "router000-exit-orders.json").exists())
        self.assertTrue((project_root / "matrizes" / "router000-exit-orders.csv").exists())
        self.assertTrue((central / target.central_folder_name / "orders" / "executivas").exists())
        self.assertEqual(len([record for record in records if record.file_type == "markdown"]), 11)
        counts = table_counts(central / target.central_folder_name / "controle-semantico.sqlite")
        self.assertGreaterEqual(counts.get("files", 0), 10)


if __name__ == "__main__":
    unittest.main()
