"""Offline safety checks for the GPT state catalog importer."""

import importlib.util
import unittest
from pathlib import Path


SCRIPT = Path(__file__).resolve().parents[1] / "scripts/synchron/sync-gpt-states.py"
SPEC = importlib.util.spec_from_file_location("sync_gpt_states", SCRIPT)
sync = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(sync)


def source(mongo_id, code, name, **extra):
    return {
        "_id": mongo_id, "id": int(mongo_id), "state_short_name": code,
        "state_name": name, "country": 1, "pricing": "rule", **extra,
    }


class StateCatalogSyncTests(unittest.TestCase):
    def test_preserves_duplicates_but_selects_gpt_lowercase_record(self):
        rows, duplicate_codes = sync.prepare_rows([
            source("1", "AL", "alabama"), source("2", "AL", "Alabama"),
            source("3", "AB", "alberta", country=2),
        ])
        self.assertEqual(3, len(rows))
        self.assertEqual(["AL"], duplicate_codes)
        self.assertEqual(["1", "3"], [row["mongo_document_id"] for row in rows if row["is_canonical"]])
        self.assertEqual("CA", rows[2]["country_code"])

    def test_only_allowlisted_fields_and_no_nested_credentials_are_copied(self):
        rows, _ = sync.prepare_rows([source(
            "1", "TX", "texas", username="never copy", file_autofillerjs="never copy",
            provision_info={"curfew": "rule", "portal_password": "never copy",
                            "nested": {"api_key": "never copy", "escort": "rule"}},
        )])
        details = rows[0]["details"]
        self.assertNotIn("username", details)
        self.assertNotIn("file_autofillerjs", details)
        self.assertNotIn("portal_password", details["provision_info"])
        self.assertNotIn("api_key", details["provision_info"]["nested"])
        self.assertEqual("rule", details["provision_info"]["nested"]["escort"])

    def test_hash_is_repeatable_and_changes_with_rules(self):
        first, _ = sync.prepare_rows([source("1", "TX", "texas", pricing="old")])
        again, _ = sync.prepare_rows([source("1", "TX", "texas", pricing="old")])
        changed, _ = sync.prepare_rows([source("1", "TX", "texas", pricing="new")])
        self.assertEqual(first[0]["source_sha256"], again[0]["source_sha256"])
        self.assertNotEqual(first[0]["source_sha256"], changed[0]["source_sha256"])

    def test_removes_embedded_nulls_from_public_details(self):
        rows, _ = sync.prepare_rows([source(
            "1", "MO", "missouri",
            provision_info={"Document 1": "permit\x00instructions"},
        )])
        document = rows[0]["details"]["provision_info"]["Document 1"]
        self.assertEqual("permitinstructions", document)
        self.assertNotIn("\x00", document)

    def test_ambiguous_duplicate_is_rejected(self):
        with self.assertRaisesRegex(ValueError, "Ambiguous GPT-active"):
            sync.prepare_rows([source("1", "AL", "Alabama"), source("2", "AL", "Alabama")])




class AutomaticSyncTests(unittest.TestCase):
    def test_accepts_a_valid_new_state_without_fixed_counts(self):
        rows, _ = sync.prepare_rows([source('1', 'TX', 'texas'), source('2', 'CA', 'california')])
        changed, missing = sync.compare_snapshot(rows, {})
        self.assertEqual(2, len(changed))
        self.assertEqual([], missing)

    def test_empty_source_is_not_a_deletion_snapshot(self):
        with self.assertRaisesRegex(ValueError, 'Empty state source'):
            sync.compare_snapshot([], {'1': {'source_present': True}})

    def test_large_unexpected_removal_preserves_the_catalog(self):
        rows, _ = sync.prepare_rows([source('1', 'TX', 'texas')])
        with self.assertRaisesRegex(ValueError, '25 percent'):
            sync.compare_snapshot(rows, {str(n): {'source_present': True} for n in range(1, 5)})

    def test_replayed_snapshot_does_not_rewrite_unchanged_records(self):
        rows, _ = sync.prepare_rows([source('1', 'TX', 'texas')])
        old = {row['mongo_document_id']: row for row in rows}
        changed, missing = sync.compare_snapshot(rows, old)
        self.assertEqual([], changed)
        self.assertEqual([], missing)

    def test_removed_field_changes_the_content_hash(self):
        old, _ = sync.prepare_rows([source('1', 'TX', 'texas', provision_info={'escorts': 'old'})])
        new, _ = sync.prepare_rows([source('1', 'TX', 'texas')])
        changed, _ = sync.compare_snapshot(new, {row['mongo_document_id']: row for row in old})
        self.assertEqual(1, len(changed))
        self.assertNotIn('provision_info', changed[0]['details'])

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