<?php

declare(strict_types=1);

class TranslationRepair
{
    private const FLAG = 'i18n_registered_override_repair_v1';
    private const DELETE_CHUNK = 200;

    public static function runOnce(): void
    {
        if (Setting::get(self::FLAG, '') === '1') {
            return;
        }

        if (!self::claim()) {
            return;
        }

        try {
            $removed = self::repair();
            if ($removed > 0) {
                error_log('TranslationRepair: removed ' . $removed . ' English override(s) written over bundled translations.');
            }
        } catch (\Throwable $e) {
            error_log('TranslationRepair failed: ' . $e->getMessage());
        }
    }

    private static function claim(): bool
    {
        try {
            $stmt = Database::query(
                'INSERT IGNORE INTO settings (setting_key, setting_value, autoload) VALUES (?, ?, 1)',
                [self::FLAG, '1']
            );
            return $stmt->rowCount() === 1;
        } catch (\Throwable $e) {
            return false;
        }
    }

    public static function repair(): int
    {
        $registered = Translator::getRegisteredKeys();
        if (empty($registered)) {
            return 0;
        }

        $codes = Database::fetchAll(
            'SELECT DISTINCT lang_code FROM translation_overrides WHERE lang_code <> ?',
            ['en']
        );
        if (empty($codes)) {
            return 0;
        }

        $removed = 0;
        foreach ($codes as $row) {
            $code = (string) $row['lang_code'];
            $fileStrings = Translator::getFileStrings($code);
            if (empty($fileStrings)) {
                continue;
            }

            $rows = Database::fetchAll(
                'SELECT id, translation_key, value FROM translation_overrides WHERE lang_code = ?',
                [$code]
            );

            $doomed = [];
            foreach ($rows as $r) {
                $key = (string) $r['translation_key'];
                if (!array_key_exists($key, $registered)) {
                    continue;
                }
                $englishDefault = (string) $registered[$key];
                if ($englishDefault === '' || (string) $r['value'] !== $englishDefault) {
                    continue;
                }
                $fileValue = (string) ($fileStrings[$key] ?? '');
                if ($fileValue === '' || $fileValue === $englishDefault) {
                    continue;
                }
                $doomed[] = (int) $r['id'];
            }

            foreach (array_chunk($doomed, self::DELETE_CHUNK) as $chunk) {
                $placeholders = implode(',', array_fill(0, count($chunk), '?'));
                $removed += Database::query(
                    'DELETE FROM translation_overrides WHERE id IN (' . $placeholders . ')',
                    $chunk
                )->rowCount();
            }
        }

        return $removed;
    }
}
