# File: /Users/bpa/Desktop/ForesixaQuant/etv_blueprint_provisioner.py
# Description: Automated 10-Minute Ephemeral Ingress & Bot Castle Provisioner
import os
import json
import time
import sqlite3
from pathlib import Path

ROOT_DIR = Path("/Users/bpa/Desktop/ForesixaQuant/products")
DB_PATH = Path("/Users/bpa/Desktop/ForesixaQuant/trading_live.db")
LEASE_WINDOW_SECONDS = 600  # Strict 10-Minute Self-Destruct Timer

def initialize_database():
    """Ensure the local database ledger has the token tracking tables ready."""
    os.makedirs(ROOT_DIR, exist_ok=True)
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS setup_tokens (
            token TEXT PRIMARY KEY,
            bot_name TEXT NOT NULL,
            status TEXT NOT NULL,
            created_at REAL NOT NULL,
            expires_at REAL NOT NULL
        )
    """)
    conn.commit()
    conn.close()

def provision_bot_castle(bot_name):
    """Automated step: Instantly builds the sandboxed directory structure."""
    bot_path = ROOT_DIR / bot_name
    os.makedirs(bot_path / "weights", exist_ok=True)
    os.makedirs(bot_path / "training_logs", exist_ok=True)
    
    # Write the compliant blueprint configuration JSON profile
    profile_data = {
        "bot_identity": bot_name,
        "operational_status": "AUTOMATED_PROVISION_COMPLETE",
        "blueprint_version": "2.5_Hardened",
        "timestamp_stamped": time.time(),
        "storage_lane": str(bot_path / "weights")
    }
    
    with open(bot_path / "development_profile.json", "w") as f:
        json.dump(profile_data, f, indent=2)
    print(f"  [AUTOMATION] 🤖 Standalone castle directories built for: {bot_name}")

def scan_and_enforce_decay():
    """Loops through tokens, provisions on match, and enforces 10-minute self-destruct."""
    print("🛡️  ETV BLUEPRINT ENGINE: Monitoring local asset rails...")
    initialize_database()
    
    while True:
        current_time = time.time()
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        
        # 1. Fetch newly submitted requests
        cursor.execute("SELECT token, bot_name, created_at FROM setup_tokens WHERE status='PENDING'")
        pending_requests = cursor.fetchall()
        
        for token, bot_name, created_at in pending_requests:
            print(f"\n⚠️  [TOKEN DETECTED] Validating session token: {token}")
            # Provision the local assets instantly
            provision_bot_castle(bot_name)
            
            # Lock in the absolute 10-minute expiration window
            expires_at = created_at + LEASE_WINDOW_SECONDS
            cursor.execute(
                "UPDATE setup_tokens SET status='ACTIVE', expires_at=? WHERE token=?", 
                (expires_at, token)
            )
            print(f"  ⏳ [TIMER SET] 10-minute countdown initiated. Expires at T+600s.")
            
        # 2. Scan for expired tokens and forcefully execute self-destruct evacuation
        cursor.execute("SELECT token, bot_name FROM setup_tokens WHERE status='ACTIVE' AND ? > expires_at", (current_time,))
        expired_sessions = cursor.fetchall()
        
        for token, bot_name in expired_sessions:
            print(f"\n🚨 [SELF-DESTRUCT TRIGGERED] 10 minutes expired for Token: {token}")
            cursor.execute("UPDATE setup_tokens SET status='EXPIRED' WHERE token=?", (token,))
            print(f"  🔒 [EVACUATION COMPLETE] Link severed. Ingress pathway forcefully destroyed.")
            
        conn.commit()
        conn.close()
        time.sleep(5)  # Scan every 5 seconds

if __name__ == "__main__":
    scan_and_enforce_decay()
