from __future__ import annotations

import unittest
from pathlib import Path

from mais_humana.catalog import get_platform
from mais_humana.evidence_index import (
    EvidenceQuery,
    build_evidence_index,
    evidence_counts_by_kind,
    evidence_gap_summary,
    evidence_markdown,
    evidence_records_for_human_surface,
    query_evidence,
)
from mais_humana.scanner import scan_platform
from tests.helpers import make_tmp


class EvidenceIndexTests(unittest.TestCase):
    def test_index_can_be_queried_by_platform_kind_and_text(self) -> None:
        root = make_tmp()
        repo = root / "tudo-para-ia-identity-platform"
        repo.mkdir()
        (repo / "README.md").write_text("identity RBAC credentialRef audit trace health readiness", encoding="utf-8")
        (repo / "src.ts").write_text("export const route = { path: '/identity/health' };\n", encoding="utf-8")
        scan = scan_platform(root, get_platform("identity"))
        records = build_evidence_index((scan,))
        self.assertTrue(records)
        identity_records = query_evidence(records, EvidenceQuery(platform_id="identity"))
        self.assertEqual(len(identity_records), len(records))
        security = query_evidence(records, EvidenceQuery(kind="security"))
        self.assertTrue(security)
        text = query_evidence(records, EvidenceQuery(text="health"))
        self.assertTrue(text)

    def test_index_markdown_and_gap_summary_are_stable(self) -> None:
        root = make_tmp()
        repo = root / "tudo-para-ia-business-platform"
        repo.mkdir()
        (repo / "README.md").write_text("business invoice entitlement checkout health", encoding="utf-8")
        scan = scan_platform(root, get_platform("business"))
        records = build_evidence_index((scan,))
        counts = evidence_counts_by_kind(records)
        self.assertTrue(counts)
        markdown = evidence_markdown(records)
        self.assertIn("Indice de evidencias", markdown)
        surface_records = evidence_records_for_human_surface(records)
        self.assertLessEqual(len(surface_records), len(records))
        gaps = evidence_gap_summary(records, ("business", "identity"))
        self.assertTrue(any("identity" in gap for gap in gaps))


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