"""Render least-privilege grants for existing operator-created SQL accounts.

No passwords are accepted, generated, printed or stored by this tool.
"""
from __future__ import annotations
import argparse,re
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
IMMUTABLE={'usage_ledger','audit_events','plan_versions','provider_field_versions','invoice_lines','credit_entries'}
DELETABLE={'sessions','password_reset_tokens','cache','cache_locks','jobs','job_batches','failed_jobs','memberships','api_key_ip_rules','recovery_codes','auth_challenges','webauthn_credentials','team_invitations'}
PRESERVED={'accounts','users','api_keys','providers','agents','enrollment_tokens','routes','route_versions','route_exit_bindings','vpn_profiles','vpn_profile_versions','quota_groups','subscriptions','usage_periods','request_logs','upstream_attempts','request_admissions','quota_reservations','response_bodies','response_body_objects','cache_fills','cache_generations','invoices','payments','refunds','checkouts','outbox_events','encrypted_secrets','operational_alerts','account_closures','exports'}
def tables():
 names={'request_log_archives','upstream_attempt_archives'}
 for path in (ROOT/'apps/hub/database/migrations').glob('*.php'):names.update(re.findall(r"Schema::create\(['\"]([a-z_]+)['\"]",path.read_text()))
 return sorted(names|{'migrations'})
def validate(value,maximum=64):
 if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]{0,'+str(maximum-1)+'}',value):raise ValueError('Invalid SQL database/account identifier.')
 return value
def render(database,runtime,maintenance,host='localhost'):
 validate(database);validate(runtime,32);validate(maintenance,32)
 if runtime==maintenance or not re.fullmatch(r'[A-Za-z0-9_.:%/-]{1,255}',host):raise ValueError('Separate runtime/maintenance accounts and an explicit safe host are required.')
 lines=['-- Existing accounts only. Provision passwords outside this artifact.','-- Apply using the separate schema owner after migrations.']
 for role,user in [('runtime',runtime),('maintenance',maintenance)]:
  lines.append('-- '+role)
  for table in tables():
   privileges=['SELECT'] if table=='migrations' or table.endswith('_archives') else ['SELECT','INSERT']
   if table not in IMMUTABLE and table!='migrations' and not table.endswith('_archives'):privileges.append('UPDATE')
   if table in DELETABLE:privileges.append('DELETE')
   if role=='maintenance':
    if table in {'request_log_archives','upstream_attempt_archives'}:privileges+=['INSERT','UPDATE','DELETE']
    elif table in {'audit_events','request_logs','upstream_attempts','request_admissions','exports','outbox_events','enrollment_tokens','payment_events','body_archive_objects'}:privileges.append('DELETE')
    elif table in {'invoice_lines','credit_entries'}:privileges.append('UPDATE')
   lines.append('GRANT '+', '.join(dict.fromkeys(privileges))+' ON `'+database+'`.`'+table+'` TO \''+user+"'@'"+host+"';")
 return '\n'.join(lines)+'\n'
def main():
 parser=argparse.ArgumentParser();parser.add_argument('--database',required=True);parser.add_argument('--runtime-user',required=True);parser.add_argument('--maintenance-user',required=True);parser.add_argument('--host',default='localhost');parser.add_argument('--output',type=Path,required=True);args=parser.parse_args()
 try:sql=render(args.database,args.runtime_user,args.maintenance_user,args.host)
 except ValueError as error:raise SystemExit(str(error))
 with args.output.open('x',encoding='utf-8') as output:output.write(sql)
 print('SQL grants written for review; credentials were not included.')
if __name__=='__main__':main()
