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

import {Script, console2} from "forge-std/Script.sol";
import "../../../contracts/bridge/trustless/integration/Stabilizer.sol";
import "../../../contracts/bridge/trustless/integration/StablecoinPegManager.sol";
import "../../../contracts/bridge/trustless/integration/CommodityPegManager.sol";

/// @notice Deploy peg managers + Stabilizer on Chain 138 (Defi Oracle Meta).
/// @dev Requires PRIVATE_KEY, RESERVE_SYSTEM, PRIVATE_POOL_REGISTRY; optional STABILIZER_ADMIN, XAU peg asset.
contract DeployChain138StabilizerStack is Script {
    function run() external {
        require(block.chainid == 138, "chain138 only");

        uint256 pk = vm.envUint("PRIVATE_KEY");
        address deployer = vm.addr(pk);
        address admin = vm.envOr("STABILIZER_ADMIN", deployer);
        address reserveSystem = vm.envAddress("RESERVE_SYSTEM");
        address privatePoolRegistry = vm.envAddress("PRIVATE_POOL_REGISTRY");

        vm.startBroadcast(pk);

        StablecoinPegManager stablecoinPeg = new StablecoinPegManager(reserveSystem);
        CommodityPegManager commodityPeg = new CommodityPegManager(reserveSystem);

        address cUsdc = vm.envOr("COMPLIANT_USDC_ADDRESS", vm.envOr("CUSDC_ADDRESS_138", address(0)));
        address cUsdt = vm.envOr("COMPLIANT_USDT_ADDRESS", vm.envOr("CUSDT_ADDRESS_138", address(0)));
        address weth = vm.envOr("WETH9", address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2));
        address xau = vm.envOr("XAU_ADDRESS_138", vm.envOr("cXAUC_ADDRESS_138", address(0x290E52a8819A4fbD0714E517225429aA2B70EC6b)));

        if (cUsdc != address(0)) {
            stablecoinPeg.registerUSDStablecoin(cUsdc);
        }
        if (cUsdt != address(0)) {
            stablecoinPeg.registerUSDStablecoin(cUsdt);
        }
        stablecoinPeg.registerWETH(weth);

        if (xau != address(0)) {
            commodityPeg.setXAUAddress(xau);
            commodityPeg.registerCommodity(xau, "XAU", 1e18);
        }

        Stabilizer stabilizer = new Stabilizer(admin, privatePoolRegistry);
        stabilizer.setStablecoinPegSource(address(stablecoinPeg), cUsdc != address(0) ? cUsdc : cUsdt);
        if (xau != address(0)) {
            stabilizer.setCommodityPegSource(address(commodityPeg), xau);
        }

        vm.stopBroadcast();

        console2.log("StablecoinPegManager", address(stablecoinPeg));
        console2.log("CommodityPegManager", address(commodityPeg));
        console2.log("Stabilizer", address(stabilizer));
        console2.log("admin", admin);
    }
}
