<?php

declare(strict_types=1);

namespace Origin\Config;

use RuntimeException;

function loadVaultValue(string $vaultPath, string $key): string
{
    $fullPath = rtrim($vaultPath, '/') . '/' . $key . '.enc';
    if (!file_exists($fullPath)) {
        throw new RuntimeException("Vault entry not found: {$key}");
    }

    $raw = file_get_contents($fullPath);
    if ($raw === false) {
        throw new RuntimeException("Failed to read vault entry: {$key}");
    }

    $decoded = base64_decode($raw);

    // OpenSSL CLI salted format: "Salted__" + 8-byte salt + ciphertext
    // Matches C++ engine_vault.cpp: openssl enc -aes-256-cbc -salt -pbkdf2 -iter 100000
    if (substr($decoded, 0, 8) !== 'Salted__') {
        return trim($raw); // Fallback for unencrypted values
    }
    $salt = substr($decoded, 8, 8);
    $ciphertext = substr($decoded, 16);

    // Derive key+IV via PBKDF2 (matches C++ engine: -pbkdf2 -iter 100000)
    $keyiv = openssl_pbkdf2(loadVaultKey(), $salt, 48, 100000, 'sha256');
    $derivedKey = substr($keyiv, 0, 32);
    $iv = substr($keyiv, 32, 16);

    $decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $derivedKey, OPENSSL_RAW_DATA, $iv);
    return $decrypted !== false ? trim($decrypted) : trim($raw);
}

function loadVaultKey(): string
{
    static $key = null;
    if ($key !== null) {
        return $key;
    }

    $keyPath = '/var/www/private/vault_master.key';
    if (!file_exists($keyPath)) {
        $fallback = $_ENV['VAULT_MASTER_KEY'] ?? '';
        if (strlen($fallback) >= 32) {
            $key = $fallback;
            return $key;
        }
        throw new RuntimeException('Vault master key not found');
    }

    $key = trim(file_get_contents($keyPath));
    return $key;
}

function getStripeWebhookSecret(): string
{
    $vaultPath = '/opt/apache/engine/vault/encrypted';
    try {
        return loadVaultValue($vaultPath, 'stripe_webhook_secret');
    } catch (RuntimeException) {
        return $_ENV['STRIPE_WEBHOOK_SECRET'] ?? '';
    }
}

function getStripeApiKey(): string
{
    $vaultPath = '/opt/apache/engine/vault/encrypted';
    try {
        return loadVaultValue($vaultPath, 'stripe_api_key');
    } catch (RuntimeException) {
        return $_ENV['STRIPE_API_KEY'] ?? '';
    }
}

return [
    'engine_host' => '10.69.69.6',
    'engine_port' => 8301,
    'hmac_key_path' => '/var/www/private/bridge_hmac.key',
    'vault_path' => '/opt/apache/engine/vault/encrypted',

    'stripe' => [
        'webhook_secret' => getStripeWebhookSecret(),
        'api_key' => getStripeApiKey(),
        'api_version' => '2024-06-20',
    ],

    'xmr' => [
        'wallet_url' => 'http://10.69.69.6:18082',
        'rpc_user' => 'wallet',
        'rpc_password' => $_ENV['XMR_RPC_PASSWORD'] ?? '',
        'confirmations_required' => 10,
        'timeout' => 30,
    ],

    'tron' => [
        'api_url' => 'http://10.69.69.6:9090',
        'signer_endpoint' => '/wallet/broadcasttransaction',
        'timeout' => 30,
    ],

    'usdc_polygon' => [
        'rpc_url' => $_ENV['POLYGON_RPC_URL'] ?? 'https://polygon-rpc.com',
        'contract_address' => '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174',
        'confirmations_required' => 12,
        'timeout' => 30,
    ],

    'etransfer' => [
        'imap_host' => $_ENV['ETRANSFER_IMAP_HOST'] ?? 'imap.gmail.com',
        'imap_port' => (int)($_ENV['ETRANSFER_IMAP_PORT'] ?? 993),
        'imap_user' => $_ENV['ETRANSFER_IMAP_USER'] ?? '',
        'imap_password' => $_ENV['ETRANSFER_IMAP_PASSWORD'] ?? '',
        'verification_endpoint' => 'http://10.69.69.6:8301/etransfer/verify',
        'auto_deposit_patterns' => [
            '/\$[0-9]+\.[0-9]{2} has been deposited/i',
            '/e-Transfer.*accepted/i',
            '/Interac e-Transfer.*deposited/i',
        ],
    ],

    'ollama' => [
        'url' => 'http://10.69.69.6:11434',
        'model' => 'llama3.1',
        'timeout' => 60,
    ],

    'email' => [
        'from_address' => 'noreply@origin.local',
        'from_name' => 'Origin Platform',
        'reply_to' => 'support@origin.local',
    ],

    'fulfillment' => [
        'canadapost_api_key' => $_ENV['CP_API_KEY'] ?? '',
        'canadapost_api_secret' => $_ENV['CP_API_SECRET'] ?? '',
        'canadapost_customer_number' => $_ENV['CP_CUSTOMER_NUM'] ?? '',
        'default_carrier' => 'canadapost',
        'origin_postal_code' => $_ENV['ORIGIN_POSTAL'] ?? 'M5V 3A8',
    ],

    'security' => [
        'max_failed_hmac' => 5,
        'hmac_window_seconds' => 300,
        'blocked_ip_file' => '/var/www/logs/blocked_ips.json',
        'event_log_path' => '/var/www/logs/security',
    ],

    'health' => [
        'check_interval_seconds' => 30,
        'failure_threshold' => 3,
        'recovery_threshold' => 2,
        'metrics_retention_hours' => 24,
    ],
];
