"""V7 private integration primitives. Import is inert; no source acquisition."""
import ctypes, hashlib, importlib.util, json, os, shutil, sqlite3, sys, time
from pathlib import Path
from datetime import datetime, timezone
HERE=Path(__file__).resolve().parent
ROOT=HERE.parents[2]
PREP=HERE.parent/'public-expansion-v7-preparation-01'
sys.path.insert(0,str(PREP));sys.path.insert(0,str(ROOT/'scripts_build'))
GIB=1024**3
def need(ok,message):
 if not ok:raise RuntimeError(message)
def now():return datetime.now(timezone.utc).isoformat()
def encoded(v):return (json.dumps(v,ensure_ascii=False,sort_keys=True,separators=(',',':'))+'\n').encode('utf-8')
def read(p):return json.loads(Path(p).read_text('utf-8'))
def sha(p,gate=lambda:None):
 h=hashlib.sha256();p=Path(p);a=p.stat()
 with p.open('rb') as f:
  for b in iter(lambda:f.read(1<<20),b''):gate();h.update(b)
 b=p.stat();need((a.st_size,a.st_ino,a.st_mtime_ns)==(b.st_size,b.st_ino,b.st_mtime_ns),'Immutable input changed while hashing')
 return h.hexdigest()
def pin(p,gate=lambda:None):return {'path':str(Path(p).resolve()),'bytes':Path(p).stat().st_size,'sha256':sha(p,gate)}
def checked(meta,gate=lambda:None):
 p=Path(meta['path']);need(p.is_file() and not p.is_symlink() and p.stat().st_size==meta['bytes'] and sha(p,gate)==meta['sha256'],'Pinned input differs: '+str(p));return p
def save(p,v):
 p=Path(p);p.parent.mkdir(parents=True,exist_ok=True)
 with p.open('xb') as f:f.write(encoded(v))
def db_ro(p):
 db=sqlite3.connect(Path(p).resolve().as_uri()+'?mode=ro',uri=True)
 db.executescript('PRAGMA query_only=ON;PRAGMA cache_size=-16384;PRAGMA mmap_size=0;')
 return db
def module(p,name):
 spec=importlib.util.spec_from_file_location(name,p);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
def rows(p):
 import gzip
 with gzip.open(p,'rb') as f:
  while True:
   line=f.readline((8<<20)+1)
   if not line:break
   need(len(line)<=8<<20 and line.endswith(b'\n'),'Closed packet row framing exceeds8MiB')
   yield json.loads(line)
def inventory(base,gate=lambda:None):
 result={}
 for p in Path(base).rglob('*'):
  if '.wrangler' in p.relative_to(base).parts:continue
  need(not p.is_symlink(),'Symlink in source inventory')
  if p.is_file():gate();result[p.relative_to(base).as_posix()]=pin(p,gate)
 return result
def is_static(name):return not name.startswith('functions/')
def memory():
 class M(ctypes.Structure):_fields_=[('length',ctypes.c_ulong),('load',ctypes.c_ulong)]+[(n,ctypes.c_ulonglong) for n in ('total','available','page_total','page_free','virtual_total','virtual_free','extended')]
 v=M();v.length=ctypes.sizeof(v);need(ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(v)),'RAM observation failed');return v.available
class Gate:
 def __init__(self,work,deadline,maximum_bytes=24*GIB):self.work=Path(work);self.deadline=deadline;self.maximum=maximum_bytes;self.last=0;self.minimum_ram=memory();self.maximum_seen=0;self.minimum_free_disk=shutil.disk_usage(self.work if self.work.exists() else self.work.parent).free
 def __call__(self,force=False):
  if not force and time.monotonic()-self.last<2:return
  self.last=time.monotonic();need(time.time()<self.deadline,'Original4h processing deadline reached')
  ram=memory();self.minimum_ram=min(self.minimum_ram,ram);need(ram>=4*GIB,'Emergency4GiB RAM floor')
  free=shutil.disk_usage(self.work if self.work.exists() else self.work.parent).free;self.minimum_free_disk=min(self.minimum_free_disk,free)
  need(free>=8*GIB,'Actual runtime8GiB free-disk floor')
  size=0
  if self.work.exists():
   for p in self.work.rglob('*'):
    try:
     if p.is_file():size+=p.stat().st_size
    except FileNotFoundError:
     # The exact owned C-sort subtree contains SQLite's ephemeral files.
     # No vanished payload/source/candidate path is silently ignored.
     sort_root=(self.work/'temp/sqlite-sort').resolve()
     need(p.name.endswith(('-journal','-wal','-shm')) or p.resolve(strict=False).is_relative_to(sort_root),'Unexpected vanished owned file')
  self.maximum_seen=max(self.maximum_seen,size);need(size<=self.maximum,'Private workspace24GiB bound')
def frozen_config(path):
 cfg=read(path);release=read(HERE/'ROOT_RELEASE.json');freeze=read(HERE/'CODE_FREEZE.json')
 need(cfg['schema']=='ndr-public-v7-private-inputs/1' and release['root_reviewed'] is True,'Actual root-reviewed source cutoff is required')
 need(cfg.get('scb') is not None and cfg.get('source_cutoff')==['bibliographic:gnd2026-retained03','official:se_scb_registered_names_20221231'],
      'Current intended V7 includes both closed GND03 and SCB01 exactly once')
 need(release['config_sha256']==sha(path) and release['code_freeze_sha256']==sha(HERE/'CODE_FREEZE.json'),'Named root release/config mismatch')
 for p in freeze['files']+freeze['dependencies']:checked(p)
 need(cfg['baseline']['production']=='e6da5d99-2e51-4f36-88a3-2860a2c2fa92' and cfg['baseline']['release']=='d966e8e1701b8287d30bcbd0','Published packed V6 baseline differs')
 need(cfg['baseline']['keys']==1966327 and cfg['baseline']['static_files']==19561,'Actual packed baseline geometry differs')
 need(cfg['compatibility_date']=='2026-06-29' and release['maximum_processing_seconds']==14400,'Production compatibility/deadline differs')
 work=Path(release['workspace']).resolve();allowed=Path(os.environ['LOCALAPPDATA'])/'NamesDoneRight'
 need(work.is_relative_to(allowed.resolve()) and work!=allowed.resolve(),'Workspace outside named private root')
 return cfg,release,work
