/**
 * Generate Activity Images Script
 *
 * Generates images for all extracurriculars and occupations using the AI image service.
 * Run with: npx tsx scripts/generate-activity-images.ts
 */

import { config } from '../src/config.js';
import { imageGenerator, COZY_CARTOON_STYLE } from '../src/services/images/image_generator.js';

// Activity definitions with prompts optimized for image generation
const EXTRACURRICULAR_PROMPTS: Record<string, string> = {
  'Choir': 'children singing in a school choir, music room with piano, happy students performing',
  'Musical Theater': 'kids performing in a school musical theater play, stage with colorful curtains, costumes',
  'Debate Team': 'students at a debate podium in school, confident speakers, academic setting',
  'Writing Club': 'students writing together at a table, notebooks and pens, cozy library setting',
  'Robotics Team': 'kids building robots in a school lab, electronics and tools, excited students',
  'Baseball': 'kids playing baseball on a sunny field, bat and glove, team uniforms',
  'Basketball': 'children playing basketball in a gym, shooting hoops, team spirit',
  'Soccer': 'kids playing soccer on a green field, kicking ball, team jerseys',
  'Football': 'children playing american football, helmets and pads, team practice',
  'Piano': 'child learning piano with teacher, grand piano, music sheets',
  'Guitar': 'kid learning acoustic guitar, music lesson, practice room',
  'Violin': 'child practicing violin, orchestra setting, elegant music room',
  'Drums': 'kid playing drum set, music studio, energetic drumming',
  'Dance Class': 'children in dance class, ballet studio, graceful movements',
};

const OCCUPATION_PROMPTS: Record<string, string> = {
  'Software Engineer': 'software developer working at computer, modern tech office, coding on multiple screens',
  'Registered Nurse': 'nurse caring for patient in hospital, medical equipment, compassionate care',
  'Elementary School Teacher': 'teacher at classroom blackboard, colorful elementary classroom, teaching children',
  'Police Officer': 'friendly police officer on duty, patrol car, protecting community',
  'Accountant': 'accountant at desk with documents, corporate office, financial reports',
  'Chef': 'chef cooking in restaurant kitchen, pots and pans, delicious food preparation',
  'Lawyer': 'lawyer in law office with books, legal documents, professional setting',
  'Automotive Mechanic': 'mechanic fixing car in garage, tools and equipment, auto repair shop',
  'Sales Representative': 'salesperson in modern office, presentation materials, client meeting',
  'Architect': 'architect reviewing blueprints, drafting table, building models',
  'Physician': 'doctor in medical office, stethoscope, examining room',
  'Dentist': 'dentist in dental office, dental chair and tools, clean clinical setting',
  'Pharmacist': 'pharmacist at pharmacy counter, medicine bottles, helping customer',
  'Librarian': 'librarian at library desk, bookshelves, helping patron find books',
  'Journalist': 'journalist writing story at desk, notepad and laptop, newsroom',
  'Counselor': 'counselor in therapy office, comfortable chairs, supportive environment',
  'Veterinarian': 'veterinarian examining pet dog, animal clinic, caring for animals',
  'Electrician': 'electrician working on wiring, tools and safety gear, construction site',
  'Plumber': 'plumber fixing pipes, toolbox, residential bathroom',
  'Firefighter': 'firefighter in action, fire truck, brave rescue scene',
  'Pilot': 'pilot in airplane cockpit, aircraft controls, flying view',
  'Flight Attendant': 'flight attendant serving passengers, airplane cabin, friendly service',
  'Real Estate Agent': 'real estate agent showing house, property tour, happy clients',
  'Marketing Manager': 'marketing professional in meeting room, presentation slides, creative team',
  'Human Resources': 'HR manager conducting interview, office setting, professional meeting',
  'Financial Advisor': 'financial advisor with client, investment charts, planning session',
  'Data Scientist': 'data scientist analyzing graphs, computer screens with data, modern lab',
  'Graphic Designer': 'graphic designer at creative workstation, design software, artistic workspace',
  'Physical Therapist': 'physical therapist helping patient exercise, therapy equipment, rehabilitation',
  'Social Worker': 'social worker meeting with family, community center, supportive guidance',
};

interface GenerationResult {
  activity: string;
  type: 'extracurricular' | 'occupation';
  prompt: string;
  imageUrl: string | null;
  error: string | null;
}

async function generateImage(
  activity: string,
  prompt: string,
  type: 'extracurricular' | 'occupation'
): Promise<GenerationResult> {
  console.log(`\nGenerating image for ${type}: ${activity}`);
  console.log(`  Prompt: ${prompt.substring(0, 60)}...`);

  const result = await imageGenerator.generateImage(prompt, {
    style: 'cozy_cartoon',
    width: 1024,
    height: 1024,
    provider: 'imagen4', // Use Imagen 4 via fal.ai for permanent URLs
  });

  if (result.imageUrl) {
    console.log(`  ✓ Success: ${result.imageUrl}`);
  } else {
    console.log(`  ✗ Failed: ${result.error}`);
  }

  return {
    activity,
    type,
    prompt,
    imageUrl: result.imageUrl,
    error: result.error,
  };
}

async function generateAllImages(): Promise<void> {
  console.log('='.repeat(60));
  console.log('Activity Image Generation Script');
  console.log('='.repeat(60));
  console.log(`Provider: ${imageGenerator.getProvider()}`);
  console.log(`FAL_AI_KEY configured: ${!!config.FAL_AI_KEY}`);
  console.log(`OPENAI_API_KEY configured: ${!!config.OPENAI_API_KEY}`);
  console.log('');

  if (!config.FAL_AI_KEY && !config.OPENAI_API_KEY) {
    console.error('ERROR: No image generation API keys configured!');
    console.error('Set FAL_AI_KEY or OPENAI_API_KEY in .env');
    process.exit(1);
  }

  const results: GenerationResult[] = [];

  // Generate extracurricular images
  console.log('\n--- Generating Extracurricular Images ---');
  for (const [activity, prompt] of Object.entries(EXTRACURRICULAR_PROMPTS)) {
    const result = await generateImage(activity, prompt, 'extracurricular');
    results.push(result);

    // Rate limit: wait 2 seconds between requests
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }

  // Generate occupation images
  console.log('\n--- Generating Occupation Images ---');
  for (const [activity, prompt] of Object.entries(OCCUPATION_PROMPTS)) {
    const result = await generateImage(activity, prompt, 'occupation');
    results.push(result);

    // Rate limit: wait 2 seconds between requests
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }

  // Summary
  console.log('\n' + '='.repeat(60));
  console.log('Generation Complete - Summary');
  console.log('='.repeat(60));

  const successful = results.filter((r) => r.imageUrl);
  const failed = results.filter((r) => !r.imageUrl);

  console.log(`\nSuccessful: ${successful.length}/${results.length}`);
  console.log(`Failed: ${failed.length}/${results.length}`);

  if (failed.length > 0) {
    console.log('\nFailed generations:');
    for (const f of failed) {
      console.log(`  - ${f.activity}: ${f.error}`);
    }
  }

  // Output URLs for updating the code
  console.log('\n' + '='.repeat(60));
  console.log('Generated Image URLs (copy to code)');
  console.log('='.repeat(60));

  console.log('\n// Extracurriculars');
  for (const r of results.filter((r) => r.type === 'extracurricular' && r.imageUrl)) {
    console.log(`'${r.activity}': '${r.imageUrl}',`);
  }

  console.log('\n// Occupations');
  for (const r of results.filter((r) => r.type === 'occupation' && r.imageUrl)) {
    console.log(`'${r.activity}': '${r.imageUrl}',`);
  }
}

// Run the script
generateAllImages().catch((error) => {
  console.error('Script failed:', error);
  process.exit(1);
});
