#!/usr/bin/env python3
"""Offline POSIX teaching experiment: real writer/reader processes and temp files.

Run without arguments. The --reader branch is an internal child-process mode.
No network, service changes, crash injection, fsync, or shared project files.
"""
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path
import platform
import select
import stat
import subprocess
import sys
import tempfile

OLD = b'old-complete\n'
NEW = b'new-complete\n'
PREFIX = b'new-'
OLD_EDITED = b'old-modified\n'


def identity(info):
    return info.st_dev, info.st_ino


def mode_text(info):
    return format(stat.S_IMODE(info.st_mode), '04o')


def content(data):
    return {'text': data.decode('ascii'), 'bytes': len(data),
            'sha256': hashlib.sha256(data).hexdigest()}


def snapshot(held, target):
    held.seek(0)
    result = {'held': content(held.read())}
    held_stat = os.fstat(held.fileno())
    result['heldLinks'] = held_stat.st_nlink
    result['heldMode'] = mode_text(held_stat)
    try:
        with target.open('rb', buffering=0) as fresh:
            result['fresh'] = content(fresh.read())
            fresh_stat = os.fstat(fresh.fileno())
            result['freshMode'] = mode_text(fresh_stat)
            result['heldMatchesFreshIdentity'] = identity(held_stat) == identity(fresh_stat)
    except FileNotFoundError:
        result['freshError'] = 'FileNotFoundError'
    return result


def reader_main(target):
    held = target.open('rb', buffering=0)
    try:
        print(json.dumps({'ready': True}), flush=True)
        for command in sys.stdin:
            command = command.strip()
            if command == 'reopen':
                held.close()
                held = target.open('rb', buffering=0)
            else:
                assert command == 'snapshot'
            print(json.dumps(snapshot(held, target)), flush=True)
    finally:
        held.close()


def receive(process):
    ready, _, _ = select.select([process.stdout], [], [], 10)
    if not ready:
        raise TimeoutError('Reader did not respond within 10 seconds')
    line = process.stdout.readline()
    if not line:
        raise RuntimeError('Reader exited before replying')
    return json.loads(line)


@contextmanager
def reader(target):
    process = subprocess.Popen(
        [sys.executable, '-u', str(Path(__file__).resolve()), '--reader', str(target)],
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1,
    )
    try:
        assert receive(process) == {'ready': True}
        yield process
    finally:
        process.stdin.close()
        try:
            process.wait(timeout=10)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait()
            raise
        finally:
            process.stdout.close()
    assert process.returncode == 0


def observe(process, phase, command='snapshot'):
    process.stdin.write(command + '\n')
    process.stdin.flush()
    return {'phase': phase, **receive(process)}


def initial_target(root, name):
    folder = root / name
    folder.mkdir()
    target = folder / 'current.txt'
    target.write_bytes(OLD)
    target.chmod(0o644)
    return target


def publish_once(target, data, mode=0o644):
    fd, name = tempfile.mkstemp(prefix=f'.{target.name}.', dir=target.parent)
    candidate = Path(name)
    try:
        with os.fdopen(fd, 'wb') as output:
            os.fchmod(output.fileno(), mode)
            output.write(data)
        os.replace(candidate, target)
    finally:
        candidate.unlink(missing_ok=True)


def main():
    if os.name != 'posix':
        raise SystemExit('This experiment requires a POSIX environment; Windows is not tested.')
    timelines = {}
    with tempfile.TemporaryDirectory(prefix='gumi-file-replace-') as directory:
        root = Path(directory)
        target = initial_target(root, 'in-place')
        original_identity = identity(target.stat())
        with reader(target) as process:
            rows = [observe(process, 'before')]
            with target.open('wb', buffering=0) as output:
                rows.append(observe(process, 'truncated'))
                assert output.write(PREFIX) == len(PREFIX)
                rows.append(observe(process, 'prefix-written'))
                assert output.write(NEW[len(PREFIX):]) == len(NEW) - len(PREFIX)
                rows.append(observe(process, 'complete'))
        for row, expected in zip(rows, [OLD, b'', PREFIX, NEW]):
            assert row['held'] == row['fresh'] == content(expected)
            assert row['heldMatchesFreshIdentity'] is True
        assert identity(target.stat()) == original_identity
        timelines['inPlace'] = rows

        target = initial_target(root, 'replace')
        with target.open('r+b', buffering=0) as retained_writer, reader(target) as process:
            rows = [observe(process, 'before')]
            fd, name = tempfile.mkstemp(prefix='.candidate-', dir=target.parent)
            candidate = Path(name)
            candidate_identity = identity(candidate.stat())
            with os.fdopen(fd, 'wb', buffering=0) as output:
                assert output.write(PREFIX) == len(PREFIX)
                rows.append(observe(process, 'candidate-prefix-written'))
                assert output.write(NEW[len(PREFIX):]) == len(NEW) - len(PREFIX)
            rows.append(observe(process, 'candidate-complete'))
            candidate_mode = mode_text(candidate.stat())
            assert candidate_mode == '0600'
            os.replace(candidate, target)
            assert not candidate.exists()
            assert identity(target.stat()) == candidate_identity
            rows.append(observe(process, 'replaced'))
            retained_writer.seek(0)
            assert retained_writer.write(OLD_EDITED) == len(OLD_EDITED)
            retained_writer.truncate()
            rows.append(observe(process, 'old-object-written'))
            rows.append(observe(process, 'reader-reopened', command='reopen'))
        for row in rows[:3]:
            assert row['held'] == row['fresh'] == content(OLD)
        changed = rows[3]
        assert changed['held'] == content(OLD) and changed['fresh'] == content(NEW)
        assert changed['heldMatchesFreshIdentity'] is False and changed['heldLinks'] == 0
        assert changed['heldMode'] == '0644' and changed['freshMode'] == '0600'
        assert rows[4]['held'] == content(OLD_EDITED) and rows[4]['fresh'] == content(NEW)
        assert rows[4]['heldMatchesFreshIdentity'] is False
        assert rows[5]['held'] == rows[5]['fresh'] == content(NEW)
        assert rows[5]['heldMatchesFreshIdentity'] is True
        timelines['replace'] = rows

        target = initial_target(root, 'delete-then-rename')
        candidate = target.with_name('next.txt')
        candidate.write_bytes(NEW)
        candidate.chmod(0o644)
        with reader(target) as process:
            rows = [observe(process, 'before')]
            target.unlink()
            rows.append(observe(process, 'name-deleted'))
            os.replace(candidate, target)
            rows.append(observe(process, 'name-restored'))
        assert rows[1]['held'] == content(OLD)
        assert rows[1]['freshError'] == 'FileNotFoundError' and rows[1]['heldLinks'] == 0
        assert rows[2]['held'] == content(OLD) and rows[2]['fresh'] == content(NEW)
        timelines['deleteThenRename'] = rows

        target = initial_target(root, 'helper-success')
        publish_once(target, NEW, mode=0o644)
        assert target.read_bytes() == NEW and mode_text(target.stat()) == '0644'
        assert sorted(p.name for p in target.parent.iterdir()) == ['current.txt']
        helper_success = {'content': content(target.read_bytes()),
                          'mode': mode_text(target.stat()), 'candidateCleaned': True}

        target = initial_target(root, 'missing-source')
        before = identity(target.stat())
        try:
            os.replace(target.with_name('absent.txt'), target)
        except FileNotFoundError as error:
            missing_error = type(error).__name__
        else:
            raise AssertionError('Missing source unexpectedly succeeded')
        assert identity(target.stat()) == before and target.read_bytes() == OLD

        target = initial_target(root, 'abort-before-publish')
        before = identity(target.stat())
        candidate = target.with_name('candidate.txt')
        try:
            candidate.write_bytes(PREFIX)
            raise RuntimeError('Deliberate teaching error before replace')
        except RuntimeError as error:
            abort_error = type(error).__name__
        finally:
            candidate.unlink()
        assert identity(target.stat()) == before and target.read_bytes() == OLD

        folder = root / 'helper-directory-error'
        folder.mkdir()
        target = folder / 'directory-target'
        target.mkdir()
        marker = target / 'keep.txt'
        marker.write_bytes(OLD)
        try:
            publish_once(target, NEW)
        except IsADirectoryError as error:
            directory_error = type(error).__name__
        else:
            raise AssertionError('File unexpectedly replaced nonempty directory')
        assert marker.read_bytes() == OLD
        assert sorted(p.name for p in folder.iterdir()) == ['directory-target']

    report = {
        'experiment': 'Controlled file publication with independent POSIX reader processes',
        'runDate': '2026-11-01',
        'environment': {'python': platform.python_version(), 'system': platform.system(),
                        'macOS': platform.mac_ver()[0], 'machine': platform.machine()},
        'fixtures': {'old': content(OLD), 'new': content(NEW), 'prefix': content(PREFIX),
                     'oldEdited': content(OLD_EDITED)},
        'timelines': timelines,
        'boundaries': {
            'candidateDefaultMode': candidate_mode,
            'helperSuccess': helper_success,
            'missingSource': {'error': missing_error, 'oldContentAndIdentityPreserved': True},
            'abortBeforePublish': {'error': abort_error, 'oldContentAndIdentityPreserved': True},
            'helperDirectoryFailure': {'error': directory_error, 'markerPreserved': True,
                                       'candidateCleaned': True},
        },
        'checks': {'readerProcesses': 3, 'controlledSnapshots': sum(map(len, timelines.values())),
                   'allAssertionsPassed': True},
        'limits': [
            'Pipe acknowledgements select observation points; no sleeps, stress statistics or crash simulation.',
            'Each held reader is unbuffered and seeks to offset zero before each snapshot.',
            'Identity comparisons use (st_dev, st_ino); unstable numeric IDs and temporary paths are omitted.',
            'Candidates and targets are on the same local temporary filesystem.',
            'No Windows, network filesystem, competing writer, mmap, ACL, ownership or service reload test.',
            'No fsync or power-loss durability claim; publish_once only illustrates single-file visibility.',
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    if len(sys.argv) == 3 and sys.argv[1] == '--reader':
        reader_main(Path(sys.argv[2]))
    elif len(sys.argv) == 1:
        main()
    else:
        raise SystemExit('Run without arguments; --reader is internal to the experiment.')
