import { Router } from 'express';
import fs from 'fs';
import path from 'path';

const PROJECT_ROOT = path.resolve(__dirname, '..', '..', '..');

export const promptsRouter = Router();

const PROMPT_FILES: Record<string, string> = {
  storyboard: 'prompts/分镜.md',
  image: 'prompts/图片提示词.md',
  video: 'prompts/视频提示词.md',
};

promptsRouter.get('/:accountId/:type', (req, res) => {
  const { accountId, type } = req.params;
  const relPath = PROMPT_FILES[type];
  if (!relPath) return res.status(400).json({ error: 'Unknown type: ' + type });

  const fullPath = path.join(PROJECT_ROOT, 'accounts', accountId, relPath);
  if (!fs.existsSync(fullPath)) return res.status(404).json({ error: 'File not found' });

  res.json({ path: relPath, content: fs.readFileSync(fullPath, 'utf-8') });
});

promptsRouter.put('/:accountId/:type', (req, res) => {
  const { accountId, type } = req.params;
  const { content } = req.body;
  const relPath = PROMPT_FILES[type];
  if (!relPath) return res.status(400).json({ error: 'Unknown type: ' + type });

  const fullPath = path.join(PROJECT_ROOT, 'accounts', accountId, relPath);
  const dir = path.dirname(fullPath);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

  fs.writeFileSync(fullPath, content, 'utf-8');
  res.json({ ok: true });
});

promptsRouter.get('/:accountId', (req, res) => {
  res.json(Object.keys(PROMPT_FILES).map((type) => ({
    type,
    path: PROMPT_FILES[type],
  })));
});
