import { Controller, Post, Body, HttpException, HttpStatus, UseGuards } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { AnalyzeService } from './analyze.service'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
import { UserService } from '../user/user.service'
import { QuotaService } from '../user/quota.service'
import { ResumeService } from '../resume/resume.service'
import { BenchmarkService, PositionBenchmark } from '../progress/benchmark.service'
import { Progress, ProgressDocument } from '../schemas/progress.schema'

@Controller('analyze')
export class AnalyzeController {
  constructor(
    private analyzeService: AnalyzeService,
    private userService: UserService,
    private quotaService: QuotaService,
    private resumeService: ResumeService,
    private benchmarkService: BenchmarkService,
    @InjectModel(Progress.name) private progressModel: Model<ProgressDocument>,
  ) {}

  @UseGuards(JwtAuthGuard)
  @Post('diagnosis')
  async diagnosis(@Body('content') content: string, @CurrentUser('userId') userId: string) {
    await this.checkAnalyzeLimit(userId)
    return this.analyzeService.diagnose(content)
  }

  @UseGuards(JwtAuthGuard)
  @Post('optimize')
  async optimize(
    @Body('content') content: string,
    @Body('direction') direction: string,
    @Body('resumeId') resumeId: string,
    @CurrentUser('userId') userId: string,
  ) {
    await this.checkAnalyzeLimit(userId)
    const result = await this.analyzeService.optimize(content, direction)

    if (resumeId && result.optimized && result.optimized !== content) {
      const updated = await this.resumeService.updateAfterOptimize(resumeId, userId, result.optimized, direction)
      return { ...result, newVersion: updated }
    }

    return result
  }

  /** 技能缺口分析：将用户四维分数与目标岗位基准对比 */
  @UseGuards(JwtAuthGuard)
  @Post('skills-gap')
  async skillsGap(@CurrentUser('userId') userId: string, @Body('targetPosition') targetPosition?: string) {
    const progress = await this.progressModel.findOne({ userId }).exec()
    if (!progress || progress.completedInterviews === 0) {
      throw new HttpException('暂无面试数据，请先完成至少一次模拟面试', HttpStatus.BAD_REQUEST)
    }

    const userDims = {
      logic: progress.avgLogic || 0,
      expression: progress.avgExpression || 0,
      professionalism: progress.avgProfessionalism || 0,
      stability: progress.avgStability || 0,
    }

    const lastPosition = targetPosition || (progress.recentScores.length > 0 ? progress.recentScores[progress.recentScores.length - 1].position : '')
    const bmData = await this.benchmarkService.getBenchmark(lastPosition)
    const bm = 'p50' in bmData ? (bmData as PositionBenchmark).p50 : { logic: 70, expression: 70, professionalism: 70, stability: 70 }
    const benchmark = { logic: bm.logic, expression: bm.expression, professionalism: bm.professionalism, stability: bm.stability }

    // Compute percentile rank
    const percData = await this.benchmarkService.getUserPercentile(userId, lastPosition)

    const gaps: Array<{ dimension: string; currentScore: number; targetScore: number; gap: number; level: string }> = []
    const dimLabels: Record<string, string> = {
      logic: '逻辑思维',
      expression: '表达能力',
      professionalism: '专业度',
      stability: '情绪稳定性',
    }

    for (const [key, label] of Object.entries(dimLabels)) {
      const score = userDims[key as keyof typeof userDims]
      const target = benchmark[key as keyof typeof benchmark]
      const gap = target - score
      if (gap > 0) {
        gaps.push({
          dimension: label,
          currentScore: score,
          targetScore: target,
          gap: Math.round(gap),
          level: gap > 15 ? '严重不足' : gap > 5 ? '需提升' : '接近基准',
        })
      }
    }

    // 生成学习建议
    const suggestions = gaps.map(g => {
      const tips: Record<string, string> = {
        '逻辑思维': '多用 STAR 法则组织回答，练习"结论先行+论据支撑"结构',
        '表达能力': '录音回听自己的回答，控制语速，减少语气词，精炼表达',
        '专业度': '补充岗位相关基础知识，阅读面经中的专业问题',
        '情绪稳定性': '进行更多模拟面试练习，适应面试压力环境',
      }
      return { dimension: g.dimension, tip: tips[g.dimension] || '持续练习提升' }
    })

    const totalGap = gaps.reduce((s, g) => s + g.gap, 0)

    return {
      dimensions: userDims,
      benchmark,
      percentile: percData?.percentile || null,
      gaps,
      suggestions,
      totalGap,
      assessment: totalGap > 30 ? '整体与目标岗位存在差距，建议针对性提升' :
                  totalGap > 10 ? '接近目标水平，针对薄弱项提升即可' :
                  '已达到或超过目标岗位基准，继续保持',
      targetPosition: lastPosition,
    }
  }

  private async checkAnalyzeLimit(userId: string) {
    await this.quotaService.checkAndDeductOptimize(userId)
  }
}
