<?php
/**
 * CopyPaste CLI Wrapper
 *
 * Usage:
 *   Export: php copyPasteSync.php export "RuleName1,RuleName2"
 *   Import: php copyPasteSync.php import '{"version":"1.0",...}' '[{"table":"Person","data":[{"id":600}]}]'
 *
 * @author enured
 */
namespace IMATHUZH\Qfq\External;

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

use IMATHUZH\Qfq\Core\Helper\CopyPaste;

// Detect API calls if this is defined. Do not try use "const QFQ_API 'Api call'" in Constanst.php : this will break detection of 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['HTTP_HOST']) || isset($_SERVER['REQUEST_URI'])) {
    die('Access denied: This script can only be executed from command line.');
}

/**
 * Main execution
 */
try {
    $args = parseArgs();

    if ($args['action'] === 'export') {
        // Export operation
        $copyPaste = new CopyPaste($args['rules']);
        $json = $copyPaste->handleExport();

        // Output JSON to stdout
        echo $json;
        exit(0);

    } elseif ($args['action'] === 'import') {
        // Import operation
        $copyPaste = new CopyPaste($args['data']);
        $result = $copyPaste->handleImport($args['overrides']);

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

} catch (Exception $e) {
    fwrite(STDERR, "Error: " . $e->getMessage() . "\n");
    fwrite(STDERR, "Trace: " . $e->getTraceAsString() . "\n");
    exit(1);
} catch (\CodeException $e) {
} catch (\DbException $e) {
} catch (\UserFormException $e) {
} catch (\UserReportException $e) {
} catch (\Exception $e) {
}

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

    if ($argc < 3) {
        fwrite(STDERR, "Usage:\n");
        fwrite(STDERR, "  Export: {$argv[0]} export \"RuleName1,RuleName2\"\n");
        fwrite(STDERR, "  Import: {$argv[0]} import 'JSON_DATA' '[OVERRIDE_JSON]'\n");
        exit(1);
    }

    $action = $argv[1];

    if ($action === 'export') {
        return [
            'action' => 'export',
            'rules' => $argv[2]
        ];
    } elseif ($action === 'import') {
        return [
            'action' => 'import',
            'data' => $argv[2],
            'overrides' => $argv[3] ?? null
        ];
    } else {
        fwrite(STDERR, "Error: Unknown action '{$action}'\n");
        exit(1);
    }
}