#!/usr/bin/env python3
"""Validate a staged or committed package using only its Git tree contents."""

import json
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
tree = sys.argv[1] if len(sys.argv) > 1 else subprocess.check_output(['git', 'write-tree'], cwd=ROOT, text=True).strip()
paths = [
    'modules/product/products/food-safety/knowledge',
    'standards-stack/agent-skills/skills/food-safety-product-design',
    'standards-stack/agent-skills/skills/product-capability-map-synthesis',
    'standards-stack/agent-skills/skills/prd-requirements-analysis',
    'standards-stack/agent-skills/skills/system-grounded-requirement-analysis',
    'work_food_safety/README.md',
    'work/2026-10-23-foodsafe-operations/summary.md',
    'work_food_safety/2026-09-24-mysql8-dm8-dual-compatibility/knowledge-base/README.md',
    'work_food_safety/knowledge-sharing-2026-10-26/validate-package.py',
]
archive = subprocess.check_output(['git', 'archive', tree, '--', *paths], cwd=ROOT)
with tempfile.TemporaryDirectory(prefix='food-safety-portable-') as temporary:
    subprocess.run(['tar', '-xf', '-', '-C', temporary], input=archive, check=True)
    validator = Path(temporary) / paths[-1]
    result = subprocess.run([sys.executable, str(validator)], capture_output=True, text=True)
    validation = json.loads(result.stdout)
    report = {'git_tree': tree, 'method': 'git archive selected tracked paths to temporary directory',
              'uses_original_workspace': False, 'uses_wedrive': False, 'uses_private_config': False,
              'validation': validation, 'passed': result.returncode == 0 and validation['passed']}
    Path(__file__).with_name('portable-check.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps(report, ensure_ascii=False, indent=2))
    sys.exit(0 if report['passed'] else 1)
