import sys
import gzip
import hashlib
import tempfile
import unittest
from pathlib import Path

from replay_native_proposals import evidence_sha, native_only, records

sys.path.insert(0, str(Path(__file__).resolve().parent.parent /
                       "pangenome-reference-cv-20261014/inference-v2/code"))
from context_inference import emission_rows, gene_evidence_rows


class NativeProposalTests(unittest.TestCase):
    def test_archived_fragment_digest_and_records(self):
        payload = b'{"fragment":"r","candidates":{}}\n'
        with tempfile.TemporaryDirectory() as folder:
            path = Path(folder) / "fragments.jsonl"
            with gzip.open(str(path) + ".gz", "wb") as stream:
                stream.write(payload)
            self.assertEqual(evidence_sha(path), hashlib.sha256(payload).hexdigest())
            self.assertEqual(list(records(path)), [{"fragment": "r", "candidates": {}}])

    def test_population_alias_kept_and_normalization_recomputed(self):
        native, graph = "IPD:HLA-A*PG123", "PG123#0#HLA_A"
        metadata = {native: {"source": "graph"}, graph: {"source": "graph"}}
        def placement(score):
            return {"score": score, "gene_overlap": True, "internal": True,
                    "gene_penalty": score, "gene_bases": 150}
        data = [{"fragment": "r1", "candidates": {
            native: [placement(0)], graph: [placement(20)]}},
            {"fragment": "r2", "candidates": {graph: [placement(30)]}}]
        ids, rows = emission_rows(native_only(data), metadata)
        self.assertEqual(ids, ["r1"])
        self.assertEqual(rows, [{native: 1.0}])
        self.assertEqual(gene_evidence_rows(native_only(data), ids), [{native: 0}])
        # The older include_graph=False control would incorrectly drop the
        # population alias along with the graph route.
        self.assertEqual(emission_rows(data, metadata, include_graph=False), ([], []))
        self.assertIn(graph, data[0]["candidates"])

    def test_native_only_evidence_is_unchanged(self):
        data = [{"fragment": "r", "candidates": {"IPD:A*01:01:01:01": []}}]
        self.assertEqual(list(native_only(data)), data)


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