#!/usr/bin/env python3
"""Shellfirm 0.4.1: command-string checks only; no candidate command execution.
Usage: python3 shellfirm-check-lab.py /path/to/shellfirm
Requires Python 3, Git, and a verified Shellfirm 0.4.1 executable.
"""
import json
from pathlib import Path
import subprocess
import sys
import tempfile


def main():
    if len(sys.argv) != 2:
        print(__doc__, file=sys.stderr)
        return 2
    binary = Path(sys.argv[1]).expanduser().resolve()
    if not binary.is_file():
        print('Shellfirm executable not found.', file=sys.stderr)
        return 2
    version = subprocess.run([str(binary), '--version'], capture_output=True, text=True, check=True).stdout.strip()
    if version != 'shellfirm 0.4.1':
        print('Expected shellfirm 0.4.1; got: ' + version, file=sys.stderr)
        return 2
    cases = [('git status --short', 'allow', 0),
             ('git rebase -i HEAD~3', 'ask', 10),
             ('git push --force origin main', 'deny', 11)]
    failures = 0
    with tempfile.TemporaryDirectory(prefix='shellfirm-check-lab-') as temp:
        root = Path(temp).resolve()
        config = root / 'config'
        config.mkdir()
        # Initialise only the temporary repository; no commit or remote.
        subprocess.run(['git', 'init', '-q', str(root)], check=True)
        marker = root / 'node_modules' / 'marker.txt'
        marker.parent.mkdir()
        marker.write_text('This file must survive every check.\n')
        for command, expected, expected_exit in cases:
            result = subprocess.run(
                [str(binary), 'check', '--config-dir', str(config), '--no-context',
                 '-c', command, '--format', 'json', '--exit-code'],
                cwd=root, capture_output=True, text=True, timeout=30)
            try:
                report = json.loads(result.stdout)
            except json.JSONDecodeError:
                print('Invalid JSON:', result.stderr, file=sys.stderr)
                return 1
            ok = report.get('decision') == expected and result.returncode == expected_exit
            failures += not ok
            print(json.dumps({'command': command, 'decision': report.get('decision'),
                              'exit': result.returncode, 'expected': expected,
                              'pass': ok, 'reason': report.get('decision_reason')}, ensure_ascii=False))
            if result.stderr:
                print(result.stderr, file=sys.stderr)
        if not marker.is_file() or marker.read_text() != 'This file must survive every check.\n':
            print('Marker check failed.', file=sys.stderr)
            return 1
    print('All candidate commands were checked as strings, never executed.')
    return 1 if failures else 0


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