#!/usr/bin/env python3
"""
TokenShield Working Memory & Scratchpad Storage Module
Handles scratchpad markdown files and key-value architectural memory.
"""

import os
import sys
import time
import sqlite3

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIR not in sys.path:
    sys.path.insert(0, SCRIPT_DIR)

from agent_rag_db import DB_PATH, SCRATCHPAD_PATH, USER_RULES_PATH, init_db


def read_scratchpad():
    if not os.path.exists(SCRATCHPAD_PATH):
        return {"content": "Scratchpad is empty.", "exists": False}
    with open(SCRATCHPAD_PATH, "r", encoding="utf-8") as f:
        return {"content": f.read(), "exists": True, "path": SCRATCHPAD_PATH}


def update_scratchpad(content: str, append: bool = False):
    os.makedirs(os.path.dirname(SCRATCHPAD_PATH), exist_ok=True)
    mode = "a" if append else "w"
    with open(SCRATCHPAD_PATH, mode, encoding="utf-8") as f:
        if append:
            f.write("\n\n" + content)
        else:
            f.write(content)
    return {"success": True, "path": SCRATCHPAD_PATH}


def store_memory(key: str, value: str, category: str = "general"):
    os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
    if not os.path.exists(DB_PATH):
        init_db(sqlite3.connect(DB_PATH))
    conn = sqlite3.connect(DB_PATH)
    conn.execute("""
        INSERT INTO architectural_memory (key, value, category, updated_at)
        VALUES (?, ?, ?, ?)
        ON CONFLICT(key) DO UPDATE SET value=excluded.value, category=excluded.category, updated_at=excluded.updated_at;
    """, (key, value, category, time.time()))
    conn.commit()
    conn.close()
    return {"success": True, "key": key, "category": category}


def get_memory(key: str):
    if not os.path.exists(DB_PATH):
        return {"found": False}
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    row = conn.execute("SELECT * FROM architectural_memory WHERE key = ?;", (key,)).fetchone()
    conn.close()
    if not row:
        return {"found": False, "key": key}
    return {"found": True, "key": row["key"], "value": row["value"], "category": row["category"]}


def list_memory():
    if not os.path.exists(DB_PATH):
        return {"entries": []}
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute("SELECT key, value, category, updated_at FROM architectural_memory ORDER BY updated_at DESC;").fetchall()
    conn.close()
    return {"entries": [{"key": r["key"], "value": r["value"], "category": r["category"], "updated_at": r["updated_at"]} for r in rows]}


def delete_memory(key: str):
    if not os.path.exists(DB_PATH):
        return {"success": False, "error": "no database"}
    conn = sqlite3.connect(DB_PATH)
    conn.execute("DELETE FROM architectural_memory WHERE key = ?;", (key,))
    conn.commit()
    conn.close()
    return {"success": True, "key": key}


def save_user_rules(content: str):
    os.makedirs(os.path.dirname(USER_RULES_PATH), exist_ok=True)
    with open(USER_RULES_PATH, "w", encoding="utf-8") as f:
        f.write(content)
    store_memory("user_rules", content, "rule")
    return {"success": True, "path": USER_RULES_PATH}


def get_user_rules():
    if os.path.exists(USER_RULES_PATH):
        with open(USER_RULES_PATH, "r", encoding="utf-8") as f:
            return {"content": f.read(), "path": USER_RULES_PATH}
    return {"content": "", "path": USER_RULES_PATH}
