<?php
/**
 * Einmaliger Import aus data/recipes.json in die relationale DB.
 * Die Website liest zur Laufzeit nur noch aus Postgres.
 *
 *   php scripts/db-seed.php
 */
require_once dirname(__DIR__) . '/helpers.php';

$seedPath = dirname(__DIR__) . '/data/recipes.json';
if (!file_exists($seedPath)) {
    fwrite(STDERR, "Seed-Datei fehlt: data/recipes.json\n");
    exit(1);
}

$raw = file_get_contents($seedPath);
$recipes = json_decode($raw, true);
if (!is_array($recipes)) {
    fwrite(STDERR, "Ungültiges JSON in data/recipes.json\n");
    exit(1);
}

try {
    $pdo = require_database();
} catch (DatabaseUnavailableException $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
}

$count = 0;
foreach ($recipes as $recipe) {
    if (!is_array($recipe) || empty($recipe['slug'])) {
        continue;
    }
    if (save_recipe($recipe, $pdo)) {
        $count++;
        echo "  + {$recipe['slug']}\n";
    } else {
        fwrite(STDERR, "  ! Fehler bei {$recipe['slug']}\n");
    }
}

echo "\nImport abgeschlossen: {$count} Rezepte.\n";
