const express = require('express');
const prisma = require('../lib/prisma');
const { authMiddleware } = require('../lib/auth');

const router = express.Router();

// 获取角色库（所有已上架角色）
router.get('/', async (req, res) => {
  try {
    const roles = await prisma.role.findMany({
      where: { status: 'running' },
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        displayName: true,
        avatar: true,
        desc: true,
        price: true,
        status: true,
      },
    });
    res.json({ roles });
  } catch (err) {
    console.error('获取角色列表失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取角色详情
router.get('/:id', async (req, res) => {
  try {
    const role = await prisma.role.findUnique({
      where: { id: req.params.id },
      select: {
        id: true,
        displayName: true,
        avatar: true,
        desc: true,
        price: true,
        status: true,
        gender: true,
        age: true,
        relationship: true,
        personality: true,
        background: true,
        speechStyle: true,
        greeting: true,
        creatorId: true,
      },
    });
    if (!role) {
      return res.status(404).json({ error: '角色不存在' });
    }
    res.json({ role });
  } catch (err) {
    console.error('获取角色详情失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取当前用户创建的角色
router.get('/my/roles', authMiddleware, async (req, res) => {
  try {
    const roles = await prisma.role.findMany({
      where: { creatorId: req.userId },
      orderBy: { createdAt: 'desc' },
    });
    res.json({ roles });
  } catch (err) {
    console.error('获取我的角色失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 发布新角色
router.post('/', authMiddleware, async (req, res) => {
  try {
    const data = req.body;
    if (!data.displayName || !data.greeting || !data.personality || !data.background || !data.speechStyle) {
      return res.status(400).json({ error: '必填字段缺失' });
    }

    const role = await prisma.role.create({
      data: {
        creatorId: req.userId,
        displayName: data.displayName,
        gender: data.gender || 'unknown',
        age: data.age || null,
        relationship: data.relationship || null,
        personality: data.personality,
        background: data.background,
        speechStyle: data.speechStyle,
        likes: data.likes || null,
        dislikes: data.dislikes || null,
        memories: data.memories || null,
        secrets: data.secrets || null,
        greeting: data.greeting,
        systemPrompt: data.systemPrompt || null,
        model: data.model || 'gpt-4o',
        temperature: parseFloat(data.temperature) || 0.8,
        maxTokens: parseInt(data.maxTokens) || 2048,
        enableMemory: data.enableMemory ?? true,
        enableTools: data.enableTools ?? false,
        agentId: data.agentId || null,
        soulMd: data.soulMd || null,
        configYaml: data.configYaml || null,
        avatar: data.avatar || null,
        desc: data.desc || data.personality.slice(0, 50),
        price: parseFloat(data.price) || 0,
        status: 'running',
      },
    });

    res.json({ role });
  } catch (err) {
    console.error('发布角色失败:', err);
    res.status(500).json({ error: '发布失败' });
  }
});

// 编辑角色
router.put('/:id', authMiddleware, async (req, res) => {
  try {
    const existing = await prisma.role.findUnique({ where: { id: req.params.id } });
    if (!existing) {
      return res.status(404).json({ error: '角色不存在' });
    }
    if (existing.creatorId !== req.userId) {
      return res.status(403).json({ error: '无权编辑他人角色' });
    }

    const data = req.body;
    const role = await prisma.role.update({
      where: { id: req.params.id },
      data: {
        displayName: data.displayName ?? existing.displayName,
        gender: data.gender ?? existing.gender,
        age: data.age ?? existing.age,
        relationship: data.relationship ?? existing.relationship,
        personality: data.personality ?? existing.personality,
        background: data.background ?? existing.background,
        speechStyle: data.speechStyle ?? existing.speechStyle,
        likes: data.likes ?? existing.likes,
        dislikes: data.dislikes ?? existing.dislikes,
        memories: data.memories ?? existing.memories,
        secrets: data.secrets ?? existing.secrets,
        greeting: data.greeting ?? existing.greeting,
        systemPrompt: data.systemPrompt ?? existing.systemPrompt,
        model: data.model ?? existing.model,
        temperature: parseFloat(data.temperature) || existing.temperature,
        maxTokens: parseInt(data.maxTokens) || existing.maxTokens,
        enableMemory: data.enableMemory ?? existing.enableMemory,
        enableTools: data.enableTools ?? existing.enableTools,
        soulMd: data.soulMd ?? existing.soulMd,
        configYaml: data.configYaml ?? existing.configYaml,
        avatar: data.avatar ?? existing.avatar,
        desc: data.desc ?? existing.desc,
        price: parseFloat(data.price) || existing.price,
        status: data.status ?? existing.status,
      },
    });

    res.json({ role });
  } catch (err) {
    console.error('编辑角色失败:', err);
    res.status(500).json({ error: '编辑失败' });
  }
});

// 获取角色详情（含 Soul.md 和 config.yaml，仅创建者可访问）
router.get('/:id/full', authMiddleware, async (req, res) => {
  try {
    const role = await prisma.role.findUnique({ where: { id: req.params.id } });
    if (!role) {
      return res.status(404).json({ error: '角色不存在' });
    }
    if (role.creatorId !== req.userId) {
      return res.status(403).json({ error: '无权查看' });
    }
    res.json({ role });
  } catch (err) {
    console.error('获取角色完整信息失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

module.exports = router;
