import ast
import base64
import hashlib
import io
import json
from pathlib import Path
import re
import shutil
import subprocess
import tarfile
from urllib.parse import unquote,urlsplit
from remote import ROOT,REMOTE,python,run

repo=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
paths=[
 'tools/icerti_offline/fight_r5_install.py','tools/icerti_offline/fight_r5_package.py',
 'tools/icerti_offline/fight_r5_settings.py','tests/test_fight_r5_site.py',
 'docs/deployment/SCENARIO_DEMO_COMPATIBILITY.ko.md','docs/integration/FIGHT_R5_WEB_CONFIG.ko.md',
 'docs/profiles/ltb1021/topics/runtime-lifecycle/README.ko.md',
 'docs/profiles/ltb1021/topics/runtime-lifecycle/decision/20261101T094844+0900-decision-r5-site-default-and-demo-deployment.md',
 'docs/profiles/ltb1021/topics/runtime-lifecycle/analysis/20261101T101310+0900-analysis-icerti-six-channel-errors.md',
 'docs/profiles/ltb1021/topics/runtime-lifecycle/run/20261101T102749+0900-run-icerti-r5-deployment.md']
for folder in (ROOT/'receipts',ROOT/'error-evidence/shared'):
 for line in (folder/'SHA256SUMS').read_text().splitlines():
  value,name=line.split('  ',1)
  assert hashlib.sha256((folder/name).read_bytes()).hexdigest()==value,name
tests=json.loads((ROOT/'receipts/isolated-tests.json').read_text())
assert tests['exit_code']==0 and tests['collected']==73 and not tests['failed'] and not tests['errors']
manifest=json.loads((ROOT/'receipts/manifest.json').read_text())
for name,digest in manifest['after'].items():
 assert hashlib.sha256((ROOT/'package/payload'/name).read_bytes()).hexdigest()==digest,name
 if name.startswith('app/fight_r5/'):
  raw=subprocess.check_output(['git','show',manifest['source_commit']+':'+name],cwd=repo)
  assert hashlib.sha256(raw).hexdigest()==digest,name
checked=[];hashes={}
for name in paths:
 path=repo/name;raw=path.read_bytes();hashes[name]=hashlib.sha256(raw).hexdigest()
 if name.endswith('.py'):ast.parse(raw)
 if name.endswith('.md'):
  tracked=subprocess.run(['git','ls-files','--error-unmatch',name],cwd=repo,capture_output=True).returncode==0
  if tracked:
   diff=subprocess.check_output(['git','diff','-U0','--',name],cwd=repo,text=True)
   text='\n'.join(x[1:] for x in diff.splitlines() if x.startswith('+') and not x.startswith('+++'))
  else:text=raw.decode()
  for target in re.findall(r'\]\(([^)]+)\)',text):
   parsed=urlsplit(target)
   if not parsed.scheme and parsed.path:
    assert (path.parent/unquote(parsed.path)).resolve().exists(),(name,target)
    checked.append(dict(source=name,target=target))
 destination=ROOT/'completion-source'/name;destination.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,destination)
subprocess.run(['git','diff','--check'],cwd=repo,check=True)
result=dict(status='AI_DEPLOYMENT_VERIFIED_WEB_VIDEO_ISSUE_DEFERRED',files=hashes,document_links=len(checked),
 tests=73,subtests=27,payload_files=15,frozen_r5_modules=11,receipt_sha256_files=12,shared_evidence_sha256_files=13,
 source_only_deployment=True,web_display='User reported problem; investigation explicitly deferred',
 actual_event_media_acceptance='NOT_VERIFIED',automatic_rollback=False,git_mutation=False)
(ROOT/'completion.json').write_text(json.dumps(result,indent=2)+'\n')
copies={'completion.json':base64.b64encode((ROOT/'completion.json').read_bytes()).decode(),
        'checkpoint.ko.md':base64.b64encode((ROOT/'checkpoint.ko.md').read_bytes()).decode()}
for name in paths:
 if name.endswith('.md'):copies['completion-docs/'+Path(name).name]=base64.b64encode((repo/name).read_bytes()).decode()
archive=ROOT/'completion_bundle.tar'
with tarfile.open(archive,'w') as bundle:
 for name,encoded in copies.items():
  raw=base64.b64decode(encoded);item=tarfile.TarInfo(name);item.size=len(raw);item.mode=0o600
  bundle.addfile(item,io.BytesIO(raw))
raw=archive.read_bytes();digest=hashlib.sha256(raw).hexdigest()
incoming='/home/si/fight-r5-completion-r01.tar'
run(['python3','-c','import sys\nfrom pathlib import Path\np=Path('+repr(incoming)+')\nassert not p.exists()\np.write_bytes(sys.stdin.buffer.read());p.chmod(0o600)'],payload=raw)
code='import hashlib,io,tarfile\nfrom pathlib import Path\nroot=Path('+repr(REMOTE)+')\nraw=Path('+repr(incoming)+').read_bytes()\nassert hashlib.sha256(raw).hexdigest()=='+repr(digest)+'''\nwith tarfile.open(fileobj=io.BytesIO(raw)) as bundle:
 for item in bundle.getmembers():assert not (root/item.name).exists()
 bundle.extractall(root,filter='data')
print('Completion evidence stored; no Runtime query or mutation.')
'''
print(python(code,sudo=True).decode().strip())
print(json.dumps(dict(status=result['status'],files=len(paths),links=len(checked),tests=73,subtests=27)))
