#!/usr/bin/env php
<?php
/**
 * Database Seeder CLI
 *
 * Uso:
 *   php bin/seed                         - Ejecutar semillas del grupo demo (default)
 *   php bin/seed --group=demo           - Ejecutar semillas demo
 *   php bin/seed --group=klee           - Ejecutar baseline mínimo para implementación
 *   php bin/seed RolesSeeder            - Ejecutar una semilla específica
 *   php bin/seed --list                 - Listar semillas disponibles (grupo demo)
 *   php bin/seed --list --group=klee    - Listar semillas del grupo klee
 *   php bin/seed --help                 - Mostrar ayuda
 *
 * Para crear una nueva semilla:
 *   1. Crear archivo en database/seeders/ (ej: MiModuloSeeder.php)
 *   2. Extender Seeder e implementar run()
 *   3. Listo. No hay que tocar este archivo.
 */

$basePath = dirname(__DIR__);
define('BASE_PATH', $basePath . '/');

require $basePath . '/core/helpers/Env.php';
Env::load($basePath . '/.env');

// ── Cargar base y runner ──────────────────────────────────────────
require $basePath . '/database/Seeder.php';
require $basePath . '/database/SeederRunner.php';

// ── Argumentos CLI ────────────────────────────────────────────────
$args = array_slice($argv, 1);
$showHelp = false;
$listMode = false;
$group = 'demo';
$singleSeeder = null;

for ($i = 0; $i < count($args); $i++) {
    $arg = (string)$args[$i];

    if ($arg === '--help' || $arg === '-h') {
        $showHelp = true;
        break;
    }

    if ($arg === '--list' || $arg === '-l') {
        $listMode = true;
        continue;
    }

    if (strpos($arg, '--group=') === 0) {
        $group = trim((string)substr($arg, 8));
        continue;
    }

    if ($arg === '--group' || $arg === '-g') {
        if (!isset($args[$i + 1])) {
            echo "Error: --group requiere un valor (ej: demo o klee).\n";
            exit(1);
        }
        $group = trim((string)$args[$i + 1]);
        $i++;
        continue;
    }

    if (str_starts_with($arg, '-')) {
        echo "Error: argumento no soportado: {$arg}\n";
        echo "Use --help para ver opciones disponibles.\n";
        exit(1);
    }

    if ($singleSeeder !== null) {
        echo "Error: solo se permite una clase seeder por ejecución.\n";
        exit(1);
    }

    $singleSeeder = $arg;
}

$group = strtolower(trim((string)$group));
if ($group === '') {
    $group = 'demo';
}

if ($showHelp) {
    echo <<<HELP

  Klee Core — Database Seeder
  ────────────────────────────
  php bin/seed                          Run default group (demo)
  php bin/seed --group=demo            Run demo dataset
  php bin/seed --group=klee            Run production baseline (admin + estados + prioridades)
  php bin/seed RolesSeeder             Run a specific seeder
  php bin/seed --list                  List seeders for current group (default: demo)
  php bin/seed --list --group=klee     List seeders for klee group
  php bin/seed --help                  Show this help

  To create a new seeder:
    1. Create file in database/seeders/ (e.g. MyModuleSeeder.php)
    2. Extend Seeder, set \$order / \$groups, implement run()
    3. Done — no registration needed.

HELP;
    exit(0);
}

// ── Conexión a BD ─────────────────────────────────────────────────
if (file_exists($basePath . '/app/config/Config.php')) {
    require $basePath . '/app/config/Config.php';
}
if (file_exists($basePath . '/app/config/ConfigEnv.php')) {
    require $basePath . '/app/config/ConfigEnv.php';
}

$dbConfig = null;
if (class_exists('ConfigEnv') && property_exists('ConfigEnv', 'DB_CONNECTIONS')) {
    $connections = ConfigEnv::$DB_CONNECTIONS;
    if (isset($connections['klee'])) {
        $dbConfig = $connections['klee'];
    }
}

if (!$dbConfig) {
    $dbConfig = [
        'driver' => getenv('DB_DRIVER') ?: 'mysql',
        'host'   => getenv('DB_HOST')   ?: 'localhost',
        'dbname' => getenv('DB_NAME')   ?: 'klee_core',
        'user'   => getenv('DB_USER')   ?: 'root',
        'password' => getenv('DB_PASS') ?: '',
    ];
}

if (empty($dbConfig['host']) || empty($dbConfig['dbname']) || empty($dbConfig['user'])) {
    echo "Error: Database configuration not found.\n";
    echo "Set DB_HOST, DB_NAME, DB_USER env vars, or check app/config/ConfigEnv.php\n";
    exit(1);
}

try {
    $dsn = "{$dbConfig['driver']}:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset=utf8mb4";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Database connection error: " . $e->getMessage() . "\n";
    exit(1);
}

$tableExists = function (PDO $pdo, $tableName) {
    $tableName = trim((string)$tableName);
    if ($tableName === '') {
        return false;
    }

    try {
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?');
        $stmt->execute(array($tableName));
        return ((int)$stmt->fetchColumn() > 0);
    } catch (Throwable $exception) {
        return false;
    }
};

// ── Ejecutar ──────────────────────────────────────────────────────
$runner = new SeederRunner($pdo, $basePath . '/database/seeders');

$recordSeedRun = function ($mode, $name = null, $group = null) use ($basePath) {
    $cacheDir = $basePath . '/storage/cache';
    if (!is_dir($cacheDir)) {
        @mkdir($cacheDir, 0755, true);
    }

    $payload = array(
        'mode' => (string)$mode,
        'name' => $name !== null ? (string)$name : null,
        'group' => $group !== null ? (string)$group : null,
        'executed_at' => date('Y-m-d H:i:s'),
    );

    @file_put_contents($cacheDir . '/last_seed.json', json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
};

try {
    if ($listMode) {
        $runner->list($group);
    } elseif ($singleSeeder !== null) {
        if (!$tableExists($pdo, 'roles')) {
            echo "[✗] Error: Base schema not initialized (missing table: roles).\n";
            echo "Run first: php bin/migrate up\n";
            exit(1);
        }
        $runner->runOne($singleSeeder);
        $recordSeedRun('single', $singleSeeder, $group);
    } else {
        if (!$tableExists($pdo, 'roles')) {
            echo "[✗] Error: Base schema not initialized (missing table: roles).\n";
            echo "Run first: php bin/migrate up\n";
            exit(1);
        }
        $runner->runAll($group);
        $recordSeedRun('all', 'GROUP:' . strtoupper($group), $group);
    }
} catch (Exception $e) {
    echo "[✗] Error: " . $e->getMessage() . "\n";
    exit(1);
}

echo "\n";
exit(0);
