import 'reflect-metadata'

import { randomUUID } from 'crypto'
import { Brackets, type Repository } from 'typeorm'
import { BrowserWindow } from 'electron'

import {
  StudentProfileEntitySchema,
  type StudentProfileEntity
} from '../entities/StudentProfileEntity'
import { ClassEntitySchema, type ClassEntity } from '../entities/ClassEntity'
import type {
  ChildProfile,
  ClassProfile,
  CommentGenerationProgress,
  GenerateStudentCommentsInput,
  ListStudentProfilesInput,
  LoadStudentDataInput
} from '../types/student'
import { getAppDataSource } from './databaseService'
import { isDataUrlImage, readImageAsDataUrl, storeImageValue } from './imageStorageService'
import { getChatCompletionsUrl, logLargeModelRequest } from './modelService'
import { loadSettings } from './settingsService'

function parseJsonList(value: string): string[] {
  try {
    const parsed = JSON.parse(value)
    return Array.isArray(parsed) ? parsed : []
  } catch {
    return []
  }
}

function stringifyList(items: string[]): string {
  return JSON.stringify(items)
}

function normalizeClassType(type: string): 'cheap' | 'noble' {
  return type === 'noble' ? 'noble' : 'cheap'
}

function parseTeacherNames(value: string): string[] {
  try {
    const parsed = JSON.parse(value)

    if (Array.isArray(parsed)) {
      return parsed
        .filter((item): item is string => typeof item === 'string')
        .map((item) => item.trim())
        .filter(Boolean)
    }
  } catch {
    // Older data may contain a single teacher name instead of a JSON array.
  }

  return value.trim() ? [value.trim()] : []
}

function stringifyTeacherNames(teacherNames: string[]): string {
  return JSON.stringify(
    teacherNames.map((teacherName) => teacherName.trim()).filter((teacherName) => teacherName)
  )
}

async function normalizeStoredClassImages(entity: ClassEntity): Promise<ClassEntity> {
  if (!isDataUrlImage(entity.familyPhoto)) {
    return entity
  }

  return {
    ...entity,
    familyPhoto: await storeImageValue('classes', entity.id, 'familyPhoto', entity.familyPhoto)
  }
}

async function hydrateClassImages(entity: ClassEntity): Promise<ClassEntity> {
  if (!entity.familyPhoto) {
    return entity
  }

  return {
    ...entity,
    familyPhoto: await readImageAsDataUrl(entity.familyPhoto)
  }
}

async function normalizeStoredStudentImages(
  entity: StudentProfileEntity
): Promise<StudentProfileEntity> {
  const [meImage, workImage1, workImage2] = await Promise.all([
    storeImageValue('students', entity.id, 'meImage', entity.meImage),
    storeImageValue('students', entity.id, 'workImage1', entity.workImage1),
    storeImageValue('students', entity.id, 'workImage2', entity.workImage2)
  ])

  return {
    ...entity,
    meImage,
    workImage1,
    workImage2
  }
}

async function hydrateStudentImages(entity: StudentProfileEntity): Promise<StudentProfileEntity> {
  const [meImage, workImage1, workImage2] = await Promise.all([
    readImageAsDataUrl(entity.meImage),
    readImageAsDataUrl(entity.workImage1),
    readImageAsDataUrl(entity.workImage2)
  ])

  return {
    ...entity,
    meImage,
    workImage1,
    workImage2
  }
}

function mapClassEntity(entity: ClassEntity): ClassProfile {
  return {
    id: entity.id,
    name: entity.name,
    type: normalizeClassType(entity.type),
    teacherNames: parseTeacherNames(entity.teacherNames || entity.teacherName || ''),
    familyPhoto: entity.familyPhoto || undefined
  }
}

function mapChildEntity(
  entity: StudentProfileEntity,
  options: { includeImages?: boolean } = {}
): ChildProfile {
  return {
    id: entity.id,
    classId: entity.classId,
    className: entity.className,
    name: entity.name,
    englishName: entity.englishName,
    gender: entity.gender,
    birthday: entity.birthday,
    zodiac: entity.zodiac,
    friends: parseJsonList(entity.friends),
    hobbies: parseJsonList(entity.hobbies),
    favoriteGames: parseJsonList(entity.favoriteGames),
    favoriteFoods: parseJsonList(entity.favoriteFoods),
    traits: entity.traits,
    comment: entity.comment ?? '',
    commentGeneratedAt: entity.commentGeneratedAt ?? '',
    reportGenerated: Boolean(entity.reportGenerated),
    meImage: options.includeImages === false ? '' : (entity.meImage ?? ''),
    workImage1: options.includeImages === false ? '' : (entity.workImage1 ?? ''),
    workImage2: options.includeImages === false ? '' : (entity.workImage2 ?? ''),
    importedAt: entity.importedAt
  }
}

async function mapClassProfile(profile: ClassProfile): Promise<ClassEntity> {
  return {
    id: profile.id,
    name: profile.name,
    type: profile.type,
    teacherName: (profile.teacherNames ?? []).join(' ') || null,
    teacherNames: stringifyTeacherNames(profile.teacherNames ?? []),
    familyPhoto:
      (await storeImageValue('classes', profile.id, 'familyPhoto', profile.familyPhoto)) || null
  }
}

async function mapChildProfile(
  profile: ChildProfile,
  classItem?: ClassProfile
): Promise<StudentProfileEntity> {
  return normalizeStoredStudentImages({
    id: profile.id,
    classId: classItem?.id ?? profile.classId,
    className: classItem?.name ?? profile.className,
    name: profile.name,
    englishName: profile.englishName,
    gender: profile.gender,
    birthday: profile.birthday,
    zodiac: profile.zodiac,
    friends: stringifyList(profile.friends),
    hobbies: stringifyList(profile.hobbies),
    favoriteGames: stringifyList(profile.favoriteGames),
    favoriteFoods: stringifyList(profile.favoriteFoods),
    traits: profile.traits,
    comment: profile.comment ?? '',
    commentGeneratedAt: profile.commentGeneratedAt ?? '',
    reportGenerated: profile.reportGenerated ?? false,
    meImage: profile.meImage ?? '',
    workImage1: profile.workImage1 ?? '',
    workImage2: profile.workImage2 ?? '',
    importedAt: profile.importedAt
  })
}

function buildStudentCommentPrompt(profile: ChildProfile): string {
  return [
    '请为这名幼儿生成一段成长报告评语。',
    '要求：语气温暖、具体、积极，适合幼儿园成长报告；不要编造资料里没有的姓名、日期或家庭信息；长度控制在 120 到 180 字。',
    '',
    `姓名：${profile.name || '未填写'}`,
    `英文名：${profile.englishName || '未填写'}`,
    `班级：${profile.className || '未分班'}`,
    `性别：${profile.gender || '未填写'}`,
    `生日：${profile.birthday || '未填写'}`,
    `属相：${profile.zodiac || '未填写'}`,
    `好朋友：${profile.friends.length > 0 ? profile.friends.join('、') : '未填写'}`,
    `爱好：${profile.hobbies.length > 0 ? profile.hobbies.join('、') : '未填写'}`,
    `喜欢的游戏：${profile.favoriteGames.length > 0 ? profile.favoriteGames.join('、') : '未填写'}`,
    `喜欢吃的食物：${profile.favoriteFoods.length > 0 ? profile.favoriteFoods.join('、') : '未填写'}`,
    `表现特征：${profile.traits || '未填写'}`
  ].join('\n')
}

function getStudentDisplayName(profile: ChildProfile | StudentProfileEntity): string {
  return profile.name || profile.englishName || '未命名学生'
}

function sendCommentProgress(progress: CommentGenerationProgress): void {
  for (const window of BrowserWindow.getAllWindows()) {
    window.webContents.send('comments:generation-progress', progress)
  }
}

async function getRepositories(): Promise<{
  classRepository: Repository<ClassEntity>
  childRepository: Repository<StudentProfileEntity>
}> {
  const source = await getAppDataSource()

  return {
    classRepository: source.getRepository<ClassEntity>(ClassEntitySchema),
    childRepository: source.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
  }
}

export async function loadStudentData(input: LoadStudentDataInput = {}): Promise<{
  classes: ClassProfile[]
  profiles: ChildProfile[]
}> {
  const includeProfiles = input.includeProfiles ?? true
  const includeImages = input.includeImages ?? true
  const { classRepository, childRepository } = await getRepositories()
  const classes = await classRepository.find({
    order: {
      id: 'ASC'
    }
  })
  const profiles = includeProfiles
    ? await childRepository.find({
        order: {
          id: 'ASC'
        }
      })
    : []

  const normalizedClasses = await Promise.all(classes.map(normalizeStoredClassImages))
  const normalizedProfiles = includeImages
    ? await Promise.all(profiles.map(normalizeStoredStudentImages))
    : profiles
  const hydratedProfiles = includeImages
    ? await Promise.all(normalizedProfiles.map(hydrateStudentImages))
    : normalizedProfiles

  for (const normalizedClass of normalizedClasses) {
    const originalClass = classes.find((classItem) => classItem.id === normalizedClass.id)

    if (originalClass && normalizedClass.familyPhoto !== originalClass.familyPhoto) {
      await classRepository.save(normalizedClass)
    }
  }

  if (includeImages) {
    for (const normalizedProfile of normalizedProfiles) {
      const originalProfile = profiles.find((profile) => profile.id === normalizedProfile.id)

      if (
        originalProfile &&
        (normalizedProfile.meImage !== originalProfile.meImage ||
          normalizedProfile.workImage1 !== originalProfile.workImage1 ||
          normalizedProfile.workImage2 !== originalProfile.workImage2)
      ) {
        await childRepository.save(normalizedProfile)
      }
    }
  }

  const hydratedClasses = includeImages
    ? await Promise.all(normalizedClasses.map(hydrateClassImages))
    : normalizedClasses

  return {
    classes: hydratedClasses.map(mapClassEntity),
    profiles: hydratedProfiles.map((profile) => mapChildEntity(profile, { includeImages }))
  }
}

export async function listStudentProfiles(input: ListStudentProfilesInput): Promise<{
  profiles: ChildProfile[]
  total: number
  page: number
  pageSize: number
}> {
  const pageSize = Math.min(Math.max(Number(input.pageSize) || 10, 1), 100)
  const page = Math.max(Number(input.page) || 1, 1)
  const keyword = input.query?.trim()
  const source = await getAppDataSource()
  const queryBuilder = source
    .getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
    .createQueryBuilder('profile')
    .orderBy('profile.className', 'ASC')
    .addOrderBy('profile.name', 'ASC')
    .addOrderBy('profile.id', 'ASC')

  if (input.classId && input.classId !== 'all') {
    queryBuilder.andWhere('profile.classId = :classId', { classId: input.classId })
  }

  if (keyword) {
    queryBuilder.andWhere(
      new Brackets((builder) => {
        builder
          .where('profile.className LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.name LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.englishName LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.gender LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.birthday LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.zodiac LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.friends LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.hobbies LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.favoriteGames LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.favoriteFoods LIKE :keyword', { keyword: `%${keyword}%` })
          .orWhere('profile.traits LIKE :keyword', { keyword: `%${keyword}%` })
      })
    )
  }

  const [profiles, total] = await queryBuilder
    .skip((page - 1) * pageSize)
    .take(pageSize)
    .getManyAndCount()

  return {
    profiles: profiles.map((profile) => mapChildEntity(profile, { includeImages: false })),
    total,
    page,
    pageSize
  }
}

export async function getStudentProfile(profileId: string): Promise<ChildProfile> {
  const source = await getAppDataSource()
  const repository = source.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
  const profile = await repository.findOneBy({ id: profileId })

  if (!profile) {
    throw new Error('学生信息不存在')
  }

  const normalizedProfile = await normalizeStoredStudentImages(profile)

  if (
    normalizedProfile.meImage !== profile.meImage ||
    normalizedProfile.workImage1 !== profile.workImage1 ||
    normalizedProfile.workImage2 !== profile.workImage2
  ) {
    await repository.save(normalizedProfile)
  }

  return mapChildEntity(await hydrateStudentImages(normalizedProfile))
}

export async function updateStudentProfile(profile: ChildProfile): Promise<ChildProfile> {
  const source = await getAppDataSource()
  const repository = source.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
  const existingProfile = await repository.findOneBy({ id: profile.id })

  if (!existingProfile) {
    throw new Error('学生信息不存在')
  }

  const nextProfile: ChildProfile = {
    ...profile,
    comment: profile.comment ?? '',
    commentGeneratedAt: profile.commentGeneratedAt ?? existingProfile.commentGeneratedAt ?? ''
  }

  const storedProfile = await mapChildProfile(nextProfile)
  await repository.save(storedProfile)
  return mapChildEntity(await hydrateStudentImages(storedProfile))
}

async function generateStudentCommentForEntity(
  entity: StudentProfileEntity,
  repository: Repository<StudentProfileEntity>
): Promise<ChildProfile> {
  const profile = mapChildEntity(entity)
  const settings = await loadSettings()

  if (!settings.ok) {
    throw new Error(settings.message)
  }

  const modelConfig = settings.modelConfig

  if (!modelConfig?.baseUrl || !modelConfig.apiKey || !modelConfig.model) {
    throw new Error('请先在设置中配置模型接口、API Key 和模型')
  }

  const requestUrl = getChatCompletionsUrl(modelConfig.baseUrl)
  const userPrompt = buildStudentCommentPrompt(profile)

  logLargeModelRequest({
    label: '生成学生评语',
    url: requestUrl,
    apiKey: modelConfig.apiKey,
    model: modelConfig.model,
    prompt: userPrompt
  })

  const response = await fetch(requestUrl, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${modelConfig.apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: modelConfig.model,
      temperature: Number(modelConfig.temperature || 0.7),
      max_tokens: Number(modelConfig.maxTokens || 512),
      messages: [
        {
          role: 'system',
          content:
            modelConfig.systemPrompt ||
            '你是一名幼儿园老师，擅长撰写真诚、具体、积极的成长报告评语。'
        },
        {
          role: 'user',
          content: userPrompt
        }
      ]
    })
  })

  if (!response.ok) {
    throw new Error(`生成评语失败：HTTP ${response.status}`)
  }

  const result = (await response.json()) as {
    choices?: Array<{ message?: { content?: unknown } }>
  }
  const comment = result.choices?.[0]?.message?.content

  if (typeof comment !== 'string' || !comment.trim()) {
    throw new Error('模型没有返回可用评语')
  }

  const nextProfile: ChildProfile = {
    ...profile,
    comment: comment.trim(),
    commentGeneratedAt: new Date().toLocaleString('zh-CN', { hour12: false })
  }

  const storedProfile = await mapChildProfile(nextProfile)
  await repository.save(storedProfile)
  return mapChildEntity(await hydrateStudentImages(storedProfile))
}

export async function generateStudentComment(profileId: string): Promise<ChildProfile> {
  const source = await getAppDataSource()
  const repository = source.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
  const entity = await repository.findOneBy({ id: profileId })

  if (!entity) {
    throw new Error('学生信息不存在')
  }

  return generateStudentCommentForEntity(entity, repository)
}

export async function generateStudentComments(input: GenerateStudentCommentsInput): Promise<{
  profiles: ChildProfile[]
  skipped: Array<{ studentName: string; reason: string }>
}> {
  const source = await getAppDataSource()
  const repository = source.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
  const selectedIds = new Set(input.profileIds ?? [])
  const allProfiles = await repository.find({
    where: input.classId ? { classId: input.classId } : undefined,
    order: {
      name: 'ASC',
      id: 'ASC'
    }
  })
  const targetProfiles =
    selectedIds.size > 0
      ? allProfiles.filter((profile) => selectedIds.has(profile.id))
      : allProfiles

  if (targetProfiles.length === 0) {
    throw new Error('没有可生成评语的学生')
  }

  const batchId = randomUUID()
  const className = targetProfiles[0]?.className
  const profiles: ChildProfile[] = []
  const skipped: Array<{ studentName: string; reason: string }> = []

  sendCommentProgress({
    batchId,
    status: 'started',
    classId: input.classId,
    className,
    current: 0,
    total: targetProfiles.length
  })

  for (const [profileIndex, profile] of targetProfiles.entries()) {
    const studentName = getStudentDisplayName(profile)

    try {
      sendCommentProgress({
        batchId,
        status: 'student-started',
        classId: profile.classId,
        className: profile.className,
        studentId: profile.id,
        studentName,
        current: profileIndex + 1,
        total: targetProfiles.length
      })

      const nextProfile = await generateStudentCommentForEntity(profile, repository)
      profiles.push(nextProfile)

      sendCommentProgress({
        batchId,
        status: 'student-finished',
        classId: profile.classId,
        className: profile.className,
        studentId: profile.id,
        studentName,
        current: profileIndex + 1,
        total: targetProfiles.length,
        profile: nextProfile
      })
    } catch (error) {
      const reason = error instanceof Error ? error.message : '生成失败'

      skipped.push({
        studentName,
        reason
      })
      sendCommentProgress({
        batchId,
        status: 'student-failed',
        classId: profile.classId,
        className: profile.className,
        studentId: profile.id,
        studentName,
        current: profileIndex + 1,
        total: targetProfiles.length,
        error: reason
      })
    }
  }

  sendCommentProgress({
    batchId,
    status: 'finished',
    classId: input.classId,
    className,
    current: targetProfiles.length,
    total: targetProfiles.length
  })

  return { profiles, skipped }
}

export async function saveClasses(classes: ClassProfile[]): Promise<void> {
  const source = await getAppDataSource()

  await source.transaction(async (manager) => {
    const classRepository = manager.getRepository<ClassEntity>(ClassEntitySchema)
    const childRepository = manager.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
    const nextClassIds = new Set(classes.map((classItem) => classItem.id))
    const existingClasses = await classRepository.find()

    for (const classItem of existingClasses) {
      if (!nextClassIds.has(classItem.id)) {
        await childRepository.delete({ classId: classItem.id })
        await classRepository.delete({ id: classItem.id })
      }
    }

    for (const classItem of classes) {
      await classRepository.save(await mapClassProfile(classItem))
      await childRepository.update({ classId: classItem.id }, { className: classItem.name })
    }
  })
}

export async function migrateLocalStudentData(
  classes: ClassProfile[],
  profiles: ChildProfile[]
): Promise<void> {
  const source = await getAppDataSource()

  await source.transaction(async (manager) => {
    const classRepository = manager.getRepository<ClassEntity>(ClassEntitySchema)
    const childRepository = manager.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
    const classCount = await classRepository.count()
    const profileCount = await childRepository.count()

    if (classCount > 0 || profileCount > 0) {
      return
    }

    await classRepository.save(await Promise.all(classes.map(mapClassProfile)))
    await childRepository.save(
      await Promise.all(profiles.map((profile) => mapChildProfile(profile)))
    )
  })
}

export async function replaceProfilesForClass(
  classItem: ClassProfile,
  profiles: ChildProfile[]
): Promise<void> {
  const source = await getAppDataSource()

  await source.transaction(async (manager) => {
    const childRepository = manager.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)

    await childRepository.delete({ classId: classItem.id })
    await childRepository.save(
      await Promise.all(profiles.map((profile) => mapChildProfile(profile, classItem)))
    )
  })
}

export async function deleteClassWithProfiles(classId: string): Promise<void> {
  const source = await getAppDataSource()

  await source.transaction(async (manager) => {
    await manager
      .getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
      .delete({ classId })
    await manager.getRepository<ClassEntity>(ClassEntitySchema).delete({ id: classId })
  })
}

export async function deleteStudentProfile(profileId: string): Promise<void> {
  const source = await getAppDataSource()
  const result = await source
    .getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
    .delete({ id: profileId })

  if (!result.affected) {
    throw new Error('学生信息不存在')
  }
}

export async function migrateStoredImagesToFiles(): Promise<void> {
  const source = await getAppDataSource()
  const classRepository = source.getRepository<ClassEntity>(ClassEntitySchema)
  const childRepository = source.getRepository<StudentProfileEntity>(StudentProfileEntitySchema)
  const classes = await classRepository.find()
  const profiles = await childRepository.find()

  for (const classItem of classes) {
    const nextClassItem = await normalizeStoredClassImages(classItem)

    if (nextClassItem.familyPhoto !== classItem.familyPhoto) {
      await classRepository.save(nextClassItem)
    }
  }

  for (const profile of profiles) {
    const nextProfile = await normalizeStoredStudentImages(profile)

    if (
      nextProfile.meImage !== profile.meImage ||
      nextProfile.workImage1 !== profile.workImage1 ||
      nextProfile.workImage2 !== profile.workImage2
    ) {
      await childRepository.save(nextProfile)
    }
  }
}
