"""Private local key creation and isolated authentication test. No live actions."""
import argparse
import contextlib
import fcntl
import hashlib
import hmac
import importlib.util
import json
import os
from pathlib import Path
import stat
import tempfile
import uuid
from datetime import datetime,timezone,timedelta


def read_private(path):
    st=path.stat()
    if path.is_symlink() or not stat.S_ISREG(st.st_mode) or st.st_uid!=os.getuid() or st.st_mode & 0o077:raise ValueError('Existing key file must be private and owned by you')
    values=json.loads(path.read_text())
    if not isinstance(values,dict) or 'manager' not in values:raise ValueError('Existing sender file lacks a manager key; no changes made')
    for sender,value in values.items():
        if not isinstance(value,str) or len(value) not in (64,128):raise ValueError('Invalid sender key encoding')
        try:bytes.fromhex(value)
        except ValueError:raise ValueError('Invalid sender key encoding')
    return values


def run(root):
    os.umask(0o077)
    root=Path(root).absolute()
    source=root/'consigliere_supervisor.py'
    if not source.is_file() or source.is_symlink():raise ValueError('Installed supervisor not found')
    keys_path=root/'sender_keys.json'
    lock_path=root/'sender_keys.setup.lock'
    fd=os.open(lock_path,os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW,0o600)
    with os.fdopen(fd,'a+') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        existing=keys_path.exists()
        if keys_path.is_symlink():raise ValueError('Symlink key file rejected')
        values=read_private(keys_path) if existing else {'manager':os.urandom(32).hex()}
        spec=importlib.util.spec_from_file_location('installed_supervisor_for_auth_test',source)
        module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
        raw_keys={k:bytes.fromhex(v) for k,v in values.items()}
        checks=[]
        with tempfile.TemporaryDirectory(prefix='qzotic-auth-') as temp:
            base=Path(temp).resolve()
            with module.ConsigliereProductionCore(base/'isolated_test.db',base/'inbox',sender_keys=raw_keys) as core:
                payload={'security_headers':{'sender_id':'manager','event_uuid':str(uuid.uuid4()),'issued_at':datetime.now(timezone.utc).isoformat()},'metadata':{'project_name':'TEST_AUTH_HANDSHAKE','vertical':'ACCOUNTING','lifecycle_state':'HOLD','deadline':(datetime.now(timezone.utc)+timedelta(days=1)).isoformat(),'budget_value':'0.00'}}
                payload['security_headers']['signature']=hmac.new(raw_keys['manager'],module.canonical(payload),hashlib.sha256).hexdigest()
                p=base/'inbox/event.json';p.write_text(json.dumps(payload))
                if core.autonomous_directory_sync_scan()!=['INGESTED']:raise ValueError('Valid signed input rejected')
                checks.append('Valid signature accepted')
                p.write_text(json.dumps(payload))
                if core.autonomous_directory_sync_scan()!=['DUPLICATE']:raise ValueError('Duplicate handling failed')
                checks.append('Exact replay archived without a second record')
                payload['metadata']['budget_value']='1.00';p.write_text(json.dumps(payload))
                if core.autonomous_directory_sync_scan()!=['REJECTED']:raise ValueError('Tampered input accepted')
                checks.append('Tampered signature rejected')
                if core.conn.execute('SELECT COUNT(*) FROM enterprise_portfolio').fetchone()[0]!=1:raise ValueError('Test row count changed')
                if core.conn.execute('SELECT COUNT(*) FROM remediation_lifecycle').fetchone()[0]!=0:raise ValueError('Unexpected action record')
        if not existing:
            # Publish only after isolated validation passes, without overwriting a file created concurrently.
            temporary=None
            try:
                fd,temporary=tempfile.mkstemp(prefix='.sender_keys.',dir=root)
                with os.fdopen(fd,'w') as f:
                    json.dump(values,f);f.write('\n');f.flush();os.fsync(f.fileno())
                os.chmod(temporary,0o600)
                os.link(temporary,keys_path)
            finally:
                if temporary:os.unlink(temporary)
        return {'status':'SIGNING_SETUP_VERIFIED','key_status':'EXISTING_PRIVATE_KEYS_PRESERVED' if existing else 'FRESH_PRIVATE_MANAGER_KEY_CREATED','key_file':str(keys_path),'isolated_checks':checks,'operational_database':'NOT_OPENED','live_actions':'NOT_ENABLED','notifications':'NOT_SENT','notice':'The key is not displayed. Do not upload sender_keys.json. This verifies local signing, not an external live-data connection.'}


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--root',default='/Users/bpa/ForesixaQuant');args=p.parse_args()
    try:print(json.dumps(run(args.root),indent=2))
    except Exception as exc:
        # Do not print secret-bearing exception payloads.
        print(json.dumps({'status':'SETUP_STOPPED','reason':type(exc).__name__,'notice':'No live operation was enabled. Existing keys were not overwritten.'}));raise SystemExit(2)
