import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DATA_DIR = path.join(__dirname, '../data');
const DB_PATH = path.join(DATA_DIR, 'paradigms.db');

// 确保数据目录存在
if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
}

// 创建数据库连接
const db = new Database(DB_PATH);

// 初始化表结构
db.exec(`
  CREATE TABLE IF NOT EXISTS paradigms (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT,
    icon TEXT DEFAULT 'sparkles',
    tag_class TEXT DEFAULT 'bg-purple-900/30 text-purple-300',
    tags TEXT,
    specialized_prompt TEXT,
    expert_guidelines TEXT,
    is_custom INTEGER DEFAULT 1,
    created_at TEXT,
    updated_at TEXT
  )
`);

console.log('📦 SQLite 数据库初始化完成:', DB_PATH);

// CRUD 方法
export function getAllParadigms() {
    const rows = db.prepare('SELECT * FROM paradigms ORDER BY created_at DESC').all();
    return rows.map(row => ({
        id: row.id,
        name: row.name,
        description: row.description,
        icon: row.icon,
        tagClass: row.tag_class,
        tags: row.tags ? JSON.parse(row.tags) : [],
        specializedPrompt: row.specialized_prompt,
        expertGuidelines: row.expert_guidelines ? JSON.parse(row.expert_guidelines) : [],
        isCustom: Boolean(row.is_custom),
        createdAt: row.created_at,
        updatedAt: row.updated_at
    }));
}

export function getParadigmById(id) {
    const row = db.prepare('SELECT * FROM paradigms WHERE id = ?').get(id);
    if (!row) return null;
    return {
        id: row.id,
        name: row.name,
        description: row.description,
        icon: row.icon,
        tagClass: row.tag_class,
        tags: row.tags ? JSON.parse(row.tags) : [],
        specializedPrompt: row.specialized_prompt,
        expertGuidelines: row.expert_guidelines ? JSON.parse(row.expert_guidelines) : [],
        isCustom: Boolean(row.is_custom),
        createdAt: row.created_at,
        updatedAt: row.updated_at
    };
}

export function createParadigm(paradigm) {
    const stmt = db.prepare(`
    INSERT INTO paradigms (id, name, description, icon, tag_class, tags, specialized_prompt, expert_guidelines, is_custom, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `);

    const now = new Date().toISOString();
    stmt.run(
        paradigm.id,
        paradigm.name,
        paradigm.description || '',
        paradigm.icon || 'sparkles',
        paradigm.tagClass || 'bg-purple-900/30 text-purple-300',
        JSON.stringify(paradigm.tags || []),
        paradigm.specializedPrompt || '',
        JSON.stringify(paradigm.expertGuidelines || []),
        paradigm.isCustom ? 1 : 0,
        paradigm.createdAt || now,
        now
    );

    return getParadigmById(paradigm.id);
}

export function updateParadigm(id, updates) {
    const existing = getParadigmById(id);
    if (!existing) return null;

    const merged = { ...existing, ...updates };
    const stmt = db.prepare(`
    UPDATE paradigms 
    SET name = ?, description = ?, icon = ?, tag_class = ?, tags = ?, 
        specialized_prompt = ?, expert_guidelines = ?, updated_at = ?
    WHERE id = ?
  `);

    stmt.run(
        merged.name,
        merged.description,
        merged.icon,
        merged.tagClass,
        JSON.stringify(merged.tags || []),
        merged.specializedPrompt,
        JSON.stringify(merged.expertGuidelines || []),
        new Date().toISOString(),
        id
    );

    return getParadigmById(id);
}

export function deleteParadigm(id) {
    const stmt = db.prepare('DELETE FROM paradigms WHERE id = ?');
    const result = stmt.run(id);
    return result.changes > 0;
}

export default db;
