from __future__ import annotations

import json
import unittest
from pathlib import Path

from mais_humana.reports import generate
from mais_humana.storage import table_counts
from tests.helpers import make_tmp


class FullGenerationTests(unittest.TestCase):
    def make_repo(self, root: Path, name: str, text: str) -> None:
        repo = root / name
        repo.mkdir()
        (repo / "README.md").write_text(text, encoding="utf-8")
        (repo / "src").mkdir()
        (repo / "src" / "index.ts").write_text(
            "export const health = { ok: true, readiness: 'ready', audit: true, trace: true };\n",
            encoding="utf-8",
        )
        (repo / "package.json").write_text(json.dumps({"scripts": {"test": "node --test"}}), encoding="utf-8")
        (repo / "test.spec.ts").write_text("test('ok', () => true)\n", encoding="utf-8")

    def test_generate_creates_artifacts_and_semantic_sql(self) -> None:
        tmp = make_tmp()
        root = tmp / "eco"
        project = tmp / "human"
        central = tmp / "central"
        root.mkdir()
        central.mkdir()
        self.make_repo(root, "tudo-para-ia-identity-platform", "identity health readiness RBAC openapi credentialRef")
        self.make_repo(root, "tudo-para-ia-business-platform", "business invoice entitlement checkout support")
        bundle = generate(root, project, central)
        self.assertTrue((project / "dados" / "snapshot-ecossistema.json").exists())
        self.assertTrue((project / "relatorios-docx" / "RELATORIO-GERAL-DO-ECOSSISTEMA-humana.docx").exists())
        self.assertTrue((project / "graficos" / "matriz-plataforma-perfil.svg").exists())
        self.assertTrue((project / "dados" / "mcp-provider-mais-humana.json").exists())
        self.assertTrue((project / "matrizes" / "mcp-contratos-humanos.csv").exists())
        self.assertTrue((project / "ecossistema" / "UI-RENDERER-SAME-SOURCE-POLICY.md").exists())
        self.assertTrue((central / "controle-semantico.sqlite").exists())
        counts = table_counts(central / "controle-semantico.sqlite")
        self.assertGreater(counts["files"], 0)
        self.assertGreater(counts["service_orders"], 0)
        self.assertEqual(bundle.platform_count, 14)
        self.assertGreaterEqual(bundle.matrix_cells, 14 * 12)


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