"""Week 18: policy fixtures plus a separate Linux-container runtime probe.

Default all runs safe fixtures only and explicitly reports runtime evidence missing.
Use --lesson 1 --runtime-probe ONLY inside the exact restricted container taught
in the lesson. The probe uses synthetic paths, loopback networking and one child.
"""
import argparse
import hashlib
import json
import os
import socket
import subprocess
import sys
import tempfile
from pathlib import Path


def runtime_probe():
    if sys.platform != 'linux' or not Path('/.dockerenv').exists():
        raise RuntimeError('Use the documented disposable Linux container command')
    allowed = Path('/work/allowed.txt')
    assert allowed.read_text(encoding='utf-8').strip() == 'synthetic allowed'
    scratch = Path('/tmp/worker-output.txt')
    scratch.write_text('safe scratch', encoding='utf-8')
    denied = []
    for target in [allowed, Path('/forbidden-root.txt')]:
        try:
            target.write_text('probe', encoding='utf-8')
        except OSError:
            denied.append(str(target))
    assert len(denied) == 2, denied
    assert not Path('/host-secret-canary').exists()
    assert os.getenv('ACADEMY_SYNTHETIC_SECRET') is None
    # Loopback stays usable within the network namespace; no external recipient.
    with socket.socket() as listener:
        listener.bind(('127.0.0.1', 0)); listener.listen(1)
        with socket.create_connection(listener.getsockname(), timeout=1):
            connection, _ = listener.accept(); connection.close()
    network_denied = False
    try:
        with socket.create_connection(('192.0.2.1', 9), timeout=0.3):
            pass
    except OSError:
        network_denied = True
    assert network_denied
    import resource
    address_limit, _ = resource.getrlimit(resource.RLIMIT_AS)
    assert 0 < address_limit <= 100000000, address_limit
    memory_denied = False
    try:
        bytearray(128 * 1024 * 1024)
    except MemoryError:
        memory_denied = True
    assert memory_denied, 'Expected safe address-space allocation denial'
    soft, hard = resource.getrlimit(resource.RLIMIT_NPROC)
    assert soft == 1, (soft, hard)
    child_denied = False
    try:
        subprocess.run([sys.executable, '-c', 'print("unexpected child")'], check=True, timeout=2)
    except OSError:
        child_denied = True
    assert child_denied, 'Child creation unexpectedly succeeded; inspect user and ulimit'
    memory = Path('/sys/fs/cgroup/memory.max')
    if memory.exists():
        assert int(memory.read_text().strip()) <= 134217728
    else:
        raise RuntimeError('Expected cgroup v2 memory.max for this runtime proof')
    print(json.dumps({'runtime': 'observed', 'allowed': ['read mount', 'scratch write', 'loopback'],
        'denied': denied + ['unmounted host canary', 'external route', 'child process', '128 MiB allocation'],
        'memory_limit_bytes': memory.read_text().strip(), 'process_limit': soft}))


def lesson1(root):
    (root / 'allowed.txt').write_text('synthetic allowed', encoding='utf-8')
    assert (root / 'allowed.txt').read_text(encoding='utf-8') == 'synthetic allowed'
    print('PASS fixture preparation only; OS-enforced runtime competency NOT completed.')
    print('Run documented Docker command with --runtime-probe for observed isolation evidence.')


def authorized(request, approval, now):
    fields = ['project', 'actor', 'operation_id', 'destination', 'payload_digest']
    if not isinstance(request, dict) or not isinstance(approval, dict):
        return False
    if any(type(record.get(key)) is not str or not record[key]
           for record in (request, approval) for key in fields):
        return False
    if any(type(value) is not int or value < 0 for value in
           (request.get('size'), approval.get('max_size'), approval.get('expires'), now)):
        return False
    return (all(request[key] == approval[key] for key in fields)
            and now < approval['expires'] and request['size'] <= approval['max_size'])


def lesson2(root):
    digest = hashlib.sha256(b'synthetic export').hexdigest()
    request = {'project': 'p1', 'actor': 'worker1', 'operation_id': 'export7',
        'destination': 'local-report', 'payload_digest': digest, 'size': 16}
    approval = dict(request, expires=100, max_size=20)
    assert authorized(request, approval, 90)
    assert not authorized(dict(request, destination='other'), approval, 90)
    assert not authorized(dict(request, project='p2'), approval, 90)
    assert not authorized(request, approval, 100)
    assert not authorized(dict(request, operation_id='export8'), approval, 90)
    for field in ['project', 'actor', 'operation_id', 'destination', 'payload_digest']:
        missing_request = dict(request); missing_request.pop(field)
        missing_approval = dict(approval); missing_approval.pop(field)
        assert not authorized(missing_request, missing_approval, 90)
        assert not authorized(dict(request, **{field: None}), dict(approval, **{field: None}), 90)
    assert not authorized(dict(request, size=-1), approval, 90)
    assert not authorized(dict(request, size=True), approval, 90)
    print('PASS exact request allowed; changed/missing/null scope, invalid size and expiry denied')


def lesson3(root):
    canary = 'SYNTHETIC-PRIVATE-219'
    records = [
        {'operation_id': 'x1', 'actor': 'worker1', 'approval': 'a1', 'policy': 'v2',
         'decision': 'allow', 'effect': 'local-export-1', 'payload_bytes': len(canary)},
        {'operation_id': 'x2', 'actor': 'worker1', 'approval': None, 'policy': 'v2',
         'decision': 'deny', 'effect': None, 'reason': 'approval_missing'}]
    path = root / 'audit.json'
    path.write_text(json.dumps(records), encoding='utf-8')
    text = path.read_text(encoding='utf-8')
    assert canary not in text
    loaded = json.loads(text)
    assert loaded[0]['effect'] and loaded[1]['effect'] is None
    print('PASS reconstruct allowed/denied effects without storing synthetic secret')


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--lesson', choices=['1', '2', '3', 'all'], default='all')
    parser.add_argument('--runtime-probe', action='store_true')
    args = parser.parse_args()
    if args.runtime_probe:
        if args.lesson != '1':
            parser.error('--runtime-probe requires --lesson 1')
        runtime_probe()
        return
    with tempfile.TemporaryDirectory(prefix='academy-w18-') as folder:
        for number, function in enumerate([lesson1, lesson2, lesson3], 1):
            if args.lesson in ('all', str(number)):
                function(Path(folder))


if __name__ == '__main__':
    main()
