<?php
/**
 * Generate POT file for AI eShop Optimizer
 * This script extracts translatable strings from PHP files in the plugin
 *
 * @package AI_eShop_Optimizer
 */

// Direct access protection - allows CLI execution for development
if ( ! defined( 'ABSPATH' ) ) {
    if ( php_sapi_name() !== 'cli' ) {
        exit;
    }
}

// Set memory limit and execution time for large codebases
ini_set('memory_limit', '512M');
set_time_limit(300);

$plugin_dir = __DIR__;
$languages_dir = $plugin_dir . '/languages';

// Create languages directory if it doesn't exist
if (!file_exists($languages_dir)) {
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir -- CLI tool, not web context
    mkdir($languages_dir, 0755, true);
}

// Files to scan
$scan_dirs = [
    $plugin_dir . '/includes',
    $plugin_dir . '/assets/pages',
];

// Initialize strings array
$strings = [];

// Translation function patterns to search for
$patterns = [
    "/__\(\s*['\"](.+?)['\"]\s*,\s*['\"]ai-eshop-optimizer['\"]\s*\)/s",
    "/_e\(\s*['\"](.+?)['\"]\s*,\s*['\"]ai-eshop-optimizer['\"]\s*\)/s",
    "/esc_html__\(\s*['\"](.+?)['\"]\s*,\s*['\"]ai-eshop-optimizer['\"]\s*\)/s",
    "/esc_html_e\(\s*['\"](.+?)['\"]\s*,\s*['\"]ai-eshop-optimizer['\"]\s*\)/s",
    "/esc_attr__\(\s*['\"](.+?)['\"]\s*,\s*['\"]ai-eshop-optimizer['\"]\s*\)/s",
    "/esc_attr_e\(\s*['\"](.+?)['\"]\s*,\s*['\"]ai-eshop-optimizer['\"]\s*\)/s",
    "/esc_js\(\s*__\(\s*['\"](.+?)['\"]\s*,\s*['\"]ai-eshop-optimizer['\"]\s*\)\s*\)/s",
];

// Scan directories recursively
function scanDirectory($dir, &$strings, $patterns) {
    if (!is_dir($dir)) {
        return;
    }

    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($files as $file) {
        if ($file->isFile() && $file->getExtension() === 'php') {
            $content = file_get_contents($file->getPathname());

            // Search for each pattern
            foreach ($patterns as $pattern) {
                if (preg_match_all($pattern, $content, $matches)) {
                    foreach ($matches[1] as $string) {
                        // Clean up the string
                        $string = trim($string);

                        // Skip empty strings
                        if (empty($string)) {
                            continue;
                        }

                        // Store unique strings
                        $strings[$string] = true;
                    }
                }
            }
        }
    }
}

// Scan all directories
foreach ($scan_dirs as $dir) {
    scanDirectory($dir, $strings, $patterns);
}

// Sort strings alphabetically
$strings = array_keys($strings);
sort($strings);

// Generate POT file content
$pot_content = <<<'EOT'
# Copyright (C) 2025 AI eShop Optimizer
# This file is distributed under the same license as the AI eShop Optimizer plugin.
msgid ""
msgstr ""
"Project-Id-Version: AI eShop Optimizer\n"
"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/ai-eshop-optimizer\n"
"POT-Creation-Date: 2025-01-27 12:00+0000\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"X-Generator: Custom PHP Script\n"

EOT;

// Add each string as a msgid entry
foreach ($strings as $string) {
    // Escape special characters
    $escaped = addcslashes($string, "\0..\37\"\\");
    $pot_content .= "msgid \"$escaped\"\n";
    $pot_content .= "msgstr \"\"\n\n";
}

// Write to POT file
$pot_file = $languages_dir . '/ai-eshop-optimizer.pot';
file_put_contents($pot_file, $pot_content);

// Output results
echo "POT file generated successfully!\n";
echo "Location: " . esc_html($pot_file) . "\n";
echo "Extracted " . count($strings) . " unique translatable strings\n";
echo "File size: " . number_format(filesize($pot_file)) . " bytes\n";
