<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';

if (!is_cli_request()) {
    header('Content-Type: text/plain; charset=utf-8');
    echo "This script can only be run in CLI mode.\n";
    exit(1);
}

$domainId = 0;
$force = false;
foreach (array_slice($argv, 1) as $arg) {
    if (strpos($arg, '--domain=') === 0) {
        $domainId = (int)substr($arg, 9);
        continue;
    }
    if ($arg === '--force') {
        $force = true;
    }
}

try {
    $result = rebuild_tag_slugs($domainId, $force);
    echo 'Tag slug rebuild completed.' . PHP_EOL;
    echo 'Total: ' . (isset($result['total_count']) ? (int)$result['total_count'] : 0) . PHP_EOL;
    echo 'Updated: ' . (isset($result['updated_count']) ? (int)$result['updated_count'] : 0) . PHP_EOL;
    echo 'Skipped: ' . (isset($result['skipped_count']) ? (int)$result['skipped_count'] : 0) . PHP_EOL;
    if (!empty($result['details'])) {
        echo str_repeat('-', 72) . PHP_EOL;
        foreach ($result['details'] as $item) {
            echo '[' . (isset($item['domain_id']) ? (int)$item['domain_id'] : 0) . '] ' . (isset($item['name']) ? (string)$item['name'] : '') . ' : ' . (isset($item['old_slug']) ? (string)$item['old_slug'] : '') . ' => ' . (isset($item['new_slug']) ? (string)$item['new_slug'] : '') . PHP_EOL;
        }
    }
    exit(0);
} catch (Exception $e) {
    fwrite(STDERR, 'Tag slug rebuild failed: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
