from pathlib import Path
import json,re,shutil
r=Path(__file__).resolve().parents[1]
path=r/'docs/platform/schema-inventory.json'
source=r/'docs/platform/received-schema-inventory.json'
if not source.exists():shutil.copy2(path,source)
inventory=json.loads(source.read_text(encoding='utf-8'))
historical=[t for t in inventory['tables'] if t.startswith(('aw260923_','vld_backup_'))]
p=r/'app/Platform/Backup/BackupPolicy.php';s=p.read_text(encoding='utf-8')
s=re.sub(r'public const HISTORICAL_TABLES = \[.*?\];',"public const HISTORICAL_TABLES = [\n"+''.join("        '"+t+"',\n" for t in historical)+"    ];",s,flags=re.S)
a=s.index("        $policy['tables']['subscriptions']");b=s.index("        $policy['file_rules']",a)
s=s[:a]+s[b:]
s=s.replace("'logo'=>'business_logos','online_order_hero_image'=>'online_order_hero_images'", "'logo'=>'business_logos'").replace("'menu_items'=>['image'=>'img'], ", '').replace("'logo'=>'invoice_logos','letter_head'=>'invoice_logos'", "'logo'=>'invoice_logos'")
# These retired modules cannot silently omit attachment content from a company archive.
s=s.replace("            'collection_settlements'", "            'legacy_migration_runs'=>['package_path'=>false,'report_path'=>false],\n            'collection_settlements'")
p.write_text(s,encoding='utf-8')
p=r/'app/Platform/Backup/TenantSelection.php';s=p.read_text(encoding='utf-8')
s=s.replace("'migrations', 'sessions'", "'jobs','failed_jobs','cms_pages','cms_page_metas','cms_site_details','migrations', 'sessions'")
extra={
 'essentials_document_shares':['document_id','essentials_documents'],
 'essentials_kb_users':['user_id','users'],
 'essentials_payroll_group_transactions':['transaction_id','transactions'],
 'essentials_todos_users':['user_id','users'],
 'essentials_todo_comments':['task_id','essentials_todos'],
 'essentials_user_allowance_and_deductions':['user_id','users'],
 'essentials_user_sales_targets':['user_id','users'],
 'essentials_user_shifts':['user_id','users'],
 'payment_processor_contract_payment_methods':['contract_id','payment_processor_contracts'],
 'payment_processor_fee_rules':['contract_id','payment_processor_contracts'],
 'payment_processor_fee_tiers':['fee_rule_id','payment_processor_fee_rules'],
 'product_supplier':['product_id','products'],
 'receipt_template_versions':['receipt_template_id','receipt_templates'],
 'sell_line_warranties':['sell_line_id','transaction_sell_lines'],
 'transaction_exchange_lines':['exchange_id','transaction_exchanges'],
}
s=s.replace('        $children = [','        $children = [\n'+''.join("            '%s'=>['%s','%s'],\n"%(t,*values) for t,values in extra.items()))
s=s.replace("['currencies','kuwait_areas']", "['currencies','online_order_kw_areas','online_order_kw_cities']")
s=s.replace("/^(migration_backup_|manual_fix_|kw_rashid_)/", "/^(aw260923_|vld_backup_)/")
p.write_text(s,encoding='utf-8')
print('Reviewed historical archives:',len(historical),'Retail child ownership rules:',len(extra))
