#!/usr/bin/env python3
"""Administration is local to the host. No secret credentials in web requests."""
import sys,os,json,getpass,secrets,base64,sqlite3,argparse,shutil
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from storage import Store,password_hash
from fields import VERSION

def main():
 p=argparse.ArgumentParser();p.add_argument('command',choices=['init-admin','reset-password','seed-demo','backup','preflight']);p.add_argument('--data',default=os.getenv('DATA_DIR','data'));p.add_argument('--email');p.add_argument('--output');args=p.parse_args();prod=os.getenv('APP_ENV')=='production'
 if args.command=='seed-demo' and prod:raise SystemExit('Refusing demonstration data in production.')
 st=Store(args.data,os.getenv('ENCRYPTION_KEY'),prod)
 if args.command=='seed-demo':
  from demo_seed import seed
  print(json.dumps(seed(st),indent=2));return
 if args.command in ('init-admin','reset-password'):
  email=(args.email or input('Email: ')).strip().lower();password=getpass.getpass('New password (at least 12 characters): ')
  if password!=getpass.getpass('Repeat password: '):raise SystemExit('Passwords differ')
  with st.db() as c:
   if args.command=='init-admin':
    name=input('Administrator display name: ').strip();secret=base64.b32encode(secrets.token_bytes(20)).decode().rstrip('=')
    c.execute("INSERT INTO users(email,name,password_hash,role,approved,totp_secret) VALUES(?,?,?,'admin',1,?)",(email,name,password_hash(password),st.seal(secret)))
    print('Store this secret in your authenticator app, then close this terminal. Do not put it in your website: '+secret)
   else:
    u=c.execute('SELECT id FROM users WHERE email=?',(email,)).fetchone()
    if not u:raise SystemExit('Account not found')
    c.execute('UPDATE users SET password_hash=?,must_change=1 WHERE id=?',(password_hash(password),u['id']));c.execute('DELETE FROM sessions WHERE user_id=?',(u['id'],));st.audit(c,None,'host_password_reset',u['id'])
  print('Account saved.');return
 if args.command=='backup':
  if not args.output:raise SystemExit('--output is required; choose a protected, new directory')
  dest=Path(args.output);dest.mkdir(mode=0o700,parents=True,exist_ok=False)
  with st.db() as src,sqlite3.connect(dest/'portal.sqlite3') as dst:src.backup(dst)
  shutil.copytree(st.files,dest/'files');print('Database and encrypted files backed up. Preserve the encryption key separately and test restoration.');return
 if args.command=='preflight':
  with st.db() as c:
   report={'version':VERSION,'production':prod,'database_integrity':c.execute('PRAGMA integrity_check').fetchone()[0],'administrator_count':c.execute("SELECT count(*) FROM users WHERE role='admin' AND disabled=0").fetchone()[0], 'admin_mfa_missing':c.execute("SELECT count(*) FROM users WHERE role='admin' AND disabled=0 AND totp_secret IS NULL").fetchone()[0],'https_configured':os.getenv('PUBLIC_BASE_URL','').startswith('https://'),'external_key_configured':bool(os.getenv('ENCRYPTION_KEY')),'privacy_notice_configured':os.getenv('PRIVACY_NOTICE_URL','').startswith('https://'),'malware_scanner_configured':bool(os.getenv('CLAMAV_SOCKET')),'season_2027_rules_approved':bool(st.rules(c,2027).get('approved')),'note':'Configuration checks only; not a penetration test or proof of live TLS, scanner operation or regulatory approval.'}
  print(json.dumps(report,indent=2))
if __name__=='__main__':main()
