main
John Lauer Profile preferences are listed for tools, never written as KiCad rules: KiCad applies one rule per constraint, so a war… 7195b16
"""Published records vs profiles (John, 2026-11-03): a record is the fab's PUBLISHED limits and nothing else;
anyone's stricter margins or text-size taste live in rules/profiles/, chosen by the user. These tests keep
comfort margins from creeping back into a record, keep frozen profiles at their reviewed bytes, and check
that overrides and preferences build."""
import hashlib, importlib.util, json, re, unittest
from pathlib import Path
BASE = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('rules', BASE / 'tools' / 'generate.py')
g = importlib.util.module_from_spec(spec); spec.loader.exec_module(g)
PROFILES = sorted((BASE / 'rules' / 'profiles').glob('*.json'))
# wording that means "this value is not what the fab publishes": it belongs in a profile
NOT_PUBLISHED = re.compile(r'\b(conservative|applied to every layer|not used separately|stricter than the|our own margin)\b', re.I)


def records():
    for f in sorted((BASE / 'rules' / 'records').glob('*.json')):
        d = json.loads(f.read_text(encoding='utf-8'))
        for r in d['records']:
            yield f.name, d['vendor'], r


class PublishedRecords(unittest.TestCase):
    def test_records_carry_no_comfort_margins(self):
        for name, vendor, rec in records():
            for key, v in rec.items():
                if isinstance(v, dict):
                    text = ' '.join(str(x) for x in v.values() if isinstance(x, str))
                    self.assertIsNone(NOT_PUBLISHED.search(text), f'{name} {vendor} {rec["process"]} {rec["layerCount"]}L {key}: "{text[:120]}" reads as a margin, not a published limit; put it in a profile')

    def test_records_have_no_profile_flags(self):
        for name, vendor, rec in records():
            self.assertNotIn('kicadStrict', rec, f'{name}: strictness is a profile, not a record flag')


class Profiles(unittest.TestCase):
    def test_every_profile_names_author_reason_and_published_base(self):
        recs = {(json.loads(f.read_text())['vendorSlug'], r['process'], r['layerCount']) for f in (BASE / 'rules' / 'records').glob('*.json') for r in json.loads(f.read_text())['records']}
        self.assertTrue(PROFILES)
        for pf in PROFILES:
            p = json.loads(pf.read_text())
            for k in ('name', 'author', 'why', 'vendorSlug', 'process', 'layerCount'):
                self.assertTrue(p.get(k), f'{pf.name}: {k}')
            self.assertIn((p['vendorSlug'], p['process'], p['layerCount']), recs, pf.name)

    def test_frozen_profiles_keep_their_reviewed_bytes(self):
        for pf in PROFILES:
            p = json.loads(pf.read_text())
            for ext, fz in (p.get('frozen') or {}).items():
                self.assertEqual(hashlib.sha256((BASE / fz['file']).read_bytes()).hexdigest(), fz['sha256'], f'{pf.name} {ext}')
                vs = g.file_slug(p['vendorSlug'], p['process'], p['layerCount']) + '-' + g.slugify(p['name'])
                out = BASE / g.OUT_DIRS[ext] / f'{vs}.{ext}'
                self.assertEqual(out.read_bytes(), (BASE / fz['file']).read_bytes(), f'{out.name} is the published copy of the frozen profile')

    def test_circuit_forge_strict_keeps_the_hashes_its_gate_checks(self):
        self.assertEqual(hashlib.sha256((BASE / 'kicad/pcbway-4L-circuit-forge-strict.kicad_dru').read_bytes()).hexdigest(), 'ed114795f294b9e6355627166f0d557132d848f2325389c8f54b0b7cf7ee0ef4')
        self.assertEqual(hashlib.sha256((BASE / 'kicad/pcbway-4L-circuit-forge-strict.board-setup.json').read_bytes()).hexdigest(), '01edbd0b23d3bbe4807e6428dc24ca4dfe320bb4986a963db44c914e4d33a9a5')

    def test_overrides_are_errors_and_preferences_stay_out_of_the_rules_files(self):
        rec = [r for _, v, r in records() if v == 'PCBWay' and r['process'] == 'standard' and r['layerCount'] == 2][0]
        rec = {**rec, 'vendor': 'PCBWay'}
        tighter = g.merged(rec, {'minTraceWidth': {'mm': 0.2}})
        self.assertEqual(tighter['minTraceWidth']['mm'], 0.2)
        self.assertEqual(rec['minTraceWidth']['mm'] != 0.2, True, 'the record itself is untouched')
        # preferences are validated and listed for tools, never written as KiCad rules: KiCad applies one rule per
        # constraint to an item, so a preference rule would replace the fab's error-level limit
        self.assertEqual(g.check_preferences({'silkMinTextHeight': {'mm': 0.6}}, 't'), {'silkMinTextHeight': {'mm': 0.6}})
        with self.assertRaises(SystemExit):
            g.check_preferences({'unknownThing': {'mm': 1}}, 't')
        with self.assertRaises(SystemExit):
            g.check_preferences({'minTraceWidth': {'mm': -1}}, 't')

    def test_index_lists_profiles_beside_their_published_pack(self):
        idx = json.loads((BASE / 'rules' / 'index.json').read_text())
        e = next(e for e in idx['vendors'] if (e['vendorSlug'], e['process'], e['layerCount']) == ('pcbway', 'standard', 4))
        names = [p['name'] for p in e.get('profiles', [])]
        self.assertIn('circuit-forge-strict', names)
        self.assertEqual(e['files']['kicadDru'], 'kicad/pcbway-4L.kicad_dru', 'the published pack keeps its file')


if __name__ == '__main__':
    unittest.main(verbosity=2)