#!/usr/bin/env tsx
/**
 * Convert CSV export to JSON format for infrastructure documentation
 * Usage: tsx scripts/infrastructure/convert-csv-to-json.ts
 */

import * as fs from 'fs'
import * as path from 'path'

const PROJECT_ROOT = path.resolve(__dirname, '../..')
const DATA_DIR = path.join(PROJECT_ROOT, 'docs/infrastructure/data')

interface Country {
  name: string
  region: 'Africa (Sub-Saharan)' | 'Middle East & North Africa' | 'Americas' | 'Asia-Pacific' | 'Europe'
  relationshipType: 'Full Diplomatic Relations' | 'Official (Non-Diplomatic)' | 'Ambassador Level' | 'Full Diplomatic Relations (Special Mission)'
  priority: 'Critical' | 'High' | 'Medium' | 'Low'
  cloudflareCoverage: boolean
  networkInfrastructurePriority: string
  notes?: string
  coordinates?: { lat: number; lng: number }
}

// Country coordinates (approximate, can be enhanced with geocoding)
const COUNTRY_COORDINATES: Record<string, { lat: number; lng: number }> = {
  'Italy': { lat: 41.9028, lng: 12.4964 },
  'Germany': { lat: 51.1657, lng: 10.4515 },
  'France': { lat: 46.2276, lng: 2.2137 },
  'Spain': { lat: 40.4637, lng: -3.7492 },
  'Brazil': { lat: -14.2350, lng: -51.9253 },
  'Argentina': { lat: -38.4161, lng: -63.6167 },
  'Philippines': { lat: 12.8797, lng: 121.7740 },
  'Kenya': { lat: -0.0236, lng: 37.9062 },
  'Ethiopia': { lat: 9.1450, lng: 38.7667 },
  'Lebanon': { lat: 33.8547, lng: 35.8623 },
  'Holy See (Vatican City)': { lat: 41.9029, lng: 12.4534 },
}

function parseCSV(csvContent: string): Country[] {
  const lines = csvContent.trim().split('\n')
  const headers = lines[0].split(',').map(h => h.trim())
  
  return lines.slice(1).map(line => {
    const values = line.split(',').map(v => v.trim())
    const country: Country = {
      name: values[0],
      region: values[1] as Country['region'],
      relationshipType: values[2] as Country['relationshipType'],
      priority: values[3] as Country['priority'],
      cloudflareCoverage: values[4] === 'Yes',
      networkInfrastructurePriority: values[5],
      notes: values[6] || undefined,
      coordinates: COUNTRY_COORDINATES[values[0]] || undefined,
    }
    return country
  })
}

function main() {
  // Find the most recent CSV file
  const files = fs.readdirSync(DATA_DIR)
    .filter(f => f.startsWith('smom_countries_full_') && f.endsWith('.csv'))
    .sort()
    .reverse()

  if (files.length === 0) {
    console.error('No CSV files found. Please run export-smom-countries.sh first.')
    process.exit(1)
  }

  const csvFile = path.join(DATA_DIR, files[0])
  console.log(`Reading CSV file: ${csvFile}`)
  
  const csvContent = fs.readFileSync(csvFile, 'utf-8')
  const countries = parseCSV(csvContent)

  // Write JSON file
  const jsonFile = path.join(DATA_DIR, 'smom_countries.json')
  fs.writeFileSync(jsonFile, JSON.stringify(countries, null, 2))
  console.log(`✓ Created ${jsonFile} with ${countries.length} countries`)

  // Create summary statistics
  const summary = {
    total: countries.length,
    byRegion: countries.reduce((acc, c) => {
      acc[c.region] = (acc[c.region] || 0) + 1
      return acc
    }, {} as Record<string, number>),
    byPriority: countries.reduce((acc, c) => {
      acc[c.priority] = (acc[c.priority] || 0) + 1
      return acc
    }, {} as Record<string, number>),
    byRelationshipType: countries.reduce((acc, c) => {
      acc[c.relationshipType] = (acc[c.relationshipType] || 0) + 1
      return acc
    }, {} as Record<string, number>),
    lastUpdated: new Date().toISOString(),
  }

  const summaryFile = path.join(DATA_DIR, 'smom_countries_summary.json')
  fs.writeFileSync(summaryFile, JSON.stringify(summary, null, 2))
  console.log(`✓ Created ${summaryFile}`)
}

if (require.main === module) {
  main()
}

