#!/usr/bin/env node

const fs = require('fs')
const path = require('path')

// Paths
const peopleComponentsDir = path.join(__dirname, '../src/components/people')
const peopleDataFile = path.join(__dirname, '../src/lib/peopleData.ts')

// Function to get all People_*.tsx files
function getPeopleComponents() {
  if (!fs.existsSync(peopleComponentsDir)) {
    console.log('People components directory not found')
    return []
  }

  const files = fs.readdirSync(peopleComponentsDir)
  return files
    .filter(file => file.startsWith('People_') && file.endsWith('.tsx'))
    .map(file => {
      const componentName = file.replace('.tsx', '')
      const importName = componentName.toLowerCase().replace('people_', '')
      return {
        fileName: file,
        componentName,
        importName,
        importPath: `@/components/people/${componentName}`
      }
    })
}

// Function to generate the peopleData.ts content
function sortComponents(components) {
  const manualOrder = [
    'People_Kristof_de_Spiegeleer',
    'People_Adnan_Fateryji',
    'People_Chris_Camponovo',
    'People_Florian_Fournier',
    'People_Alexandre_Hannelas',
    'People_Gregory_Flipo',
    'People_Hugo_Mathecowitsch',
    'People_Jan_De_Landtsheer',
    'People_Karoline_Zizka',
    'People_Malte_Geierhos',
    'People_Marion_Ravarino',
    'People_Michel_Coucke',
    'People_Nousrath_Bhugeloo',
    'People_Owen_Kemp',
    'People_Sacha_Obeegadoo',
    'People_Sam_Taggart',
    'People_Sasha_Astiadi',
    'People_Timur_Gordon',
    'People_Emre_Koc',
    'People_Vianney_Spriet'
  ]

  return components
    .map(component => {
      const orderIndex = manualOrder.indexOf(component.componentName)
      return {
        ...component,
        orderIndex: orderIndex === -1 ? Number.MAX_SAFE_INTEGER : orderIndex
      }
    })
    .sort((a, b) => {
      if (a.orderIndex !== b.orderIndex) {
        return a.orderIndex - b.orderIndex
      }
      // Fallback to alphabetical ordering for any components not listed
      return a.componentName.localeCompare(b.componentName)
    })
}

function generatePeopleDataContent(components) {
  const sortedComponents = sortComponents(components)

  const imports = sortedComponents
    .map(comp => `import { data as ${comp.importName}Data } from '${comp.importPath}'`)
    .join('\n')

  const dynamicImports = sortedComponents
    .map(comp => `    () => import('${comp.importPath}'),`)
    .join('\n')

  const syncDataPush = sortedComponents
    .map(comp => `
  try {
    allPeopleData.push(...${comp.importName}Data)
  } catch (error) {
    console.error('Error loading ${comp.importName} data:', error)
  }`)
    .join('\n')

  return `// This file is auto-generated by scripts/generate-people-data.js
// When new people components are added, run: npm run generate-people-data

export interface PersonData {
  name: string
  role: string
  imageUrl: string
  xUrl: string
  linkedinUrl: string
  tags?: string[]
  note?: string
}

// Function to dynamically get all people data
export async function getAllPeopleData(): Promise<PersonData[]> {
  const allPeopleData: PersonData[] = []

  // Auto-generated list of all people components
  const peopleComponents = [
${dynamicImports}
  ]

  for (const importComponent of peopleComponents) {
    try {
      const module = await importComponent()
      if (module.data && Array.isArray(module.data)) {
        allPeopleData.push(...module.data)
      }
    } catch (error) {
      console.error('Error loading people data:', error)
    }
  }

  return allPeopleData
}

// Synchronous version using static imports for immediate data access
${imports}

export function getAllPeopleDataSync(): PersonData[] {
  const allPeopleData: PersonData[] = []
${syncDataPush}

  return allPeopleData
}
`
}

// Main function
function main() {
  console.log('🔍 Scanning for people components...')
  
  const components = getPeopleComponents()
  
  if (components.length === 0) {
    console.log('❌ No people components found')
    return
  }

  console.log(`✅ Found ${components.length} people component(s):`)
  components.forEach(comp => {
    console.log(`   - ${comp.componentName}`)
  })

  console.log('📝 Generating peopleData.ts...')
  
  const content = generatePeopleDataContent(components)
  fs.writeFileSync(peopleDataFile, content, 'utf8')
  
  console.log('✅ Successfully updated src/lib/peopleData.ts')
  console.log('\n🎉 All people components will now automatically appear on the people page!')
}

// Run the script
if (require.main === module) {
  main()
}

module.exports = { main, getPeopleComponents, generatePeopleDataContent }
