#!/usr/bin/env python3
"""Save and inspect explicit, cwd-scoped checkpoint snapshots."""
import argparse
import hashlib
import json
import os
import re
import stat
import sys
import time
import uuid

MAX_BYTES = 32768
SECTIONS = ('Goal', 'Current state', 'Decisions', 'Validation', 'Next steps', 'Work in flight', 'Artifacts')
ID_RE = re.compile(r'^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{32}$')
SESSION_RE = re.compile(r'^[A-Za-z0-9_-]{1,128}$')


class CheckpointError(Exception):
    pass


def _directory(parent, name, create):
    if create:
        try:
            os.mkdir(name, 0o700, dir_fd=parent)
            os.fsync(parent)
        except FileExistsError:
            pass
    fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
    return fd


def _scope(cwd, create):
    cwd = os.path.realpath(cwd)
    if not os.path.isdir(cwd):
        raise CheckpointError('cwd must be an existing directory')
    home = os.path.realpath(os.path.expanduser('~'))
    opened = []
    try:
        fd = os.open(home, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
        opened.append(fd)
        for part in ('.claude-swap-backup', 'checkpoints', hashlib.sha256(cwd.encode()).hexdigest()):
            fd = _directory(fd, part, create)
            opened.append(fd)
            if create and part != '.claude-swap-backup':
                os.fchmod(fd, 0o700)
        return cwd, opened
    except BaseException:
        for item in reversed(opened):
            os.close(item)
        raise


def _close(fds):
    for fd in reversed(fds):
        os.close(fd)


def _read_entry(fd, name):
    file_fd = os.open(name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, dir_fd=fd)
    try:
        info = os.fstat(file_fd)
        if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_BYTES:
            raise CheckpointError('checkpoint is not a bounded regular file')
        data = b''
        while len(data) <= MAX_BYTES:
            chunk = os.read(file_fd, min(65536, MAX_BYTES + 1 - len(data)))
            if not chunk:
                break
            data += chunk
        if len(data) > MAX_BYTES:
            raise CheckpointError('checkpoint exceeds size limit')
        return data.decode('utf-8')
    finally:
        os.close(file_fd)


def save(cwd, session, stream):
    if not SESSION_RE.fullmatch(session):
        raise CheckpointError('session must be 1–128 letters, digits, underscores or hyphens')
    raw = stream.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise CheckpointError('input exceeds 32 KiB')
    try:
        data = json.loads(raw)
    except (ValueError, UnicodeError, RecursionError):
        raise CheckpointError('input must be a JSON object') from None
    if not isinstance(data, dict) or set(data) != set(SECTIONS):
        raise CheckpointError('input must contain exactly the seven checkpoint sections')
    for name in SECTIONS:
        value = data[name]
        if not isinstance(value, str) or not value.strip() or any(ord(c) < 32 and c not in '\n\t\r' for c in value):
            raise CheckpointError('every section must contain explicit text')
        if name in ('Goal', 'Current state', 'Next steps'):
            meaningful = re.sub(r'(?im)<!--.*?-->|\b(?:todo|tbd|none|n/?a|placeholder)\b|[\s\W_]+', '', value)
            if not meaningful:
                raise CheckpointError(name + ' requires meaningful content')
    cwd, fds = _scope(cwd, True)
    fd = fds[-1]
    tmp = None
    try:
        created = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime())
        ident = created + '-' + uuid.uuid4().hex
        # Metadata is machine-readable without parsing arbitrary section content.
        header = json.dumps({'id': ident, 'session': session, 'session_known': session != 'unknown', 'cwd': cwd}, ensure_ascii=True, separators=(',', ':'))
        text = '# Checkpoint\n\n<!-- overclaude-checkpoint ' + header + ' -->\n'
        text += ''.join('\n## ' + name + '\n\n' + data[name].strip() + '\n' for name in SECTIONS)
        content = text.encode('utf-8')
        if len(content) > MAX_BYTES:
            raise CheckpointError('rendered checkpoint exceeds 32 KiB')
        tmp = '.tmp-' + uuid.uuid4().hex
        out = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=fd)
        try:
            with os.fdopen(out, 'wb', closefd=False) as writer:
                writer.write(content)
                writer.flush()
            os.fchmod(out, 0o400)
            os.fsync(out)
        finally:
            os.close(out)
        # link is an atomic, exclusive publish: an existing snapshot cannot be replaced.
        os.link(tmp, ident + '.md', src_dir_fd=fd, dst_dir_fd=fd, follow_symlinks=False)
        os.fsync(fd)
        return {'id': ident, 'cwd': cwd, 'session': session, 'session_known': session != 'unknown'}
    finally:
        if tmp is not None:
            try:
                os.unlink(tmp, dir_fd=fd)
            except FileNotFoundError:
                pass
        _close(fds)


def entries(cwd):
    try:
        canonical, fds = _scope(cwd, False)
    except FileNotFoundError:
        return []
    try:
        result = []
        for name in sorted(os.listdir(fds[-1]), reverse=True):
            ident = name[:-3] if name.endswith('.md') else ''
            if not ID_RE.fullmatch(ident):
                continue
            try:
                text = _read_entry(fds[-1], name)
                line = text.splitlines()[2]
                if not line.startswith('<!-- overclaude-checkpoint ') or not line.endswith(' -->'):
                    continue
                meta = json.loads(line[len('<!-- overclaude-checkpoint '):-4])
                if meta.get('id') == ident and meta.get('cwd') == canonical and SESSION_RE.fullmatch(meta.get('session', '')):
                    result.append(meta)
            except (OSError, ValueError, UnicodeError, IndexError, AttributeError, TypeError, RecursionError, CheckpointError):
                continue
        return result
    finally:
        _close(fds)


def show(cwd, ident):
    if not ID_RE.fullmatch(ident):
        raise CheckpointError('invalid checkpoint id')
    canonical, fds = _scope(cwd, False)
    try:
        text = _read_entry(fds[-1], ident + '.md')
        line = text.splitlines()[2]
        if not line.startswith('<!-- overclaude-checkpoint ') or not line.endswith(' -->'):
            raise CheckpointError('invalid checkpoint metadata')
        meta = json.loads(line[len('<!-- overclaude-checkpoint '):-4])
        if not isinstance(meta, dict) or meta.get('id') != ident or meta.get('cwd') != canonical or not SESSION_RE.fullmatch(meta.get('session', '')):
            raise CheckpointError('checkpoint does not belong to this cwd')
        return text
    finally:
        _close(fds)


def main():
    ap = argparse.ArgumentParser(allow_abbrev=False)
    subs = ap.add_subparsers(dest='action', required=True)
    save_parser = subs.add_parser('save', allow_abbrev=False)
    save_parser.add_argument('--session', required=True)
    save_parser.add_argument('--cwd', default=os.getcwd())
    list_parser = subs.add_parser('list', allow_abbrev=False)
    list_parser.add_argument('--cwd', default=os.getcwd())
    show_parser = subs.add_parser('show', allow_abbrev=False)
    show_parser.add_argument('id')
    show_parser.add_argument('--cwd', default=os.getcwd())
    args = ap.parse_args()
    try:
        if args.action == 'save':
            print(json.dumps(save(args.cwd, args.session, sys.stdin.buffer), ensure_ascii=True))
        elif args.action == 'list':
            print(json.dumps(entries(args.cwd), ensure_ascii=True))
        else:
            sys.stdout.write(show(args.cwd, args.id))
    except (CheckpointError, OSError, ValueError, UnicodeError, IndexError, AttributeError, TypeError, RecursionError) as exc:
        message = str(exc) if isinstance(exc, CheckpointError) else 'cannot access checkpoint storage'
        print('overclaude-checkpoint: ' + message, file=sys.stderr)
        return 1
    return 0


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