from __future__ import annotations

import json
import unittest
from pathlib import Path

from mais_humana.catalog import get_platform
from mais_humana.cli import main
from mais_humana.insights import build_insights, dependency_dot, insights_markdown
from mais_humana.matrix import build_global_recommendations, build_matrix, build_platform_reports
from mais_humana.orders import build_exit_orders, order_markdown
from mais_humana.scanner import scan_platform
from tests.helpers import make_tmp


class OrdersInsightsCliTests(unittest.TestCase):
    def make_reports(self, root: Path):
        for platform_id in ("identity", "business"):
            platform = get_platform(platform_id)
            repo = root / platform.repo_name
            repo.mkdir()
            (repo / "README.md").write_text(
                f"# {platform.title}\nhealth readiness audit trace screen support invoice entitlement",
                encoding="utf-8",
            )
            (repo / "src").mkdir()
            (repo / "src" / "index.ts").write_text(
                "export const routes = [{ path: '/health' }, { path: '/openapi' }];\n",
                encoding="utf-8",
            )
        scans = tuple(scan_platform(root, get_platform(pid)) for pid in ("identity", "business"))
        cells = build_matrix(scans)
        return build_platform_reports(scans, cells)

    def test_orders_are_created_from_recommendations(self) -> None:
        tmp = make_tmp()
        reports = self.make_reports(tmp)
        recommendations = build_global_recommendations(reports)
        orders = build_exit_orders(recommendations)
        self.assertGreaterEqual(len(orders), 2)
        markdown = order_markdown(orders[0], "central", "tudo-para-ia-mais-humana")
        self.assertIn("ORDEM DE SERVICO", markdown)
        self.assertIn("criterio de pronto", markdown.lower())

    def test_insights_include_risks_roadmap_and_dependencies(self) -> None:
        tmp = make_tmp()
        reports = self.make_reports(tmp)
        recommendations = build_global_recommendations(reports)
        insights = build_insights(reports, recommendations)
        self.assertTrue(insights.dependencies)
        self.assertTrue(insights.risks)
        self.assertTrue(insights.roadmap)
        self.assertIn("digraph", dependency_dot(insights))
        self.assertIn("Roadmap", insights_markdown(insights))

    def test_cli_env_returns_success(self) -> None:
        tmp = make_tmp()
        code = main(["env", "--ecosystem-root", str(tmp)])
        self.assertEqual(code, 0)

    def test_cli_sql_counts_handles_empty_missing_file(self) -> None:
        tmp = make_tmp()
        missing = tmp / "missing.sqlite"
        code = main(["sql-counts", "--sqlite", str(missing)])
        self.assertEqual(code, 0)


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