import Koa from 'koa';
import cors from '@koa/cors';
import Router from '@koa/router';
import bodyParser from '@koa/bodyparser';
import koaBody from 'koa-body';
import serve from 'koa-static';
import mount from 'koa-mount';
import path from 'path';
import { config } from './config';
import { connectDatabase } from './models';
import { errorHandler } from './middleware/errorHandler';
import authRoutes from './modules/auth/auth.controller';
import ttsRoutes from './modules/tts/tts.controller';
import audioRoutes from './modules/audio/audio.controller';
import memberRoutes from './modules/member/member.controller';
import shareRoutes from './modules/share/share.controller';
import aiRoutes from './modules/ai/ai.controller';
import aiContentRoutes from './modules/ai-content/ai-content.controller';
import playerRoutes from './modules/player/player.controller';
import favoritesRoutes from './modules/favorites/favorites.controller';
import preferencesRoutes from './modules/preferences/preferences.controller';
import searchRoutes from './modules/search/search.controller';
import categoriesRoutes from './modules/categories/categories.controller';
import commentsRoutes from './modules/comments/comments.controller';
import notificationsRoutes from './modules/notifications/notifications.controller';
import albumsRoutes from './modules/albums/albums.controller';
import templatesRoutes from './modules/templates/templates.controller';
import bgmRoutes from './modules/bgm/bgm.controller';
import audioEditRoutes from './modules/audioedit/audioedit.controller';
import bookGeneratorRoutes from './modules/book-generator/book-generator.controller';
import langGraphRoutes from './modules/book-generator/langgraph/controller';
import videoGeneratorRoutes from './modules/video-generator/video-generator.controller';

const app = new Koa();
const router = new Router();

// 中间件
app.use(errorHandler);
app.use(cors({
  origin: '*',
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization'],
}));
app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(process.cwd(), 'uploads', 'materials'),
    keepExtensions: true,
    maxFileSize: 100 * 1024 * 1024, // 100MB
  },
}));

// 静态文件服务 - 音频文件
app.use(mount('/uploads', serve(config.upload.dir));

// 静态文件服务 - 视频文件
app.use(mount('/videos', serve(path.join(process.cwd(), 'public', 'videos')));

// 健康检查
router.get('/health', (ctx) => {
  ctx.body = { code: 0, message: 'ok', data: { status: 'healthy' } };
});

// 注册路由
router.use('/api/auth', authRoutes.routes());
router.use('/api/tts', ttsRoutes.routes());
router.use('/api/audio', audioRoutes.routes());
router.use('/api/member', memberRoutes.routes());
router.use('/api/share', shareRoutes.routes());
router.use('/api/ai', aiRoutes.routes());
router.use('/api/ai-content', aiContentRoutes.routes());
router.use('/api/player', playerRoutes.routes());
router.use('/api/favorites', favoritesRoutes.routes());
router.use('/api/user/preferences', preferencesRoutes.routes());
router.use('/api/search', searchRoutes.routes());
router.use('/api/categories', categoriesRoutes.routes());
router.use('/api/comments', commentsRoutes.routes());
router.use('/api/notifications', notificationsRoutes.routes());
router.use('/api/albums', albumsRoutes.routes());
router.use('/api/templates', templatesRoutes.routes());
router.use('/api/bgm', bgmRoutes.routes());
router.use('/api/audio', audioEditRoutes.routes());
router.use('/api/book-generator', bookGeneratorRoutes.routes());
router.use('/api/book-generator/langgraph', langGraphRoutes.routes());
router.use('/api/video', videoGeneratorRoutes.routes());

app.use(router.routes()).use(router.allowedMethods());

// 启动服务
async function start() {
  try {
    await connectDatabase();
    console.log('✅ MySQL 连接成功');
    
    app.listen(config.port, () => {
      console.log(`🚀 服务启动成功: http://localhost:${config.port}`);
      console.log(`📁 上传目录: ${config.upload.dir}`);
    });
  } catch (error) {
    console.error('❌ 服务启动失败:', error);
    process.exit(1);
  }
}

start();