"""Offline teaching fixture. No network, model calls, or production writes.
Python 3.11+. Only A/CNAME records, not a complete DNS validator.
"""
import copy
import hashlib
import ipaddress
import json
import math


def canonical_name(value):
    if not isinstance(value, str) or not value.endswith('.'):
        raise ValueError('absolute_name_required')
    name = value.lower()
    labels = name[:-1].split('.')
    if len(name.encode('ascii')) > 254 or any(
        not label or len(label) > 63 or
        any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-' for c in label) or
        label.startswith('-') or label.endswith('-') for label in labels
    ):
        raise ValueError('restricted_hostname_required')
    return name


def validate(records, zone='example.com.'):
    """Restricted hostname-only zone policy, deliberately rejects other types."""
    zone = canonical_name(zone)
    by_name = {}
    for record in records:
        if set(record) != {'name', 'type', 'ttl', 'value'}:
            raise ValueError('schema')
        name = canonical_name(record['name'])
        if name != zone and not name.endswith('.' + zone):
            raise ValueError('outside_zone')
        ttl = record['ttl']
        if type(ttl) is not int or not 30 <= ttl <= 86400:
            raise ValueError('ttl_policy')
        kind, value = record['type'], record['value']
        if kind == 'A':
            if ipaddress.ip_address(value).version != 4:
                raise ValueError('ipv4_required')
        elif kind == 'CNAME':
            canonical_name(value)
            if name == zone:
                raise ValueError('apex_cname')
        else:
            raise ValueError('unsupported_type')
        by_name.setdefault(name, []).append(record)
    for rr in by_name.values():
        if any(r['type'] == 'CNAME' for r in rr) and len(rr) != 1:
            raise ValueError('cname_conflict')
        if len({r['ttl'] for r in rr}) != 1:
            raise ValueError('rrset_ttl')
    return 'candidate'


def plan_hash(records):
    return hashlib.sha256(json.dumps(records, sort_keys=True,
                                     separators=(',', ':')).encode()).hexdigest()


def apply_gate(records, approved_hash, expected_version, actual_version):
    # Illustrates checks, not an atomic provider write or a lock.
    if expected_version != actual_version:
        raise ValueError('stale_plan')
    if plan_hash(records) != approved_hash:
        raise ValueError('changed_plan')
    return validate(records)


def diagnose(authority, recursive, now):
    """Suggest a hypothesis and next test; never claims proven root cause."""
    required = {'name', 'type', 'view', 'at', 'rcode', 'answer', 'source'}
    if not authority or not required <= authority.keys() or not required <= recursive.keys():
        return 'investigate'
    if any(not 0 <= now - o['at'] <= 60 for o in (authority, recursive)):
        return 'investigate'
    if any(authority[k] != recursive[k] for k in ('name', 'type', 'view')):
        return 'investigate'
    ttl = recursive.get('negative_ttl')
    if (authority['source'] == 'authoritative' and
        recursive['source'] == 'recursive' and
        authority['rcode'] == 'NOERROR' and authority['answer'] and
        recursive['rcode'] == 'NXDOMAIN' and not recursive['answer'] and
        type(ttl) is int and ttl - (now - recursive['at']) > 0):
        return 'negative_cache_candidate'
    return 'investigate'


def run_checks():
    checks = 0
    def reject(fn):
        nonlocal checks
        try:
            fn()
        except (ValueError, UnicodeError):
            checks += 1
        else:
            raise AssertionError('unsafe candidate accepted')
    clean = [{'name': 'api.example.com.', 'type': 'A',
              'ttl': 300, 'value': '192.0.2.20'}]
    assert validate(clean) == 'candidate'
    checks += 1
    for patch in ({'value': 'not-an-ip'}, {'value': '2001:db8::1'},
                  {'name': 'api.otherexample.com.'}, {'ttl': True}, {'ttl': 0},
                  {'name': 'api.example.com'}, {'type': 'TXT'}, {'extra': 1}):
        bad = copy.deepcopy(clean)
        bad[0].update(patch)
        reject(lambda: validate(bad))
    alias = {'name': 'api.example.com.', 'type': 'CNAME',
             'ttl': 300, 'value': 'edge.example.net.'}
    reject(lambda: validate(clean + [alias]))
    reject(lambda: validate([dict(alias, name='example.com.')]))
    reject(lambda: validate(clean + [dict(clean[0], ttl=600, value='192.0.2.10')]))
    digest = plan_hash(clean)
    assert apply_gate(clean, digest, 'v1', 'v1') == 'candidate'
    checks += 1
    reject(lambda: apply_gate(clean, digest, 'v1', 'v2'))
    reject(lambda: apply_gate([dict(clean[0], ttl=600)], digest, 'v1', 'v1'))
    auth = {'name': 'api.example.com.', 'type': 'A', 'view': 'public',
            'at': 180, 'rcode': 'NOERROR', 'answer': ['192.0.2.20'],
            'source': 'authoritative'}
    rec = dict(auth, source='recursive', rcode='NXDOMAIN', answer=[], negative_ttl=720)
    assert diagnose(auth, rec, 180) == 'negative_cache_candidate'
    checks += 1
    for a, r, now in ((None, rec, 180), (auth, dict(rec, view='private'), 180),
                      (auth, rec, 241), (auth, dict(rec, negative_ttl=0), 180),
                      (auth, dict(rec, rcode='SERVFAIL'), 180),
                      (auth, dict(rec, type='AAAA'), 180),
                      (dict(auth, answer=[]), rec, 180),
                      (auth, dict(rec, at=200), 180)):
        assert diagnose(a, r, now) == 'investigate'
        checks += 1
    tp, fn, fp = 100 * .95, 100 * .05, 999900 * .001
    precision = tp / (tp + fp)
    assert math.isclose(precision, .086765914695406, rel_tol=1e-12)
    checks += 1
    print(f'checks={checks} clean=candidate stale_plan=rejected cache=negative_cache_candidate')
    print(f'synthetic_tp={tp:.0f} fn={fn:.0f} fp={fp:.1f} precision={precision:.4%}')


if __name__ == '__main__':
    run_checks()
