import os
import sys
import json
import sqlite3
from datetime import datetime

class ConsigliereSystemDiagnostic:
    def __init__(self, base_dir="/Users/bpa/ForesixaQuant"):
        self.base_dir = base_dir
        self.db_path = os.path.join(self.base_dir, "qzotic_pure_sandbox.db")
        self.log_dir = os.path.join(self.base_dir, "enterprise_logs")
        
    def execute_complete_parameter_audit(self) -> str:
        timestamp_now = datetime.utcnow().isoformat() + "Z"
        
        # 1. CORE FILESYSTEM BOUNDARY PERIMETER AUDIT
        critical_files = {
            "supervisor_core": "consigliere_supervisor.py",
            "room_auditor": "interaction_auditor.py",
            "launcher_dashboard": "consigliere_control.sh",
            "worker_config_matrix": "worker_config.json",
            "hidden_key_vault": "credentials.env"
        }
        
        file_status_registry = {}
        all_files_present = True
        
        for key, filename in critical_files.items():
            full_path = os.path.join(self.base_dir, filename)
            exists = os.path.exists(full_path)
            file_status_registry[key] = "VERIFIED_PRESENT" if exists else "MISSING_ERROR"
            if not exists:
                all_files_present = False

        # 2. LOCAL RELATIONAL DATABASE STRUCTURAL AUDIT
        db_clear = False
        table_registry_status = "UNINITIALIZED"
        
        if os.path.exists(self.db_path):
            try:
                conn = sqlite3.connect(self.db_path)
                cursor = conn.cursor()
                
                # Check for the mandatory multi-enterprise tracking tables
                cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='enterprise_portfolio';")
                has_portfolio = cursor.fetchone() is not None
                
                cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='remediation_lifecycle';")
                has_remediation = cursor.fetchone() is not None
                
                if has_portfolio and has_remediation:
                    db_clear = True
                    table_registry_status = "SCHEMAS_VERIFIED_INTECT"
                else:
                    table_registry_status = "CORRUPTED_MISSING_TABLES"
                    
                conn.close()
            except Exception as e:
                table_registry_status = f"DATABASE_CONNECT_ERROR: {str(e)}"
        else:
            table_registry_status = "DATABASE_FILE_ABSENT"

        # 3. BACKGROUND MONITOR INGRESS HOOK AUDIT
        log_dir_clear = os.path.exists(self.log_dir)

        # 4. COMPILE UN-DELAYED DASHBOARD JSON PAYLOAD
        system_healthy = all_files_present and db_clear and log_dir_clear
        
        diagnostic_payload = {
            "engine_architecture": "CONSIGLIERE_DIAGNOSTIC_CORE",
            "execution_timestamp": timestamp_now,
            "overall_system_health": "HEALTHY_OPERATIONAL_OK" if system_healthy else "VARIANCE_ATTENTION_REQUIRED",
            "filesystem_perimeter": {
                "status": "PASS" if all_files_present else "FAIL",
                "file_registry": file_status_registry
            },
            "database_integrity_layer": {
                "status": "PASS" if db_clear else "FAIL",
                "storage_path": self.db_path,
                "table_verification_state": table_registry_status
            },
            "background_monitor_ingress": {
                "status": "PASS" if log_dir_clear else "FAIL",
                "monitored_directory_path": self.log_dir
            }
        }
        
        return json.dumps(diagnostic_payload, indent=4)

if __name__ == "__main__":
    auditor = ConsigliereSystemDiagnostic()
    print(auditor.execute_complete_parameter_audit())
