import express from 'express';
import cors from 'cors';
import { getAllParadigms, getParadigmById, createParadigm, updateParadigm, deleteParadigm } from './db.js';

const app = express();
const PORT = process.env.API_PORT || 3001;

// 中间件
app.use(cors());
app.use(express.json());

// API 路由
// 获取所有范式
app.get('/api/paradigms', (req, res) => {
    try {
        const paradigms = getAllParadigms();
        res.json({ success: true, data: paradigms });
    } catch (error) {
        console.error('获取范式列表失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 获取单个范式
app.get('/api/paradigms/:id', (req, res) => {
    try {
        const paradigm = getParadigmById(req.params.id);
        if (!paradigm) {
            return res.status(404).json({ success: false, error: '范式不存在' });
        }
        res.json({ success: true, data: paradigm });
    } catch (error) {
        console.error('获取范式失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 创建范式
app.post('/api/paradigms', (req, res) => {
    try {
        const paradigm = createParadigm(req.body);
        console.log('✅ 创建范式:', paradigm.name);
        res.status(201).json({ success: true, data: paradigm });
    } catch (error) {
        console.error('创建范式失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 更新范式
app.put('/api/paradigms/:id', (req, res) => {
    try {
        const paradigm = updateParadigm(req.params.id, req.body);
        if (!paradigm) {
            return res.status(404).json({ success: false, error: '范式不存在' });
        }
        console.log('✅ 更新范式:', paradigm.name);
        res.json({ success: true, data: paradigm });
    } catch (error) {
        console.error('更新范式失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 删除范式
app.delete('/api/paradigms/:id', (req, res) => {
    try {
        const deleted = deleteParadigm(req.params.id);
        if (!deleted) {
            return res.status(404).json({ success: false, error: '范式不存在' });
        }
        console.log('✅ 删除范式:', req.params.id);
        res.json({ success: true });
    } catch (error) {
        console.error('删除范式失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 健康检查
app.get('/api/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`🚀 API 服务器已启动: http://localhost:${PORT}`);
    console.log(`   - GET    /api/paradigms`);
    console.log(`   - GET    /api/paradigms/:id`);
    console.log(`   - POST   /api/paradigms`);
    console.log(`   - PUT    /api/paradigms/:id`);
    console.log(`   - DELETE /api/paradigms/:id`);
});
