import sqlite3,hashlib,json,sys
def audit(x):
c=sqlite3.connect('file:'+x+'?mode=ro&immutable=1',uri=True); c.row_factory=sqlite3.Row
v=c.execute('pragma foreign_key_check').fetchall(); fp=hashlib.sha256(json.dumps([(r[0],r[1],r[2],r[3]) for r in v],sort_keys=True).encode()).hexdigest()
out={'integrity':c.execute('pragma integrity_check').fetchone()[0],'fk':len(v),'fp':fp,'ku':c.execute('select count(*) from knowledge_units').fetchone()[0],'tables':{}}
cols={r[1] for r in c.execute('pragma table_info(knowledge_units)')}
if 'legacy_placeholder' in cols:
out.update({'legacy':c.execute('select count(*) from knowledge_units where legacy_placeholder=1').fetchone()[0],'legacy_rejected':c.execute("select count(*) from knowledge_units where review_state=? and gold_state=?",('REJECTED','NONE')).fetchone()[0],'gold':c.execute("select count(*) from knowledge_units where gold_state=?",('GOLD',)).fetchone()[0],'prov':c.execute('select count(*) from knowledge_unit_provenance').fetchone()[0],'review_audit':c.execute('select count(*) from knowledge_unit_review_audit').fetchone()[0],'placeholder_statements':c.execute('select count(*) from knowledge_units where statement like ?',('Knowledge unit from %',)).fetchone()[0]})
else: out['legacy']='not_in_pre_schema'
for t in [r[0] for r in c.execute("select name from sqlite_master where type='table' and name not like 'sqlite_%'")]: out['tables'][t]=c.execute('select count(*) from "'+t+'"').fetchone()[0]
c.close(); return out
p=sys.argv[1]; b=sys.argv[2]; prod=audit(p); bak=audit(b)
print(json.dumps({'prod':prod,'backup':bak,'existing_table_counts_same':{k:prod['tables'].get(k)==v for k,v in bak['tables'].items() if k not in ['knowledge_unit_provenance','knowledge_unit_review_audit','sqlite_sequence']}},ensure_ascii=False))