<?php
/**
 * importWildlife.php
 *
 * Reads wildlife.txt and generates:
 *   web/data/wildlife/<slug>.json
 *
 * Output JSON format matches your requested schema
 * (health/moves are empty arrays).
 */

declare(strict_types=1);

$inputFile = __DIR__ . DIRECTORY_SEPARATOR . 'wildlife.txt';

// Adjust these if your folder differs:
$outputDir = __DIR__ . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'wildlife';

$regions = ['Halsand', 'Durand', 'Droquia', 'Isilia', 'Othenia'];
$regionName = "non";

$map = [
    'Size' => 'size',
    'Aggressiveness' => 'aggressiveness',
    'Societal Impact' => 'societalImpact',
    'Rituals/Behaviours' => 'ritualsBehaviour',
    'Defence/Hunting' => 'defence',
    'Diet' => 'diet',
    'Appearance' => 'appearance',
    'Habitat' => 'habitat',
    'Social Structure' => 'societalStructure',
];

function slugify(string $name): string
{
    $name = trim($name);
    $name = preg_replace('/[^\p{L}\p{N}]+/u', '-', $name) ?? $name; // keep unicode letters/digits
    $name = trim($name, '-');
    $name = mb_strtolower($name);
    return $name;
}

function ensureDir(string $dir): void
{
    if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new RuntimeException("Failed to create directory: $dir");
    }
}

if (!file_exists($inputFile)) {
    throw new RuntimeException("Input file not found: $inputFile");
}
ensureDir($outputDir);

$lines = file($inputFile, FILE_IGNORE_NEW_LINES);
if ($lines === false) {
    throw new RuntimeException("Failed to read: $inputFile");
}

$currentRegion = null;
$entries = [];

$i = 0;
while ($i < count($lines)) {
    $line = trim((string) $lines[$i]);

    // Skip blank lines
    if ($line === '') {
        $i++;
        continue;
    }

    // Region headers (ignored for output, but used to parse)
    if (in_array($line, $regions, true)) {
        $currentRegion = $line;
        $i++;
        continue;
    }

    // Creature name (start of a new entry)
    $name = $line;

    $data = [
        'region' => $currentRegion, // not requested in JSON; uncomment if you ever want it
        'type' => 'wildlife',
        'name' => $name,
        'size' => '',
        'aggressiveness' => '',
        'societalImpact' => '',
        'ritualsBehaviour' => '',
        'defence' => '',
        'diet' => '',
        'appearance' => '',
        'habitat' => '',
        'societalStructure' => '',
        'health' => [],
        'moves' => [],
    ];

    $i++;

    // Parse until we hit "Moves:" (end marker)
    while ($i < count($lines)) {
        $l = trim((string) $lines[$i]);

        // If we hit a region header mid-parse, treat as boundary
        if ($l !== '' && in_array($l, $regions, true)) {
            $currentRegion = $l;
            break;
        }

        // End marker for an entry
        if (str_starts_with($l, 'Moves:')) {
            $i++;
            break;
        }

        // Normal "Label: value"
        if (preg_match('/^([^:]+):\s*(.*)$/u', $l, $m)) {
            $label = trim($m[1]);
            $value = trim($m[2]);

            if (isset($map[$label])) {
                $data[$map[$label]] = $value;
            }
        }

        $i++;
    }

    $entries[] = $data;
}

// Write files
$written = 0;
foreach ($entries as $e) {
    $slug = slugify($e['name']);
    $folder = $e["region"];
    unset($e["region"]);
    ensureDir($outputDir . DIRECTORY_SEPARATOR . $folder);
    $path = $outputDir . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . $slug . '.json';

    // If two names slugify to the same filename, add a suffix
    $suffix = 2;
    while (file_exists($path)) {
        $path = $outputDir . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . $slug . '-' . $suffix . '.json';
        $suffix++;
    }

    $json = json_encode($e, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    if ($json === false) {
        throw new RuntimeException("JSON encode failed for: " . $e['name']);
    }

    file_put_contents($path, $json . PHP_EOL);
    $written++;
}

echo "Imported " . count($entries) . " entries; wrote $written JSON files to: $outputDir" . PHP_EOL;
