<?php
/**
 * CopyPaste CLI Wrapper - Updated for DeployRule
 *
 * Usage:
 *   Export: php deploySync.php export "RuleName1,RuleName2"
 *   Import: php deploySync.php import '{"version":"2.0",...}' '[{"table":"Person","data":[{"id":600}]}]'
 *   Import from file: php deploySync.php import @/path/to/data.json [@/path/to/override.json]
 *
 * @author enured
 * @version 2.0
 */
namespace IMATHUZH\Qfq\External;

require_once(__DIR__ . '/../../vendor/autoload.php');

use IMATHUZH\Qfq\Core\Helper\SyncByRule;

// Detect API calls
define('QFQ_API', 'Api call');

// SECURITY: CLI-only execution - prevent web access
if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') {
    http_response_code(403);
    die('Access denied: This script can only be executed from command line.');
}

// Additional security check
if (isset($_SERVER[CLIENT_HTTP_HOST]) || isset($_SERVER[CLIENT_REQUEST_URI])) {
    die('Access denied: This script can only be executed from command line.');
}

/**
 * Main execution
 */
try {
    $startTime = microtime(true);

    $args = parseArgs();

    if ($args[SYNC_BY_RULE_CMD_ACTION] === SYNC_BY_RULE_CMD_EXPORT) {
        // Export operation
        fwrite(STDERR, "Exporting using rules: {$args[SYNC_BY_RULE_CMD_RULES]}\n");

        // Enable deployment tracking for CLI usage
        $copyPaste = new SyncByRule($args[SYNC_BY_RULE_CMD_RULES], null, null, false, true);
        $json = $copyPaste->handleExport();

        // Output JSON to stdout
        echo $json;

        $duration = round(microtime(true) - $startTime, 2);
        fwrite(STDERR, "\nExport completed in {$duration}s\n");
        exit(0);

    } elseif ($args[SYNC_BY_RULE_CMD_ACTION] === SYNC_BY_RULE_CMD_IMPORT) {
        // Import operation
        fwrite(STDERR, "Importing data...\n");

        // Enable deployment tracking for CLI usage
        $copyPaste = new SyncByRule($args[SYNC_BY_RULE_JSON_DATA], null, null, false, true);
        $result = $copyPaste->handleImport($args[SYNC_BY_RULE_CMD_OVERRIDES]);

        // Count statistics
        $stats = [
            'inserted' => 0,
            'updated' => 0,
            'existing' => 0,
            'skipped' => 0,
        ];

        function countActions($element, &$stats) {
            if (isset($element[SYNC_BY_RULE_ITEMS])) {
                foreach ($element[SYNC_BY_RULE_ITEMS] as $item) {
                    $action = $item[SYNC_BY_RULE_CMD_ACTION] ?? 'unknown';
                    if (isset($stats[$action])) {
                        $stats[$action]++;
                    }
                }
            }
            if (isset($element[SYNC_BY_RULE_CHILDREN])) {
                foreach ($element[SYNC_BY_RULE_CHILDREN] as $child) {
                    countActions($child, $stats);
                }
            }
        }

        foreach ($result['imported'] as $element) {
            countActions($element, $stats);
        }

        // Output result as JSON
        echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

        $duration = round(microtime(true) - $startTime, 2);
        fwrite(STDERR, "\nImport completed in {$duration}s\n");
        fwrite(STDERR, "Statistics:\n");
        fwrite(STDERR, "  Inserted: {$stats['inserted']}\n");
        fwrite(STDERR, "  Updated:  {$stats['updated']}\n");
        fwrite(STDERR, "  Existing: {$stats['existing']}\n");
        fwrite(STDERR, "  Skipped:  {$stats['skipped']}\n");
        exit(0);
    }

} catch (Exception $e) {
    fwrite(STDERR, "\nError: " . $e->getMessage() . "\n");
    if (isset($_SERVER['DEBUG']) || getenv('DEBUG')) {
        fwrite(STDERR, "Trace: " . $e->getTraceAsString() . "\n");
    }
    exit(1);
}

/**
 * Parse CLI arguments
 */
function parseArgs() {
    global $argc, $argv;

    if ($argc < 3) {
        fwrite(STDERR, "DeploySync - Database Deployment Tool v2.0\n\n");
        fwrite(STDERR, "Usage:\n");
        fwrite(STDERR, "  Export: {$argv[0]} export \"RuleName1,RuleName2\"\n");
        fwrite(STDERR, "  Import: {$argv[0]} import 'JSON_DATA' '[OVERRIDE_JSON]'\n");
        fwrite(STDERR, "  Import: {$argv[0]} import @/path/to/data.json [@/path/to/override.json]\n\n");
        fwrite(STDERR, "Examples:\n");
        fwrite(STDERR, "  {$argv[0]} export \"FormExport\"\n");
        fwrite(STDERR, "  {$argv[0]} import @export.json\n");
        fwrite(STDERR, "  {$argv[0]} import @export.json @overrides.json\n\n");
        fwrite(STDERR, "Features:\n");
        fwrite(STDERR, "  - Tracks deployments in DeployRef table\n");
        fwrite(STDERR, "  - Supports update modes: once, always, skipModified\n");
        fwrite(STDERR, "  - Handles complex relational hierarchies\n");
        exit(1);
    }

    $action = $argv[1];

    if ($action === SYNC_BY_RULE_CMD_EXPORT) {
        return [
            SYNC_BY_RULE_CMD_ACTION => SYNC_BY_RULE_CMD_EXPORT,
            SYNC_BY_RULE_CMD_RULES => $argv[2]
        ];
    } elseif ($action === SYNC_BY_RULE_CMD_IMPORT) {
        // Check if argument is a file path (starts with @)
        $dataArg = $argv[2];
        if (str_starts_with($dataArg, '@')) {
            // Read from file
            $filePath = substr($dataArg, 1);
            if (!file_exists($filePath)) {
                fwrite(STDERR, "Error: File not found: {$filePath}\n");
                exit(1);
            }
            $data = file_get_contents($filePath);
        } else {
            // Use argument as data
            $data = $dataArg;
        }

        // Handle overrides (optional)
        $overrides = null;
        if ($argc >= 4) {
            $overrideArg = $argv[3];
            if (str_starts_with($overrideArg, '@')) {
                // Read from file
                $filePath = substr($overrideArg, 1);
                if (!file_exists($filePath)) {
                    fwrite(STDERR, "Error: Override file not found: {$filePath}\n");
                    exit(1);
                }
                $overrides = file_get_contents($filePath);
            } else {
                // Use argument as data
                $overrides = $overrideArg;
            }
        }

        return [
            SYNC_BY_RULE_CMD_ACTION => SYNC_BY_RULE_CMD_IMPORT,
            SYNC_BY_RULE_JSON_DATA => $data,
            SYNC_BY_RULE_CMD_OVERRIDES => $overrides
        ];
    } else {
        fwrite(STDERR, "Error: Unknown action '{$action}'\n");
        fwrite(STDERR, "Valid actions: export, import\n");
        exit(1);
    }
}