import sqlite3
import os

DB_PATH = os.path.join(os.path.dirname(__file__), 'hitl_memory.db')

def init_db():
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS approvals (
        id INTEGER PRIMARY KEY AUTOINCREMENT, 
        agent_name TEXT, 
        code_payload TEXT, 
        status TEXT DEFAULT 'PENDING'
    )''')
    conn.commit()
    conn.close()

init_db()

def request_approval(agent_name: str, code: str) -> int:
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    c.execute("INSERT INTO approvals (agent_name, code_payload) VALUES (?, ?)", (agent_name, code))
    exec_id = c.lastrowid
    conn.commit()
    conn.close()
    return exec_id

def get_pending():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    c.execute("SELECT * FROM approvals WHERE status='PENDING'")
    rows = [dict(r) for r in c.fetchall()]
    conn.close()
    return rows

def resolve(exec_id: int, decision: str):
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    c.execute("UPDATE approvals SET status=? WHERE id=?", (decision, exec_id))
    conn.commit()
    conn.close()
