// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {Script, console} from "forge-std/Script.sol";
import "../../../contracts/bridge/trustless/integration/BridgeReserveCoordinator.sol";
import "../../../contracts/bridge/trustless/integration/StablecoinPegManager.sol";
import "../../../contracts/bridge/trustless/integration/CommodityPegManager.sol";
import "../../../contracts/bridge/trustless/integration/ISOCurrencyManager.sol";
import "../../../contracts/reserve/ReserveSystem.sol";

/**
 * @title DeployIntegrationContracts
 * @notice Deployment script for integration contracts (Peg Managers, Reserve Coordinator)
 * @dev Deploys all integration contracts and links them together
 */
contract DeployIntegrationContracts is Script {
    // Configuration
    uint256 constant DEFAULT_MIN_RESERVE_RATIO_BPS = 11000; // 110%
    uint256 constant DEFAULT_USD_PEG_THRESHOLD_BPS = 50; // 0.5%
    uint256 constant DEFAULT_ETH_PEG_THRESHOLD_BPS = 10; // 0.1%
    uint256 constant DEFAULT_COMMODITY_PEG_THRESHOLD_BPS = 100; // 1%

    // Ethereum Mainnet addresses
    address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
    address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    address constant ETH_ADDRESS = address(0); // Native ETH

    struct DeploymentAddresses {
        address bridgeSwapCoordinator;
        address reserveSystem;
        address stablecoinPegManager;
        address commodityPegManager;
        address isoCurrencyManager;
        address bridgeReserveCoordinator;
        address xauAddress; // XAU token address (if tokenized)
    }

    function run() external {
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
        address deployer = vm.addr(deployerPrivateKey);
        
        console.log("=== Integration Contracts Deployment ===");
        console.log("Deployer:", deployer);
        console.log("Chain ID:", block.chainid);
        
        require(block.chainid == 1, "DeployIntegrationContracts: Ethereum Mainnet only");

        // Load required addresses from environment
        address bridgeSwapCoordinator = vm.envAddress("BRIDGE_SWAP_COORDINATOR");
        address reserveSystem = vm.envAddress("RESERVE_SYSTEM");
        address xauAddress = vm.envOr("XAU_ADDRESS", address(0));

        vm.startBroadcast(deployerPrivateKey);

        DeploymentAddresses memory addresses;
        addresses.bridgeSwapCoordinator = bridgeSwapCoordinator;
        addresses.reserveSystem = reserveSystem;
        addresses.xauAddress = xauAddress;

        // Deploy StablecoinPegManager
        addresses.stablecoinPegManager = _deployStablecoinPegManager(addresses.reserveSystem);

        // Deploy CommodityPegManager
        addresses.commodityPegManager = _deployCommodityPegManager(addresses.reserveSystem, addresses.xauAddress);

        // Deploy ISOCurrencyManager
        addresses.isoCurrencyManager = _deployISOCurrencyManager(addresses.reserveSystem, addresses.xauAddress);

        // Deploy BridgeReserveCoordinator
        addresses.bridgeReserveCoordinator = _deployBridgeReserveCoordinator(
            addresses.bridgeSwapCoordinator,
            addresses.reserveSystem,
            addresses.stablecoinPegManager,
            addresses.commodityPegManager,
            addresses.isoCurrencyManager
        );

        // Initialize peg managers
        _initializePegManagers(
            addresses.stablecoinPegManager,
            addresses.commodityPegManager,
            addresses.isoCurrencyManager,
            addresses.xauAddress,
            deployer
        );

        vm.stopBroadcast();

        // Print deployment summary
        console.log("\n=== Deployment Summary ===");
        console.log("StablecoinPegManager:", addresses.stablecoinPegManager);
        console.log("CommodityPegManager:", addresses.commodityPegManager);
        console.log("ISOCurrencyManager:", addresses.isoCurrencyManager);
        console.log("BridgeReserveCoordinator:", addresses.bridgeReserveCoordinator);
        
        console.log("\n=== Export to .env ===");
        console.log("export STABLECOIN_PEG_MANAGER=", vm.toString(addresses.stablecoinPegManager));
        console.log("export COMMODITY_PEG_MANAGER=", vm.toString(addresses.commodityPegManager));
        console.log("export ISO_CURRENCY_MANAGER=", vm.toString(addresses.isoCurrencyManager));
        console.log("export BRIDGE_RESERVE_COORDINATOR=", vm.toString(addresses.bridgeReserveCoordinator));
    }

    function _deployStablecoinPegManager(address reserveSystem) internal returns (address) {
        console.log("\n--- Deploying StablecoinPegManager ---");
        StablecoinPegManager manager = new StablecoinPegManager(reserveSystem);
        console.log("StablecoinPegManager deployed at:", address(manager));
        return address(manager);
    }

    function _deployCommodityPegManager(address reserveSystem, address xauAddress) internal returns (address) {
        console.log("\n--- Deploying CommodityPegManager ---");
        CommodityPegManager manager = new CommodityPegManager(reserveSystem);
        if (xauAddress != address(0)) {
            vm.prank(vm.addr(vm.envUint("PRIVATE_KEY")));
            manager.setXAUAddress(xauAddress);
        }
        console.log("CommodityPegManager deployed at:", address(manager));
        return address(manager);
    }

    function _deployISOCurrencyManager(address reserveSystem, address xauAddress) internal returns (address) {
        console.log("\n--- Deploying ISOCurrencyManager ---");
        ISOCurrencyManager manager = new ISOCurrencyManager(reserveSystem);
        if (xauAddress != address(0)) {
            vm.prank(vm.addr(vm.envUint("PRIVATE_KEY")));
            manager.setXAUAddress(xauAddress);
        }
        console.log("ISOCurrencyManager deployed at:", address(manager));
        return address(manager);
    }

    function _deployBridgeReserveCoordinator(
        address bridgeSwapCoordinator,
        address reserveSystem,
        address stablecoinPegManager,
        address commodityPegManager,
        address isoCurrencyManager
    ) internal returns (address) {
        console.log("\n--- Deploying BridgeReserveCoordinator ---");
        
        BridgeReserveCoordinator coordinator = new BridgeReserveCoordinator(
            bridgeSwapCoordinator,
            reserveSystem,
            stablecoinPegManager,
            commodityPegManager,
            isoCurrencyManager
        );
        console.log("BridgeReserveCoordinator deployed at:", address(coordinator));
        return address(coordinator);
    }

    function _initializePegManagers(
        address stablecoinPegManager,
        address commodityPegManager,
        address isoCurrencyManager,
        address xauAddress,
        address deployer
    ) internal {
        console.log("\n--- Initializing Peg Managers ---");
        
        // Register USD stablecoins
        StablecoinPegManager stablecoinManager = StablecoinPegManager(stablecoinPegManager);
        uint256 usdThreshold = vm.envOr("USD_PEG_THRESHOLD_BPS", DEFAULT_USD_PEG_THRESHOLD_BPS);
        uint256 ethThreshold = vm.envOr("ETH_PEG_THRESHOLD_BPS", DEFAULT_ETH_PEG_THRESHOLD_BPS);
        
        vm.prank(deployer);
        stablecoinManager.registerUSDStablecoin(USDT);
        console.log("Registered USDT with threshold:", usdThreshold, "bps");
        
        vm.prank(deployer);
        stablecoinManager.registerUSDStablecoin(USDC);
        console.log("Registered USDC with threshold:", usdThreshold, "bps");
        
        vm.prank(deployer);
        stablecoinManager.registerWETH(WETH);
        console.log("Registered WETH with threshold:", ethThreshold, "bps");

        // Register XAU in CommodityPegManager
        CommodityPegManager commodityManager = CommodityPegManager(commodityPegManager);
        uint256 commodityThreshold = vm.envOr("COMMODITY_PEG_THRESHOLD_BPS", DEFAULT_COMMODITY_PEG_THRESHOLD_BPS);
        
        vm.prank(deployer);
        commodityManager.registerCommodity(xauAddress, "XAU", 1e18); // 1:1 for XAU
        console.log("Registered XAU with threshold:", commodityThreshold, "bps");

        // Register major ISO currencies
        ISOCurrencyManager isoManager = ISOCurrencyManager(isoCurrencyManager);
        
        // USD: 1 oz XAU = ~2000 USD (example rate, should be updated from market)
        vm.prank(deployer);
        isoManager.registerCurrency("USD", USDT, 2000e18);
        console.log("Registered USD");
        
        // EUR: 1 oz XAU = ~1800 EUR (example rate)
        vm.prank(deployer);
        isoManager.registerCurrency("EUR", address(0), 1800e18);
        console.log("Registered EUR");
        
        // GBP: 1 oz XAU = ~1500 GBP (example rate)
        vm.prank(deployer);
        isoManager.registerCurrency("GBP", address(0), 1500e18);
        console.log("Registered GBP");
        
        // Add more currencies as needed
        console.log("Peg managers initialized");
    }
}

