#!/usr/bin/env python3
"""Read-only intake for the QR improvement plan; never downloads, builds or edits."""
import argparse
import hashlib
import json
import shutil
from pathlib import Path
import re
import subprocess
import sys

BASELINE = '2f759f9415b46a7166215fa670d5b4fafeef615e'
SDK_SHA = 'adabb1f0f4750081abe131a3baa6f76057ff931e05d7264c56bf6fba5d99aeec'
REPOSITORY_PATH = '60069db88deaa14d9e02b875/zhct/device/restaurant/billedBygram/ZhctWeightingTableYoukate'


def run(argv, cwd=None):
    p = subprocess.run(argv, cwd=cwd, capture_output=True, text=True, timeout=15)
    return p.returncode, p.stdout.strip(), p.stderr.strip()


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--repo', required=True)
    p.add_argument('--mode', choices=['baseline', 'resume'], default='baseline')
    p.add_argument('--require-container-images', action='store_true')
    args = p.parse_args()
    entered = Path(args.repo).expanduser().absolute()
    checks = []

    def check(name, passed, detail):
        checks.append({'check': name, 'passed': bool(passed), 'detail': detail})

    check('real_directory', entered.is_dir() and not any(x.is_symlink() for x in [entered, *entered.parents]),
          'Input and parent directories must not be symlinks')
    if not checks[-1]['passed']:
        print(json.dumps({'checks': checks}, ensure_ascii=False, indent=2)); return 2
    repo = entered.resolve()
    rc, top, _ = run(['git', 'rev-parse', '--show-toplevel'], repo)
    check('repository_root', rc == 0 and Path(top).resolve() == repo, 'Exact repository root required')
    if not checks[-1]['passed']:
        print(json.dumps({'checks': checks}, ensure_ascii=False, indent=2)); return 2
    _, origin, _ = run(['git', 'remote', 'get-url', 'origin'], repo)
    normalized = re.sub(r'\.git$', '', origin)
    approved_origins = ['https://codeup.aliyun.com/' + REPOSITORY_PATH,
                        'git@codeup.aliyun.com:' + REPOSITORY_PATH]
    check('origin_identity', normalized in approved_origins, 'Codeup repository identity checked; URL not echoed')
    _, head, _ = run(['git', 'rev-parse', 'HEAD'], repo)
    _, branch, _ = run(['git', 'branch', '--show-current'], repo)
    _, status, _ = run(['git', 'status', '--porcelain'], repo)
    rc, _, _ = run(['git', 'merge-base', '--is-ancestor', BASELINE, 'HEAD'], repo)
    check('baseline_ancestry', rc == 0, BASELINE)
    if args.mode == 'baseline':
        check('frozen_head', head == BASELINE, head)
        check('clean_baseline', not status, 'Dirty tree is preserved; no cleanup is attempted')
    else:
        check('task_branch', branch.startswith('codex/'), branch)
    sdk = repo / 'app/libs/DeviceSDK-80.1.10.12.20260129.aar'
    sdk_hash = hashlib.sha256(sdk.read_bytes()).hexdigest() if sdk.is_file() else None
    check('sdk_identity', sdk_hash == SDK_SHA, sdk_hash)
    evidence = Path(__file__).resolve().parents[2] / 'app-verification/verification-result.json'
    reference = json.loads(evidence.read_text())
    source_hashes = {}
    for rel, expected in reference['source_sha256'].items():
        path = repo / rel
        actual = hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
        source_hashes[rel] = actual
        if args.mode == 'baseline':
            check('source:' + rel, actual == expected, actual)
    docker = shutil.which('docker')
    daemon = False
    docker_version = None
    images = {}
    if docker:
        rc, docker_version, _ = run([docker, 'version', '--format', '{{.Client.Version}}'])
        try:
            rc, daemon_platform, _ = run([docker, 'info', '--format', '{{.OSType}}/{{.Architecture}}'])
            daemon = rc == 0
        except subprocess.TimeoutExpired:
            daemon_platform = 'TIMEOUT'
        if daemon:
            for label in ['zhct-qr-jdk8:20260909', 'zhct-qr-jdk17:20260909']:
                rc, image_id, _ = run([docker, 'image', 'inspect', '--format', '{{.Id}}', label])
                images[label] = image_id if rc == 0 else None
    inventory = {'docker_client': docker, 'docker_client_version': docker_version,
                 'docker_daemon_available': daemon, 'required_images': images,
                 'host_jdk_used': False, 'host_android_sdk_used': False,
                 'container_platform': 'linux/amd64'}
    build_ready = daemon and len(images) == 2 and all(images.values())
    if args.require_container_images:
        check('container_images_ready', build_ready,
              'Docker images required; this is not proof of a Gradle build')
    result = {'mode': args.mode, 'repository': str(repo), 'head': head, 'branch': branch,
              'working_tree_clean': not status, 'checks': checks, 'source_sha256': source_hashes,
              'static_precheck': 'PASS' if all(x['passed'] for x in checks) else 'FAIL',
              'build_environment': 'IMAGES_PRESENT_NOT_BUILD_PROVEN' if build_ready else ('IMAGES_NOT_PREPARED' if daemon else 'DOCKER_DAEMON_UNAVAILABLE'),
              'inventory': inventory,
              'boundary': 'No host Java/JDK/Android SDK used; no downloads, Gradle, device, production, file writes or repository mutation performed. Resume mode reports current hashes and does not certify changed implementation.'}
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if all(x['passed'] for x in checks) else 2


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