from __future__ import annotations
import collections, hashlib, json, os, sqlite3
from pathlib import Path
from jarvis_finance.services.household_import import preview_household_import
DB=Path('/home/agent/jarvis_runtime/finance-system/data/finance.sqlite3')
ROOT=Path('/home/agent/jarvis_runtime/finance-system/sprint16.1-uat')
PAYLOAD=ROOT/'real-preview-payload-private.json'; RESPONSE=ROOT/'pre16.1-real-preview-private.json'; EVIDENCE=ROOT/'pre16.1-preview-summary-private.json'
def digest_db():
 c=sqlite3.connect(f'file:{DB}?mode=ro',uri=True); h=hashlib.sha256()
 for t, in c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"):
  h.update(t.encode())
  for r in c.execute(f'SELECT * FROM "{t}" ORDER BY rowid'): h.update(json.dumps(list(r),default=str,ensure_ascii=False,separators=(',',':')).encode())
 fk=len(c.execute('PRAGMA foreign_key_check').fetchall()); integrity=c.execute('PRAGMA integrity_check').fetchone()[0]; c.close(); return h.hexdigest(),fk,integrity
before=digest_db(); c=sqlite3.connect(f'file:{DB}?mode=ro',uri=True); c.row_factory=sqlite3.Row; c.execute('PRAGMA foreign_keys=ON')
payload=json.loads(PAYLOAD.read_text()); result=preview_household_import(c,payload); c.close(); after=digest_db()
fd=os.open(RESPONSE,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
with os.fdopen(fd,'w') as f:json.dump(result,f,ensure_ascii=False,indent=2)
rows=result.get('rows',[]); unresolved=[r for r in rows if r.get('user_state')=='decision_needed' and r.get('disposition') not in ('duplicate_file','duplicate_source_row','pending','superseded_pending')]
proposals=collections.Counter(str(r.get('proposed_category_name') or 'unbenannt') for r in rows if r.get('user_state')=='proposal_ready')
summary={'code_commit':'a5e8dd0e5b1330b588e5c6e501cd2af03f23818f','counts':result.get('counts'),'review_threshold':result.get('review_threshold'),'readiness_checks':result.get('readiness_checks'),'technically_confirmable':result.get('technically_confirmable',result.get('confirmable')),'business_ready_for_confirm':result.get('business_ready_for_confirm'),'errors':result.get('errors'),'individual_review_count':len(unresolved),'merchant_cluster_count':len(result.get('merchant_clusters',[])),'proposal_categories':dict(proposals),'db_unchanged':before[0]==after[0],'fk_before_after':[before[1],after[1]],'integrity_before_after':[before[2],after[2]],'confirm_called':False}
fd=os.open(EVIDENCE,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
with os.fdopen(fd,'w') as f:json.dump(summary,f,ensure_ascii=False,indent=2)
print(json.dumps(summary|{'private_response':str(RESPONSE),'private_evidence':str(EVIDENCE),'modes':[oct(RESPONSE.stat().st_mode&0o777),oct(EVIDENCE.stat().st_mode&0o777)]},ensure_ascii=False,indent=2))
