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

class MasterEcosystemTestSuite:
    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_system_wide_validation(self) -> bool:
        print("\n============================================================")
        print("     QZOTIC SOVEREIGN ENGINE: SYSTEM INTEGRITY RUNTIME      ")
        print("============================================================")
        print(f"[INFO] Project Workspace Root : {self.base_dir}")
        print(f"[INFO] Verification Clock Time: {datetime.now().strftime('%A, %B %d, %Y')}\n")

        # 1. VERIFY FILESYSTEM PERIMETER
        critical_files = [
            "consigliere_supervisor.py",
            "interaction_auditor.py",
            "generated/secure_backup_vault.py",
            "generated/verify_ledger_json.py",
            "generated/portfolio_performance_ranker.py"
        ]
        
        print("1. FILESYSTEM BOUNDARY PERIMETER PASS")
        all_files_present = True
        for filename in critical_files:
            full_path = os.path.join(self.base_dir, filename)
            exists = os.path.exists(full_path)
            status = "[PASSED - FILE PRESENT]" if exists else "[MISSING_ERROR - HALTED]"
            print(f"   - {filename:<43}: {status}")
            if not exists:
                all_files_present = False

        if not all_files_present:
            print("\n============================================================")
            print(" MASTER INTEGRITY RUNTIME STATUS: CRITICAL_FILES_MISSING")
            print("============================================================\n")
            return False

        # 2. EXERCISE SYSTEM ENGINE CALLS
        print("\n2. STATEFUL ENGINE OPERATIONS TRIAGE")
        
        # Import target modules dynamically to ensure runtime isolation
        sys.path.append(self.base_dir)
        try:
            from consigliere_supervisor import ConsigliereAutonomousOrchestrator
            from interaction_auditor import ConsigliereRoomAuditor
        except ImportError as ie:
            print(f"   - [FAIL] Core modules failed namespace ingestion: {str(ie)}")
            return False

        # A. Exercise background supervisor daemon & directory sync loops
        try:
            orchestrator = ConsigliereAutonomousOrchestrator(db_filepath=self.db_path, monitor_dir=self.log_dir)
            
            # Seed a mock payload safely to exercise the transactional unlink pass
            sample_payload = {
                "metadata": {
                    "project_name": "TEST_VERIFICATION_PASS_NODE",
                    "vertical": "ACCOUNTING",
                    "lifecycle_state": "ACTIVE",
                    "deadline": "2026-12-31",
                    "budget_value": "1000.00",
                    "days_lagging": 0
                }
            }
            mock_file = os.path.join(self.log_dir, "test_verification_stream.json")
            with open(mock_file, "w") as f:
                json.dump(sample_payload, f, indent=4)
                
            orchestrator.autonomous_directory_sync_scan()
            orchestrator.execute_autonomous_triage_loop()
            orchestrator.close()
            print("   - Ingress Directory & Database Sync  : [PASSED - TRANSACTION SECURED]")
        except Exception as e:
            print(f"   - [FAIL] Ingress Supervisor engine crashed: {str(e)}")
            return False

        # B. Exercise conversational linguistic room auditor loops
        try:
            auditor = ConsigliereRoomAuditor(db_filepath=self.db_path)
            mock_id = "TEST_SUITE_AUDIT_LOG_ENTRY"
            mock_text = "Client response: This pricing structure is unacceptable. We want a lower fee schedule."
            auditor.audit_completed_interaction_transcript(mock_id, local_transcript_array=mock_text)
            auditor.close()
            print("   - Consigliere Behavioral Room Audit  : [PASSED - SUCCESS_COMMITTED_OK]")
        except Exception as e:
            print(f"   - [FAIL] Conversational auditor engine crashed: {str(e)}")
            return False

        print("\n============================================================")
        print(" MASTER INTEGRITY RUNTIME STATUS: 100% OPERATIONAL SUCCESS")
        print(" STATUS: ECOSYSTEM SECURITY PERIMETER FULLY SECURED.")
        print("============================================================\n")
        return True

if __name__ == "__main__":
    suite = MasterEcosystemTestSuite()
    suite.execute_system_wide_validation()
