import 'dotenv/config';
import fs from 'fs';
import { pool } from './connection.js';
import { runMigrations } from './migrate.js';

function loadJson(path: string): any[] {
  try {
    return JSON.parse(fs.readFileSync(path, 'utf-8'));
  } catch {
    console.log(`Skipping ${path} (not found or invalid)`);
    return [];
  }
}

async function main() {
  console.log('Running migrations first...');
  await runMigrations();

  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // Categories
    const categories = loadJson('/tmp/luna_categories.json');
    for (const c of categories) {
      await client.query(
        'INSERT INTO categories (id, name, slug, icon, sort_order, created_at) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO NOTHING',
        [c.id, c.name, c.slug, c.icon, c.sort_order, c.created_at]
      );
    }
    console.log(`Imported ${categories.length} categories`);

    // Tags
    const tags = loadJson('/tmp/luna_tags.json');
    for (const t of tags) {
      await client.query(
        'INSERT INTO tags (id, name, slug, created_at) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING',
        [t.id, t.name, t.slug, t.created_at]
      );
    }
    console.log(`Imported ${tags.length} tags`);

    // Recipes
    const recipes = loadJson('/tmp/luna_recipes.json');
    for (const r of recipes) {
      await client.query(
        `INSERT INTO recipes (id, title, slug, description, category_id, difficulty, prep_time, cook_time, total_time, servings, image_url, source_url, image_source, is_favorite, created_at, updated_at)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) ON CONFLICT (id) DO NOTHING`,
        [r.id, r.title, r.slug, r.description, r.category_id, r.difficulty, r.prep_time, r.cook_time, r.total_time, r.servings, r.image_url, r.source_url, r.image_source, r.is_favorite || 0, r.created_at, r.updated_at]
      );
    }
    console.log(`Imported ${recipes.length} recipes`);

    // Recipe Tags
    const recipeTags = loadJson('/tmp/luna_recipe_tags.json');
    for (const rt of recipeTags) {
      await client.query(
        'INSERT INTO recipe_tags (recipe_id, tag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',
        [rt.recipe_id, rt.tag_id]
      );
    }
    console.log(`Imported ${recipeTags.length} recipe_tags`);

    // Ingredients
    const ingredients = loadJson('/tmp/luna_ingredients.json');
    for (const i of ingredients) {
      await client.query(
        'INSERT INTO ingredients (id, recipe_id, amount, unit, name, group_name, sort_order) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO NOTHING',
        [i.id, i.recipe_id, i.amount, i.unit, i.name, i.group_name, i.sort_order]
      );
    }
    console.log(`Imported ${ingredients.length} ingredients`);

    // Steps
    const steps = loadJson('/tmp/luna_steps.json');
    for (const s of steps) {
      await client.query(
        'INSERT INTO steps (id, recipe_id, step_number, instruction, duration_minutes, image_url) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO NOTHING',
        [s.id, s.recipe_id, s.step_number, s.instruction, s.duration_minutes, s.image_url]
      );
    }
    console.log(`Imported ${steps.length} steps`);

    // Notes
    const notes = loadJson('/tmp/luna_notes.json');
    for (const n of notes) {
      await client.query(
        'INSERT INTO notes (id, recipe_id, content, created_at) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING',
        [n.id, n.recipe_id, n.content, n.created_at]
      );
    }
    console.log(`Imported ${notes.length} notes`);

    // Shopping items
    const shopping = loadJson('/tmp/luna_shopping.json');
    for (const s of shopping) {
      await client.query(
        'INSERT INTO shopping_items (id, name, amount, unit, checked, recipe_id, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO NOTHING',
        [s.id, s.name, s.amount, s.unit, Boolean(s.checked), s.recipe_id, s.created_at]
      );
    }
    console.log(`Imported ${shopping.length} shopping items`);

    await client.query('COMMIT');
    console.log('Import complete!');
  } catch (e) {
    await client.query('ROLLBACK');
    console.error('Import failed:', e);
    throw e;
  } finally {
    client.release();
    await pool.end();
  }
}

main().catch(() => process.exit(1));
