"""Read-only local inventory and schema scan; does not approve deployment."""
import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import sqlite3


def inspect_database(path, *, operational=False):
    if not path.is_file():
        return {'status':'MISSING','path':str(path)}
    conn=None
    try:
        conn=sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True,timeout=5)
        integrity=[r[0] for r in conn.execute('PRAGMA integrity_check')]
        foreign_keys=conn.execute('PRAGMA foreign_key_check').fetchall()
        result={'status':'PASS' if integrity==['ok'] and not foreign_keys else 'FAIL','path':str(path),'integrity_ok':integrity==['ok'],'foreign_key_violations':len(foreign_keys),'schema_version':conn.execute('PRAGMA user_version').fetchone()[0]}
        if operational:
            fields={r[1]:r[2].upper() for r in conn.execute('PRAGMA table_info(enterprise_portfolio)')}
            correct=fields.get('allocated_budget_cents')=='INTEGER' and 'allocated_budget' not in fields
            result['portfolio_budget_storage']='INTEGER_CENTS' if correct else 'UNVERIFIED_OR_LEGACY'
            if correct:
                bad=conn.execute("SELECT COUNT(*) FROM enterprise_portfolio WHERE typeof(allocated_budget_cents)!='integer' OR allocated_budget_cents<0 OR allocated_budget_cents>900000000000000000").fetchone()[0]
                result['invalid_budget_rows']=bad
                correct=bad==0
            if not correct:result['status']='FAIL'
        return result
    except sqlite3.Error:
        return {'status':'FAIL','path':str(path),'reason':'Database could not be read or schema check failed'}
    finally:
        if conn is not None:conn.close()


def execute_wider_ecosystem_verification(base_path='/Users/bpa/ForesixaQuant'):
    root=Path(base_path).absolute()
    components={
        'Consigliere supervisor':'consigliere_supervisor.py',
        'Luxzia research system':'luxzia_core.py',
        'Ledger validator (requested filename)':'generated/verify_ledger_json.py',
        'Portfolio ranker (requested filename)':'generated/portfolio_performance_ranker.py',
    }
    files={}
    for label,name in components.items():
        path=root/name
        entry={'path':str(path),'status':'MISSING'}
        if path.is_file():
            try:
                compile(path.read_text(encoding='utf-8'),str(path),'exec')
                entry['status']='FOUND_SYNTAX_VALID'
            except (OSError,UnicodeError,SyntaxError):
                entry['status']='UNREADABLE_OR_INVALID_SYNTAX'
        files[label]=entry
    operational=root/'qzotic_pure_sandbox.db'
    current=root/'luxzia_research.db'
    legacy=root/'lucxia_research.db'
    conflict=current.exists() and legacy.exists()
    research=legacy if legacy.exists() and not current.exists() else current
    isolation='UNVERIFIED'
    if conflict:
        isolation='CONFLICT_BOTH_RESEARCH_FILENAMES_EXIST'
    elif operational.exists() and research.exists():
        try:isolation='SEPARATE_FILES' if not os.path.samefile(operational,research) else 'FAIL_SAME_FILE'
        except OSError:isolation='UNVERIFIED'
    operational_result=inspect_database(operational,operational=True)
    research_result=inspect_database(research)
    passed=all(r['status']=='FOUND_SYNTAX_VALID' for r in files.values()) and operational_result['status']=='PASS' and research_result['status']=='PASS' and isolation=='SEPARATE_FILES'
    return {
        'checked_at_utc':datetime.now(timezone.utc).isoformat(),
        'scope':'Read-only file inventory, syntax, database integrity, portfolio budget storage and file isolation only',
        'components':files,
        'operational_database':operational_result,
        'research_database':research_result,
        'storage_isolation':isolation,
        'inventory_status':'PASS' if passed else 'INCOMPLETE_OR_FAILED',
        'deployment_status':'UNVERIFIED',
        'not_verified':['IRS Form 8949 ledger/business rules and transmission','Trading feeds and order safety','Approved action handler outcomes','Notification gateway and phone receipt','Host scheduler','Mobile WebSocket and diagnostic-button integration'],
        'notice':'Files found are not proof of connected services. Portfolio budget storage is not an IRS ledger compliance test. This scan neither executes modules nor modifies database records.'
    }


if __name__=='__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('--root',default='/Users/bpa/ForesixaQuant')
    args=parser.parse_args()
    result=execute_wider_ecosystem_verification(args.root)
    print(json.dumps(result,indent=2))
    raise SystemExit(0 if result['inventory_status']=='PASS' else 2)
