#!/usr/bin/env python3
"""Journaled installation of the managed kit. No package or service operations."""
import argparse
import base64
import fcntl
import hashlib
import importlib.util
import json
import os
import re
import stat
import sys
import time
import uuid
from pathlib import Path

LIMIT = 4 * 1024 * 1024
JOURNAL_LIMIT = 64 * 1024 * 1024
ID_RE = re.compile(r'^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{32}$')
SHARED = ('.claude-swap-backup/kit-version', '.claude/CLAUDE.md', '.claude/settings.json', '.zshrc')


class TransactionError(Exception):
    pass


def digest(data):
    return hashlib.sha256(data).hexdigest()


def sync_dir(path):
    fd = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    try:
        os.fsync(fd)
    finally:
        os.close(fd)


def durable_mkdir(path):
    """Ensure directory entries have a parent barrier, including after retries."""
    path = Path(path)
    if not path.is_absolute():
        raise TransactionError('directory path must be absolute')
    current = Path('/')
    for part in path.parts[1:]:
        parent = current
        current = current / part
        try:
            info = os.lstat(str(current))
        except FileNotFoundError:
            try:
                os.mkdir(str(current), 0o700)
            except FileExistsError:
                pass
            info = os.lstat(str(current))
        if stat.S_ISLNK(info.st_mode):
            try:
                info = os.stat(str(current))
            except OSError:
                raise TransactionError('dangling directory symlink') from None
        if not stat.S_ISDIR(info.st_mode):
            raise TransactionError('directory path is unsafe')
        # An existing entry may be the result of an earlier mkdir whose fsync
        # failed. Reestablish its parent barrier before descending on retry.
        sync_dir(Path(os.path.realpath(str(parent))))


def atomic_write(path, data, mode):
    path = Path(path)
    temp = path.parent / ('.overclaude-tmp-' + uuid.uuid4().hex)
    try:
        fd = os.open(str(temp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
        try:
            with os.fdopen(fd, 'wb', closefd=False) as stream:
                stream.write(data)
                stream.flush()
            os.fchmod(fd, mode)
            os.fsync(fd)
        finally:
            os.close(fd)
        os.replace(str(temp), str(path))
        sync_dir(path.parent)
    finally:
        try:
            temp.unlink()
        except FileNotFoundError:
            pass


def read_regular(path, allow_absent=False, limit=LIMIT):
    try:
        fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    except FileNotFoundError:
        if allow_absent:
            return None
        raise
    try:
        st = os.fstat(fd)
        if not stat.S_ISREG(st.st_mode) or st.st_size > limit:
            raise TransactionError('target is not a bounded regular file')
        data = b''
        while len(data) <= limit:
            part = os.read(fd, min(65536, limit + 1 - len(data)))
            if not part:
                break
            data += part
        if len(data) > limit:
            raise TransactionError('target exceeds size limit')
        return data, stat.S_IMODE(st.st_mode)
    finally:
        os.close(fd)


def validate_ancestors(home, rel):
    """Reject dangling or non-directory ancestors before resolving a target."""
    current = home
    for part in Path(rel).parts[:-1]:
        current = current / part
        try:
            info = os.lstat(str(current))
        except FileNotFoundError:
            return
        if stat.S_ISLNK(info.st_mode):
            try:
                info = os.stat(str(current))
            except (FileNotFoundError, OSError):
                raise TransactionError('dangling or unsafe destination ancestor: ' + rel) from None
        if not stat.S_ISDIR(info.st_mode):
            raise TransactionError('destination ancestor is not a directory: ' + rel)


def snapshot(home, rel, allow_link):
    validate_ancestors(home, rel)
    logical = home / rel
    try:
        st = os.lstat(str(logical))
    except FileNotFoundError:
        # A missing destination under a dangling intermediate symlink is unsafe.
        if os.path.lexists(str(logical)):
            raise TransactionError('invalid destination')
        return {'link': None, 'target': os.path.realpath(str(logical)), 'exists': False, 'mode': None, 'data': None, 'sha256': None}
    link = None
    if stat.S_ISLNK(st.st_mode):
        if not allow_link:
            raise TransactionError('managed payload destination is a symlink: ' + rel)
        link = os.readlink(str(logical))
    elif not stat.S_ISREG(st.st_mode):
        raise TransactionError('destination is not a regular file: ' + rel)
    target = os.path.realpath(str(logical))
    item = read_regular(target, allow_absent=False)
    data, mode = item
    return {'link': link, 'target': target, 'exists': True, 'mode': mode,
            'data': base64.b64encode(data).decode('ascii'), 'sha256': digest(data)}


def same(a, b):
    return all(a.get(k) == b.get(k) for k in ('link', 'target', 'exists', 'mode', 'data', 'sha256'))


def read_payload(payload):
    source = payload / 'src/overclaude/verify.py'
    if not source.is_file():
        source = payload.parent / 'verify.py'
    spec = importlib.util.spec_from_file_location('overclaude_install_verify', str(source))
    if not spec or not spec.loader:
        raise TransactionError('bundled verifier is unavailable')
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def store_manifest(directory, manifest):
    data = (json.dumps(manifest, sort_keys=True, separators=(',', ':')) + '\n').encode()
    if len(data) > JOURNAL_LIMIT:
        raise TransactionError('transaction journal exceeds size limit')
    atomic_write(directory / 'journal.json', data, 0o600)


def setup(home):
    base = home / '.claude-swap-backup'
    durable_mkdir(base)
    if base.is_symlink() or not base.is_dir():
        raise TransactionError('unsafe backup directory')
    root = base / 'install-transactions'
    durable_mkdir(root)
    if root.is_symlink() or not root.is_dir():
        raise TransactionError('unsafe transaction directory')
    os.chmod(str(root), 0o700)
    lockfd = os.open(str(root / '.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    if not stat.S_ISREG(os.fstat(lockfd).st_mode):
        os.close(lockfd)
        raise TransactionError('unsafe transaction lock')
    try:
        fcntl.flock(lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(lockfd)
        raise TransactionError('another install or recovery is running') from None
    return root, lockfd


def load_journal(root, ident, allowed, home):
    if not ID_RE.fullmatch(ident):
        raise TransactionError('invalid transaction id')
    directory = root / ident
    if directory.is_symlink() or not directory.is_dir():
        raise TransactionError('transaction is unavailable')
    raw, _ = read_regular(directory / 'journal.json', limit=JOURNAL_LIMIT)
    try:
        value = json.loads(raw)
    except (ValueError, UnicodeError, RecursionError):
        raise TransactionError('invalid transaction journal') from None
    if not isinstance(value, dict) or value.get('id') != ident or value.get('version') != 1 or value.get('home') != str(home) or value.get('state') not in ('prepared', 'applying', 'committed', 'rolled_back', 'conflict', 'recovered-with-edits') or not isinstance(value.get('entries'), list):
        raise TransactionError('invalid transaction journal')
    seen = set()
    for item in value['entries']:
        if not isinstance(item, dict) or item.get('rel') not in allowed or item['rel'] in seen or item.get('status') not in ('planned', 'intent', 'applied', 'rolled_back', 'skipped', 'conflict', 'retained'):
            raise TransactionError('invalid transaction entry')
        seen.add(item['rel'])
        for field in ('before', 'after'):
            snap = item.get(field)
            if not isinstance(snap, dict) or type(snap.get('exists')) is not bool or not isinstance(snap.get('target'), str) or not os.path.isabs(snap['target']) or (snap.get('link') is not None and not isinstance(snap.get('link'), str)):
                raise TransactionError('invalid transaction snapshot')
            if snap['exists']:
                if type(snap.get('mode')) is not int or not 0 <= snap['mode'] <= 0o7777 or not isinstance(snap.get('data'), str):
                    raise TransactionError('invalid transaction snapshot')
                try:
                    data = base64.b64decode(snap['data'], validate=True)
                except ValueError:
                    raise TransactionError('invalid transaction data') from None
                if len(data) > LIMIT or snap.get('sha256') != digest(data):
                    raise TransactionError('invalid transaction data')
            elif snap.get('data') is not None or snap.get('mode') is not None or snap.get('link') is not None or snap.get('sha256') is not None:
                raise TransactionError('invalid absent snapshot')
        if not item['after']['exists'] or item['before']['target'] != item['after']['target'] or item['before']['link'] != item['after']['link']:
            raise TransactionError('invalid transaction target')
    if seen != allowed:
        raise TransactionError('transaction entries are incomplete')
    if value['state'] == 'committed' and any(item['status'] not in ('applied', 'skipped') for item in value['entries']):
        raise TransactionError('invalid committed transaction')
    if value['state'] == 'rolled_back' and any(item['status'] not in ('planned', 'skipped', 'rolled_back') for item in value['entries']):
        raise TransactionError('invalid rolled-back transaction')
    if value['state'] == 'recovered-with-edits':
        if (not any(item['status'] == 'retained' for item in value['entries']) or
                any(item['status'] not in ('planned', 'skipped', 'rolled_back', 'retained') for item in value['entries']) or
                any(not isinstance(item.get('retainedEvidence'), dict) for item in value['entries'] if item['status'] == 'retained')):
            raise TransactionError('invalid retained-conflict evidence')
    elif any(item['status'] == 'retained' for item in value['entries']):
        raise TransactionError('invalid retained-conflict state')
    return directory, value


def marker(hook):
    command = hook.get('command', '')
    if command.startswith('bash '):
        command = command[5:]
    return command.rsplit('/', 1)[-1]


def merge_settings(raw, fragment):
    if raw is None or not raw.strip():
        current = {}
    else:
        try:
            current = json.loads(raw)
        except (ValueError, UnicodeError, RecursionError):
            raise TransactionError('settings.json is not a JSON object') from None
    if not isinstance(current, dict):
        raise TransactionError('settings.json is not a JSON object')
    permissions = current.setdefault('permissions', {})
    hooks = current.setdefault('hooks', {})
    if not isinstance(permissions, dict) or not isinstance(hooks, dict):
        raise TransactionError('settings permissions or hooks are invalid')
    allow = permissions.setdefault('allow', [])
    if not isinstance(allow, list):
        raise TransactionError('settings permissions are invalid')
    for value in fragment['permissions']['allow']:
        if value not in allow:
            allow.append(value)
    for event, groups in fragment['hooks'].items():
        existing = hooks.setdefault(event, [])
        if not isinstance(existing, list):
            raise TransactionError('settings hooks are invalid')
        for group in groups:
            name = marker(group['hooks'][0])
            found = any(name in candidate.get('command', '') for entry in existing if isinstance(entry, dict)
                        for candidate in entry.get('hooks', []) if isinstance(candidate, dict) and isinstance(candidate.get('command', ''), str))
            if not found:
                existing.append(group)
                if event == 'StopFailure' and 'ratelimit' in name:
                    print('  [!] Instant swap is ON: usage limits can switch accounts.')
                if event == 'PreToolUse' and 'route-guard' in name:
                    print('  [!] Routing guard is ON: agent launches are checked.')
    if current.get('statusLine') is None:
        current['statusLine'] = fragment['statusLine']
    elif current['statusLine'] != fragment['statusLine']:
        print('  [!] custom statusLine retained; kit context relay may be unavailable')
    return (json.dumps(current, ensure_ascii=False, indent=2) + '\n').encode()


def plan(payload, home, version, verifier):
    if not version or '\n' in version or '\r' in version:
        raise TransactionError('kit version is unavailable')
    specs = [(src, rel, mode, False) for src, rel, mode in verifier.FILES]
    specs += [(None, rel, None, rel != SHARED[0]) for rel in SHARED]
    if len({rel for _, rel, _, _ in specs}) != len(specs):
        raise TransactionError('duplicate managed destination')
    snapshots, targets = {}, set()
    # Capture every preimage before deriving or writing any desired content.
    for _, rel, _, link in specs:
        snap = snapshot(home, rel, link)
        if snap['target'] in targets:
            raise TransactionError('managed destinations resolve to the same target')
        targets.add(snap['target']); snapshots[rel] = snap
    fragment_data, _ = read_regular(payload / 'settings/settings-fragment.json')
    fragment = json.loads(fragment_data)
    snippet, _ = read_regular(payload / 'shell/zshrc-snippet.sh')
    entries = []
    for src, rel, mode, _ in specs:
        before = snapshots[rel]
        old = base64.b64decode(before['data']) if before['exists'] else None
        if src:
            desired, _ = read_regular(payload / src)
        elif rel == SHARED[0]:
            desired = (version + '\n').encode()
        elif rel == SHARED[1]:
            desired = old or b''
            if b'@ULTRACODE.md' not in desired.splitlines():
                desired += (b'\n' if desired and not desired.endswith(b'\n') else b'') + b'@ULTRACODE.md\n'
        elif rel == SHARED[2]:
            desired = merge_settings(old, fragment)
            # Preserve formatting on semantically identical JSON.
            if old and json.loads(old) == json.loads(desired):
                desired = old
        else:
            desired = old or b''
            if b'# --- claude-swap integration (begin) ---' not in desired:
                desired += (b'\n' if desired and not desired.endswith(b'\n') else b'') + (b'\n' if desired else b'') + snippet
                print('  [!] Open a new shell or source ~/.zshrc')
        if len(desired) > LIMIT:
            raise TransactionError('desired file exceeds size limit')
        target_mode = mode if mode is not None else (before['mode'] if before['exists'] else 0o644)
        after = dict(before, exists=True, mode=target_mode, data=base64.b64encode(desired).decode('ascii'), sha256=digest(desired))
        entries.append({'rel': rel, 'before': before, 'after': after, 'status': 'planned'})
    return entries


def apply_snapshot(home, rel, wanted, expected, allow_link):
    current = snapshot(home, rel, allow_link)
    if not same(current, expected):
        raise TransactionError('concurrent change detected: ' + rel)
    target = Path(wanted['target'])
    if wanted['exists']:
        durable_mkdir(target.parent)
        # Recheck after directory creation and immediately before replacement.
        if not same(snapshot(home, rel, allow_link), expected):
            raise TransactionError('concurrent change detected: ' + rel)
        atomic_write(target, base64.b64decode(wanted['data'], validate=True), wanted['mode'])
    else:
        target.unlink()
        sync_dir(target.parent)


def rollback(directory, journal, home):
    conflicts = []
    for item in reversed(journal['entries']):
        if item['status'] not in ('intent', 'applied', 'conflict'):
            continue
        rel, before, after = item['rel'], item['before'], item['after']
        try:
            current = snapshot(home, rel, rel in SHARED[1:])
            if same(current, before):
                item['status'] = 'rolled_back'
            elif same(current, after):
                apply_snapshot(home, rel, before, after, rel in SHARED[1:])
                item['status'] = 'rolled_back'
            else:
                item['status'] = 'conflict'; conflicts.append(rel)
        except (OSError, TransactionError, ValueError):
            item['status'] = 'conflict'; conflicts.append(rel)
        store_manifest(directory, journal)
    journal['state'] = 'conflict' if conflicts else 'rolled_back'
    store_manifest(directory, journal)
    return conflicts


def retain_conflicts(directory, journal, home):
    """Record current conflicting state without modifying any managed target."""
    for item in journal['entries']:
        if item['status'] != 'conflict':
            continue
        rel = item['rel']
        validate_ancestors(home, rel)
        logical = home / rel
        try:
            current = snapshot(home, rel, rel in SHARED[1:])
            evidence = {key: current[key] for key in ('exists', 'link', 'target', 'mode', 'sha256')}
        except (FileNotFoundError, TransactionError):
            # Describe the entry itself when it cannot safely be opened; never
            # follow a retained symlink or open a special file.
            try:
                info = os.lstat(str(logical))
            except FileNotFoundError:
                evidence = {'exists': False}
            else:
                evidence = {'exists': True, 'kind': 'symlink' if stat.S_ISLNK(info.st_mode) else 'special',
                            'mode': stat.S_IMODE(info.st_mode)}
                if stat.S_ISLNK(info.st_mode):
                    evidence['link'] = os.readlink(str(logical))
        item['retainedEvidence'] = evidence
        item['status'] = 'retained'
    journal['state'] = 'recovered-with-edits'
    store_manifest(directory, journal)


def main():
    parser = argparse.ArgumentParser(allow_abbrev=False)
    parser.add_argument('--payload', required=True)
    sub = parser.add_subparsers(dest='action', required=True)
    p = sub.add_parser('apply', allow_abbrev=False); p.add_argument('--version', required=True)
    sub.add_parser('list', allow_abbrev=False)
    p = sub.add_parser('recover', allow_abbrev=False); p.add_argument('--transaction', required=True); p.add_argument('--keep-current', action='store_true')
    args = parser.parse_args()
    home = Path(os.path.realpath(os.path.expanduser('~')))
    payload = Path(os.path.realpath(args.payload))
    lockfd = None
    try:
        verifier = read_payload(payload)
        allowed = {rel for _, rel, _ in verifier.FILES} | set(SHARED)
        root, lockfd = setup(home)
        if args.action == 'list':
            output = []
            for path in sorted(root.iterdir()):
                if ID_RE.fullmatch(path.name):
                    _, item = load_journal(root, path.name, allowed, home)
                    output.append({'id': path.name, 'state': item['state']})
            print(json.dumps(output)); return 0
        if args.action == 'recover':
            directory, journal = load_journal(root, args.transaction, allowed, home)
            if journal['state'] in ('committed', 'recovered-with-edits'):
                raise TransactionError('terminal transactions cannot be rolled back')
            conflicts = rollback(directory, journal, home)
            if conflicts and args.keep_current:
                retain_conflicts(directory, journal, home)
            elif conflicts:
                print('Conflicts preserved; after reviewing, run overclaude recover --transaction ' + args.transaction + ' --keep-current to retain them.', file=sys.stderr)
            print(json.dumps({'id': args.transaction, 'state': journal['state'], 'conflicts': conflicts}))
            return 1 if conflicts and not args.keep_current else 0
        for path in root.iterdir():
            if ID_RE.fullmatch(path.name):
                _, previous = load_journal(root, path.name, allowed, home)
                if previous['state'] not in ('committed', 'rolled_back', 'recovered-with-edits'):
                    raise TransactionError('pending transaction requires recovery: ' + path.name)
        entries = plan(payload, home, args.version, verifier)
        ident = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '-' + uuid.uuid4().hex
        directory = root / ident
        staging = root / ('.staging-' + uuid.uuid4().hex)
        staging.mkdir(mode=0o700)
        journal = {'version': 1, 'id': ident, 'home': str(home), 'state': 'prepared', 'entries': entries}
        try:
            store_manifest(staging, journal)
            sync_dir(staging)
            if os.path.lexists(str(directory)):
                raise TransactionError('transaction id already exists')
            os.rename(str(staging), str(directory))
            sync_dir(root)
        finally:
            if staging.exists():
                try:
                    (staging / 'journal.json').unlink(missing_ok=True)
                    staging.rmdir()
                except OSError:
                    pass
        commit_started = False
        try:
            journal['state'] = 'applying'; store_manifest(directory, journal)
            for item in entries:
                if same(item['before'], item['after']):
                    item['status'] = 'skipped'; continue
                item['status'] = 'intent'; store_manifest(directory, journal)
                apply_snapshot(home, item['rel'], item['after'], item['before'], item['rel'] in SHARED[1:])
                item['status'] = 'applied'; store_manifest(directory, journal)
            errors, notes = verifier.verify(payload, home, args.version)
            for note in notes: print('  [!] ' + note)
            if errors:
                for error in errors: print('  [!] ' + error, file=sys.stderr)
                raise TransactionError('offline verification failed')
            journal['state'] = 'committed'; commit_started = True
            store_manifest(directory, journal)
            print('  [+] managed files verified; transaction ' + ident)
            return 0
        except BaseException:
            if commit_started:
                # A failed directory fsync may follow a visible committed rename.
                # Never start rollback after a commit marker could have landed.
                try:
                    _, recorded = load_journal(root, ident, allowed, home)
                except (OSError, TransactionError, ValueError, TypeError):
                    print('install: commit state is uncertain; inspect transaction ' + ident, file=sys.stderr)
                    raise
                if recorded['state'] == 'committed':
                    print('install: commit marker is present; service activation was skipped', file=sys.stderr)
                    raise
                journal = recorded
            conflicts = rollback(directory, journal, home)
            if conflicts:
                print('install: recovery conflicts preserved: ' + ', '.join(conflicts), file=sys.stderr)
            raise
    except (TransactionError, OSError, ValueError, TypeError, KeyError, UnicodeError, RecursionError) as exc:
        print('install transaction: ' + (str(exc) if isinstance(exc, TransactionError) else 'operation failed'), file=sys.stderr)
        return 1
    finally:
        if lockfd is not None:
            os.close(lockfd)


if __name__ == '__main__':
    sys.exit(main())
