import sqlite3
import os

DB_PATH = os.environ.get("DB_PATH", "/data/planner.db")


def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA foreign_keys=ON")
    return conn


def init_db():
    os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
    conn = get_db()
    c = conn.cursor()
    c.executescript("""
        -- 用户认证（单用户 planner 密码）
        CREATE TABLE IF NOT EXISTS config (
            key TEXT PRIMARY KEY,
            value TEXT NOT NULL
        );

        -- 随手记
        CREATE TABLE IF NOT EXISTS notes (
            id TEXT PRIMARY KEY,
            text TEXT NOT NULL,
            tag TEXT DEFAULT '灵感',
            created_at TEXT DEFAULT (datetime('now')),
            updated_at TEXT DEFAULT (datetime('now'))
        );

        -- 待办事项（四象限）
        CREATE TABLE IF NOT EXISTS todos (
            id TEXT PRIMARY KEY,
            text TEXT NOT NULL,
            quadrant TEXT NOT NULL DEFAULT 'q1',
            done INTEGER DEFAULT 0,
            created_at TEXT DEFAULT (datetime('now')),
            updated_at TEXT DEFAULT (datetime('now'))
        );

        -- 收集箱
        CREATE TABLE IF NOT EXISTS inbox (
            id TEXT PRIMARY KEY,
            text TEXT NOT NULL,
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 提醒
        CREATE TABLE IF NOT EXISTS reminders (
            id TEXT PRIMARY KEY,
            text TEXT NOT NULL,
            time TEXT,
            repeat TEXT DEFAULT 'none',
            enabled INTEGER DEFAULT 1,
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 目标
        CREATE TABLE IF NOT EXISTS goals (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            month TEXT,
            checks TEXT DEFAULT '{}',
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 清单
        CREATE TABLE IF NOT EXISTS checklists (
            id TEXT PRIMARY KEY,
            title TEXT NOT NULL,
            items TEXT DEFAULT '[]',
            archived INTEGER DEFAULT 0,
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 健康打卡 - 项目池
        CREATE TABLE IF NOT EXISTS health_items (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            type TEXT NOT NULL DEFAULT 'health',
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 健康打卡 - 月计划
        CREATE TABLE IF NOT EXISTS health_plans (
            month TEXT NOT NULL,
            type TEXT NOT NULL DEFAULT 'health',
            item_ids TEXT DEFAULT '[]',
            PRIMARY KEY (month, type)
        );

        -- 健康打卡 - 记录
        CREATE TABLE IF NOT EXISTS health_checks (
            date TEXT NOT NULL,
            type TEXT NOT NULL DEFAULT 'health',
            item_id TEXT NOT NULL,
            checked INTEGER DEFAULT 1,
            PRIMARY KEY (date, type, item_id)
        );

        -- 睡眠记录
        CREATE TABLE IF NOT EXISTS sleep_records (
            date TEXT PRIMARY KEY,
            time TEXT NOT NULL,
            minutes REAL,
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 健身记录
        CREATE TABLE IF NOT EXISTS gym_records (
            id TEXT PRIMARY KEY,
            date TEXT NOT NULL,
            type TEXT DEFAULT '',
            duration TEXT DEFAULT '',
            note TEXT DEFAULT '',
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 经期记录
        CREATE TABLE IF NOT EXISTS period_records (
            id TEXT PRIMARY KEY,
            start_date TEXT NOT NULL,
            end_date TEXT,
            note TEXT DEFAULT '',
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 文档
        CREATE TABLE IF NOT EXISTS docs (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            icon TEXT DEFAULT '📄',
            keywords TEXT DEFAULT '',
            extract_rule TEXT DEFAULT 'none',
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 文档条目
        CREATE TABLE IF NOT EXISTS doc_entries (
            id TEXT PRIMARY KEY,
            doc_id TEXT NOT NULL REFERENCES docs(id) ON DELETE CASCADE,
            text TEXT NOT NULL,
            note_id TEXT,
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- 日程模块
        CREATE TABLE IF NOT EXISTS schedule_modules (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            emoji TEXT DEFAULT '📌',
            color TEXT DEFAULT '#667eea',
            sort_order INTEGER DEFAULT 0
        );

        -- 日程安排（每天的时间块）
        CREATE TABLE IF NOT EXISTS schedule_slots (
            date TEXT NOT NULL,
            time_slot TEXT NOT NULL,
            module_id TEXT NOT NULL REFERENCES schedule_modules(id) ON DELETE CASCADE,
            PRIMARY KEY (date, time_slot, module_id)
        );

        -- 每周模板
        CREATE TABLE IF NOT EXISTS weekly_template (
            day INTEGER NOT NULL,
            data TEXT DEFAULT '[]',
            PRIMARY KEY (day)
        );

        -- 周回顾
        CREATE TABLE IF NOT EXISTS reviews (
            week TEXT PRIMARY KEY,
            data TEXT DEFAULT '{}'
        );

        -- Bug 追踪
        CREATE TABLE IF NOT EXISTS bugs (
            id TEXT PRIMARY KEY,
            text TEXT NOT NULL,
            status TEXT DEFAULT 'open',
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- Sleep Buddy 用户
        CREATE TABLE IF NOT EXISTS buddy_users (
            username TEXT PRIMARY KEY,
            password_hash TEXT NOT NULL,
            target_time TEXT DEFAULT '22:00',
            created_at TEXT DEFAULT (datetime('now'))
        );

        -- Sleep Buddy 记录
        CREATE TABLE IF NOT EXISTS buddy_records (
            username TEXT NOT NULL,
            date TEXT NOT NULL,
            time TEXT NOT NULL,
            created_at TEXT DEFAULT (datetime('now')),
            PRIMARY KEY (username, date)
        );

        -- Sleep Buddy 通知
        CREATE TABLE IF NOT EXISTS buddy_notifications (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            from_user TEXT NOT NULL,
            message TEXT NOT NULL,
            time TEXT NOT NULL,
            date TEXT NOT NULL,
            created_at REAL NOT NULL
        );
    """)

    conn.commit()
    conn.close()
