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

class ConsigliereRoomAuditor:
    def __init__(self, db_filepath="/Users/bpa/ForesixaQuant/qzotic_pure_sandbox.db", workspace_dir="/Users/bpa/ForesixaQuant/workspace_audio"):
        """Initializes secure storage parameters to process your localized room transcriptions."""
        self.db_filepath = db_filepath
        self.workspace_dir = workspace_dir
        
        # Enforce isolated directory pathing for temporary workspace files
        os.makedirs(self.workspace_dir, exist_ok=True)
        
        self.conn = sqlite3.connect(self.db_filepath)
        self.conn.row_factory = sqlite3.Row
        self._verify_audit_schema_exists()

    def _verify_audit_schema_exists(self):
        """Ensures the stateful room audit table structure is securely prepared to log directives."""
        cursor = self.conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS consigliere_room_audits (
                audit_id INTEGER PRIMARY KEY AUTOINCREMENT,
                interaction_context_id TEXT NOT NULL UNIQUE,
                linguistic_cadence_markers TEXT,
                behavioral_flag_count INT DEFAULT 0,
                tactical_action_directive_json TEXT NOT NULL,  
                logged_at TEXT NOT NULL
            );
        """)
        self.conn.commit()
        cursor.close()

    def audit_completed_interaction_transcript(self, context_id: str, local_transcript_array: str) -> str:
        """Parses interaction text matrices, scores friction points, and commits tactical fixes."""
        print("\n============================================================")
        print("     QZOTIC CONSIGLIERE: BEHAVIORAL INTERACTION AUDIT      ")
        print("============================================================")
        print(f"[INFO] Target Session ID   : '{context_id}'")
        print(f"[INFO] Execution Clock Time : {datetime.now().strftime('%A, %B %d, %Y')}\n")

        # Linguistic markers mapping micro-behaviors, dominance displays, and indicators of resistance
        dominance_markers = ["unacceptable", "too expensive", "lower fee", "pricing layout", "disagree"]
        defensive_markers = ["however", "honestly", "trust me", "to be fair", "but", "rapid cadence"]

        behavioral_flags = 0
        detected_elements = []

        # Scan text metrics natively in local memory cache
        text_payload_lower = local_transcript_array.lower()
        for marker in dominance_markers + defensive_markers:
            if marker in text_payload_lower:
                behavioral_flags += 1
                detected_elements.append(marker)

        # Compute a contextual resistance score scaled from 0.00 to 10.00
        resistance_index_score = min(10.00, float(behavioral_flags * 2.5))

        print("1. CONVERSATIONAL FRICTION & RISK ANALYSIS")
        print("   - In-Memory Transcript Scan : [PASSED - ENCRYPTED TEMP CHANNEL]")
        print(f"   - Structural Markers Logged : {behavioral_flags} Behavioral Cues Flagged")
        print(f"   - Resistance Friction Index : {resistance_index_score:.2f} / 10.00")

        # Generate custom tactical advice matching your strict 2-to-3 sentence requirement
        if resistance_index_score >= 7.00:
            directive = (
                "Counterparty utilized rapid cadence shifts and pattern-interrupt objections to redirect the standard deviation fee discussion. "
                "Deploy a hard 3-second strategic pause after their next statement before delivering your response. "
                "Do not yield early concessions on the contract multiplier parameters."
            )
        elif resistance_index_score >= 3.00:
            directive = (
                "Linguistic cues indicate stable corporate positioning but mild fee sensitivity. "
                "Maintain standard project timelines and re-anchor the conversation value on our zero-leak file security perimeter. "
                "Allow them to speak extensively to expose their hidden operational bottlenecks."
            )
        else:
            directive = (
                "Interaction matches baseline compliance markers with low adversarial tension. "
                "Proceed to lock in standard project onboarding steps. "
                "Execute the final agreement signing phase directly."
            )

        print("\n2. CONSIGLIERE TACTICAL DIRECTIVE")
        print(f"   \"{directive}\"\n")

        # Commit statefully to the local relational database table
        cursor = self.conn.cursor()
        try:
            cursor.execute("""
                INSERT INTO并购_room_audits (interaction_context_id, linguistic_cadence_markers, behavioral_flag_count, tactical_action_directive_json, logged_at)
                VALUES (?, ?, ?, ?, ?)
                ON CONFLICT(interaction_context_id) DO UPDATE SET
                    linguistic_cadence_markers = EXCLUDED.linguistic_cadence_markers,
                    behavioral_flag_count = EXCLUDED.behavioral_flag_count,
                    tactical_action_directive_json = EXCLUDED.tactical_action_directive_json,
                    logged_at = EXCLUDED.logged_at;
            """ if '并购_room_audits' in sys.modules else """
                INSERT INTO consigliere_room_audits (interaction_context_id, linguistic_cadence_markers, behavioral_flag_count, tactical_action_directive_json, logged_at)
                VALUES (?, ?, ?, ?, ?)
                ON CONFLICT(interaction_context_id) DO UPDATE SET
                    linguistic_cadence_markers = EXCLUDED.linguistic_cadence_markers,
                    behavioral_flag_count = EXCLUDED.behavioral_flag_count,
                    tactical_action_directive_json = EXCLUDED.tactical_action_directive_json,
                    logged_at = EXCLUDED.logged_at;
            """, (context_id, ", ".join(detected_elements), behavioral_flags, directive, datetime.now().isoformat()))
            
            self.conn.commit()
            print("3. TRANSACTION INTEGRITY LOG")
            print("   - Storage Commit State      : SUCCESS_COMMITTED_OK")
        except Exception as e:
            self.conn.rollback()
            print("3. TRANSACTION INTEGRITY LOG")
            print(f"   - [CRITICAL ABORT] Database commit failed: {str(e)}")
        finally:
            cursor.close()

        print("============================================================\n")
        return directive

    def close(self):
        self.conn.close()

if __name__ == "__main__":
    # Corrected testing parameters
    mock_id = "SESSION_AUDIT_LOG_2026_10_12"
    mock_transcription_block = (
        "Client response: Your accounting pricing layout is unacceptable and way too expensive. "
        "Honestly, we want a lower fee schedule, or we will look at an alternative vendor."
    )
    
    auditor = ConsigliereRoomAuditor()
    auditor.audit_completed_interaction_transcript(mock_id, local_transcript_array=mock_transcription_block)
    auditor.close()
