#!/usr/bin/env python3
"""Execute doyle OK6EONQN: only the classified old target subtree."""
import datetime
import hashlib
import json
import os
from pathlib import Path
import runpy
import shutil
import stat
import subprocess

PROOF = Path(__file__).resolve().parent
ROOT = Path('/home/reavus/projects/spt-core/spt-core')
TARGET = ROOT / '.worktrees/consumer-linux-304-b8482445/target'
S3 = ROOT / '.worktrees/consumer-linux-49a08a07'
assert not (PROOF / 'old-target-reclaim.json').exists()
previous = json.loads((PROOF / 'old-target-classification.json').read_text())
(PROOF / 'old-target-classification-initial.json').write_bytes((PROOF / 'old-target-classification.json').read_bytes())
runpy.run_path(str(PROOF / 'classify-old-target.py'))
fresh = json.loads((PROOF / 'old-target-classification.json').read_text())
assert fresh['proof_sha256'] == previous['proof_sha256']
assert fresh['inode'] == previous['inode'] and fresh['device'] == previous['device']
assert not fresh['active_producers'] and not fresh['target_process_references']
assert not fresh['inbound'] and not fresh['walk_errors']
assert json.loads((TARGET / 'POOL-OWNER.json').read_text()) == fresh['owner']
helper = json.loads((PROOF / 'preserved-helper.json').read_text())
assert hashlib.sha256(Path(helper['preserved']).read_bytes()).hexdigest() == helper['sha256']
assert Path(helper['preserved']).resolve().is_relative_to(PROOF)
assert TARGET.name == 'target' and not TARGET.is_symlink() and TARGET.resolve() == TARGET
assert stat.S_ISDIR(TARGET.lstat().st_mode)
source_stat = TARGET.parent.stat()
s3_tree_stat = S3.stat()
s3_target_stat = (S3 / 'target').stat()
s3_owner = (S3 / 'target/POOL-OWNER.json').read_bytes()
report = {'authority': 'OK6EONQN', 'target': str(TARGET),
          'start_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
          'allocated_bytes_before': fresh['allocated_bytes'], 'free_bytes_before': shutil.disk_usage(ROOT).free,
          'classification_sha256': hashlib.sha256((PROOF / 'old-target-classification.json').read_bytes()).hexdigest(),
          'helper_sha256': helper['sha256'], 'action': 'shutil.rmtree on exact real target directory'}
(PROOF / 'old-target-reclaim-before.json').write_text(json.dumps(report, indent=2) + '\n')
shutil.rmtree(TARGET)
os.sync()
assert not TARGET.exists()
assert TARGET.parent.stat().st_ino == source_stat.st_ino
assert S3.stat().st_ino == s3_tree_stat.st_ino
assert (S3 / 'target').stat().st_ino == s3_target_stat.st_ino
assert (S3 / 'target/POOL-OWNER.json').read_bytes() == s3_owner
report.update(end_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),
              free_bytes_after=shutil.disk_usage(ROOT).free, target_exists=False,
              old_source_retained=True, s3_tree_and_target_retained=True)
report['free_bytes_delta'] = report['free_bytes_after'] - report['free_bytes_before']
(PROOF / 'old-target-reclaim.json').write_text(json.dumps(report, indent=2) + '\n')
print('RECLAIM_DONE ' + json.dumps(report), flush=True)
