import os
import sqlite3
from datetime import datetime
from pathlib import Path

DB_PATH = Path(os.environ.get("WOOSTER_DB_PATH", Path.home() / ".wooster" / "wooster.db")).expanduser()
DB_DIR = DB_PATH.parent


def get_db():
    DB_DIR.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(DB_PATH))
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("""
        CREATE TABLE IF NOT EXISTS agents (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            type TEXT NOT NULL DEFAULT 'claude',
            status TEXT NOT NULL DEFAULT 'running',
            summary TEXT DEFAULT '',
            pid INTEGER DEFAULT NULL,
            cwd TEXT DEFAULT '',
            auto_discovered INTEGER NOT NULL DEFAULT 0,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )
    """)
    for col, defn in [("pid", "INTEGER DEFAULT NULL"), ("cwd", "TEXT DEFAULT ''"),
                      ("auto_discovered", "INTEGER NOT NULL DEFAULT 0"),
                      ("started_at", "TEXT DEFAULT ''"),
                      ("low_cpu_count", "INTEGER NOT NULL DEFAULT 0"),
                      ("tty", "TEXT DEFAULT ''"),
                      ("notified_idle", "INTEGER NOT NULL DEFAULT 0")]:
        try:
            conn.execute(f"ALTER TABLE agents ADD COLUMN {col} {defn}")
        except sqlite3.OperationalError:
            pass
    conn.execute("""
        CREATE TABLE IF NOT EXISTS todos (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            agent_id INTEGER NOT NULL,
            description TEXT NOT NULL,
            completed INTEGER NOT NULL DEFAULT 0,
            created_at TEXT NOT NULL,
            FOREIGN KEY (agent_id) REFERENCES agents(id) ON DELETE CASCADE
        )
    """)
    conn.execute("PRAGMA foreign_keys = ON")

    conn.execute("""
        DELETE FROM agents
        WHERE status = 'done'
          AND auto_discovered = 1
          AND updated_at < datetime('now', '-7 days')
    """)

    conn.execute("""
        DELETE FROM agents
        WHERE status = 'done'
          AND auto_discovered = 1
          AND id NOT IN (
            SELECT id FROM agents
            WHERE status = 'done' AND auto_discovered = 1
            ORDER BY updated_at DESC
            LIMIT 500
          )
    """)

    conn.commit()
    return conn


def now():
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
