import { readdirSync, statSync, readFileSync, writeFileSync, existsSync } from 'fs'
import { join, basename } from 'path'
import { fileURLToPath } from 'url'

const __dirname = fileURLToPath(new URL('.', import.meta.url))
const CASE_DIR = join(__dirname, '../case-source')
const OUTPUT = join(__dirname, '../src/data/cases.ts')

const IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp']

// Known slug mappings for existing cases. New cases auto-generate slug as "case-{sort}".
// Add custom slugs here when adding new cases for friendlier URLs.
const slugMap = {
  '10-景德镇陶川溪凯悦酒店': 'jingdezhen-taechuanxi-hyatt',
  '20-武汉茶林驿站': 'wuhan-chalin-station',
  '30-拉萨阿诺康巴酒店': 'lhasa-anuokangba-hotel',
  '40-温州嘉野酒店': 'wenzhou-jiaye-hotel',
  '50-美林别墅室内外': 'meilin-villa',
  '60-莫干山折折院': 'moganshan-zhezhe-courtyard',
  '70-景德镇建筑': 'jingdezhen-architecture',
}

function isImage(filename) {
  return IMAGE_EXTENSIONS.some((ext) => filename.toLowerCase().endsWith(ext))
}

function naturalSort(a, b) {
  return a.localeCompare(b, 'zh-CN-u-co-pinyin', { numeric: true })
}

function getImagesInDir(dirPath, urlPrefix) {
  try {
    const files = readdirSync(dirPath)
      .filter((f) => !f.startsWith('.') && isImage(f) && statSync(join(dirPath, f)).isFile())
      .sort(naturalSort)
    return files.map((f) => `${urlPrefix}/${f}`)
  } catch {
    return []
  }
}

function generateCases() {
  const folders = readdirSync(CASE_DIR)
    .filter((f) => {
      const fullPath = join(CASE_DIR, f)
      return statSync(fullPath).isDirectory() && !f.startsWith('.')
    })
    .sort((a, b) => parseInt(a) - parseInt(b))

  const cases = []

  for (const folder of folders) {
    const folderPath = join(CASE_DIR, folder)
    const urlPrefix = `/case/${folder}`

    const dashIdx = folder.indexOf('-')
    const sortNum = parseInt(folder.slice(0, dashIdx), 10)
    const title = folder.slice(dashIdx + 1)
    // Use custom slug if mapped, otherwise auto-generate from sort number
    const slug = slugMap[folder] || `case-${sortNum}`

    // Read description txt (GBK → UTF-8)
    const txtPath = join(folderPath, '文字信息.txt')
    let description
    if (existsSync(txtPath)) {
      try {
        const raw = readFileSync(txtPath)
        // Decode GBK manually using TextDecoder
        const decoder = new TextDecoder('gbk')
        description = decoder.decode(raw).trim()
      } catch {
        try {
          description = readFileSync(txtPath, 'utf-8').trim()
        } catch { /* skip */ }
      }
    }

    // Detect sub-folders
    const entries = readdirSync(folderPath)
    const subFolders = entries.filter((e) => {
      const fullPath = join(folderPath, e)
      return statSync(fullPath).isDirectory() && !e.startsWith('.')
    }).sort(naturalSort)

    // Get root-level images
    const rootImages = getImagesInDir(folderPath, urlPrefix)

    let categories = []
    let coverImage

    if (subFolders.length > 0 && rootImages.length === 0) {
      // Only sub-folders, no root images
      categories = subFolders.map((sub) => ({
        name: sub,
        images: getImagesInDir(join(folderPath, sub), `${urlPrefix}/${sub}`),
      }))
      coverImage = categories[0]?.images[0] || ''
    } else if (subFolders.length > 0 && rootImages.length > 0) {
      // Both root images and sub-folders (e.g. case 30)
      // Root images treated as a category
      categories = [
        { name: '室外', images: rootImages },
        ...subFolders.map((sub) => ({
          name: sub,
          images: getImagesInDir(join(folderPath, sub), `${urlPrefix}/${sub}`),
        })),
      ]
      coverImage = categories[0]?.images[0] || ''
    } else {
      // No sub-folders - single category
      categories = [{ name: '', images: rootImages }]
      coverImage = rootImages[0] || ''
    }

    cases.push({ slug, title, sort: sortNum, description, coverImage, categories })
  }

  return cases
}

const cases = generateCases()

const output = `// Auto-generated by scripts/generate-cases.mjs
// Do not edit manually - run "node scripts/generate-cases.mjs" to regenerate

import type { CaseData } from '@/types'

export const cases: CaseData[] = ${JSON.stringify(cases, null, 2)}
`

writeFileSync(OUTPUT, output, 'utf-8')
console.log(`Generated ${cases.length} cases to ${OUTPUT}`)
cases.forEach((c) => console.log(`  ${c.sort}-${c.title}: ${c.categories.length} categories, ${c.categories.reduce((sum, cat) => sum + cat.images.length, 0)} images`))
