import { NextResponse } from 'next/server'
import { exec } from 'child_process'
import { promisify } from 'util'

const execAsync = promisify(exec)

export async function POST() {
  try {
    // 执行同步脚本
    const { stdout, stderr } = await execAsync('node scripts/sync-book-content.js')
    
    if (stderr) {
      console.error('Sync stderr:', stderr)
    }
    
    console.log('Sync stdout:', stdout)
    
    return NextResponse.json({
      success: true,
      message: '章节同步成功',
      output: stdout
    })
  } catch (error) {
    console.error('Sync error:', error)
    return NextResponse.json(
      {
        success: false,
        error: '同步失败',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}

// 获取同步状态
export async function GET() {
  try {
    const fs = require('fs')
    const path = require('path')
    const dataPath = path.join(process.cwd(), 'public/book-chapters.json')
    
    if (!fs.existsSync(dataPath)) {
      return NextResponse.json({
        success: false,
        synced: false,
        message: '章节数据未生成'
      })
    }
    
    const stats = fs.statSync(dataPath)
    const fileContent = fs.readFileSync(dataPath, 'utf-8')
    const chapters = JSON.parse(fileContent)
    
    return NextResponse.json({
      success: true,
      synced: true,
      totalChapters: chapters.length,
      lastSyncTime: stats.mtime,
      message: '章节数据已同步'
    })
  } catch (error) {
    return NextResponse.json(
      {
        success: false,
        synced: false,
        error: '获取状态失败'
      },
      { status: 500 }
    )
  }
}
