"""Apply the native companion to a verified extracted baseline kit; never build."""
import argparse, hashlib, json, shutil, stat
from pathlib import Path

def digest(p):
    return hashlib.sha256(p.read_bytes()).hexdigest()

def check(ok, message):
    if not ok: raise RuntimeError(message)

p = argparse.ArgumentParser(description=__doc__)
p.add_argument('baseline', type=Path)
p.add_argument('--output-kit', type=Path, required=True)
a = p.parse_args()
companion = Path(__file__).resolve().parent
baseline, output = a.baseline.resolve(), a.output_kit.resolve()
identity = json.loads((companion / 'manifest.json').read_text())
for name, expected in identity['files'].items():
    check(digest(companion / name) == expected, 'Companion changed: ' + name)
check(digest(baseline / 'recipe.json') == identity['baselineRecipeSha256'], 'Wrong baseline recipe')
old = json.loads((baseline / 'recipe.json').read_text())
actual = set()
for f in baseline.rglob('*'):
    check(not f.is_symlink() and not getattr(f.lstat(), 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT, 'Linked baseline entry')
    if f.is_file(): actual.add(f.relative_to(baseline).as_posix())
check(actual == set(old['files']) | {'recipe.json'}, 'Baseline membership changed')
for name, expected in old['files'].items():
    check(digest(baseline / name) == expected, 'Baseline changed: ' + name)
check(not output.exists() and not output.is_relative_to(baseline) and not baseline.is_relative_to(output), 'Output must be a new directory outside baseline')
check(not output.is_relative_to(companion) and not companion.is_relative_to(output), 'Output must be outside companion')
shutil.copytree(baseline, output)
for name in ('README.md', 'host/sfc-host.cpp', 'provenance/native-build.py', 'provenance/native-build-inputs.json', 'recipe.json'):
    dest = output / name
    dest.parent.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(companion / name, dest)
recipe = json.loads((output / 'recipe.json').read_text())
check({f.relative_to(output).as_posix() for f in output.rglob('*') if f.is_file()} == set(recipe['files']) | {'recipe.json'}, 'Native membership mismatch')
for name, expected in recipe['files'].items():
    check(digest(output / name) == expected, 'Native source mismatch: ' + name)
print('Native kit verified. Run its original rebuild_source_kit.py with the pinned SDK and a new output directory.')
