import sqlite3
import uuid
import datetime

db_path = "/app/data/ai_hub.db"

def create_cron_agent():
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 1. Create a dummy Agent Template for the CRON
        template_id = str(uuid.uuid4())
        cursor.execute(
            """INSERT INTO agent_templates (id, name, description, system_prompt_path, max_loop_iterations) 
               VALUES (?, ?, ?, ?, ?)""",
            (template_id, "Prod CRON Agent", "Simple agent triggered every 1 minute via CRON", None, 1)
        )
        
        # 2. Get a user_id (just grab the first one)
        cursor.execute("SELECT id FROM users LIMIT 1")
        user_row = cursor.fetchone()
        if not user_row:
            print("No users found in database.")
            return
        user_id = user_row[0]
        
        # 3. Create a Session
        cursor.execute(
            """INSERT INTO sessions (title, user_id, provider_name, feature_name) 
               VALUES (?, ?, ?, ?)""",
            ("CRON Session - Prod test", user_id, "gemini/gemini-2.5-flash", "test_feature")
        )
        session_id = cursor.lastrowid
        
        # 4. Create the Agent Instance
        instance_id = str(uuid.uuid4())
        now = datetime.datetime.utcnow().isoformat()
        cursor.execute(
            """INSERT INTO agent_instances 
               (id, name, template_id, session_id, user_id, status, current_workspace_jail, current_target_uid, last_heartbeat) 
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (instance_id, "Prod CRON Instance", template_id, session_id, user_id, "idle", "/tmp", None, now)
        )
        
        # 5. Create the CRON Trigger
        trigger_id = str(uuid.uuid4())
        # Let's run it every 1 minute "*/1 * * * *", or just use the literal "60" to mean 60 seconds 
        # based on our scheduler.py implementation (it parses integers as seconds inside AI Hub!). 
        # Based on previous tests, '30' means 30 seconds. So we use '60'.
        cursor.execute(
            """INSERT INTO agent_triggers (id, instance_id, trigger_type, cron_expression) 
               VALUES (?, ?, ?, ?)""",
            (trigger_id, instance_id, "cron", "60")
        )
        
        conn.commit()
        print(f"✅ Successfully provisioned Prod CRON Agent Instance: {instance_id}")
        print(f"✅ Trigger Type: CRON | Interval: 60 seconds")
        conn.close()
    except Exception as e:
        print(f"Database insertion failed: {e}")

create_cron_agent()
