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

import {Script, console2} from "forge-std/Script.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {WLPReceiptToken} from "../../contracts/wrapped-lp-public/WLPReceiptToken.sol";
import {PublicChainMintController} from "../../contracts/wrapped-lp-public/PublicChainMintController.sol";
import {WLPRedemptionGateway} from "../../contracts/wrapped-lp-public/WLPRedemptionGateway.sol";
import {WLPNAVOracle} from "../../contracts/wrapped-lp-public/WLPNAVOracle.sol";
import {WrappedLPNAVVault} from "../../contracts/wrapped-lp-public/WrappedLPNAVVault.sol";

/**
 * @title DeployWrappedLPPublicChain
 * @notice Deploy wLP stack on **public** chain (mainnet or L2). `--rpc-url` must be destination chain.
 * @dev Env: `ADMIN`, `PRIVATE_KEY`, `CHAIN138_LOCKER` (locker address for mint controller reference),
 *      optional `USDC` for vault, optional `WIRE_ROLES=1`, `RELAYER_ADDRESS`, `KEEPER_ADDRESS` (defaults to relayer).
 */
contract DeployWrappedLPPublicChain is Script {
    function run() external {
        address admin = vm.envAddress("ADMIN");
        address chain138Locker = vm.envAddress("CHAIN138_LOCKER");
        uint256 pk = vm.envUint("PRIVATE_KEY");

        vm.startBroadcast(pk);

        WLPReceiptToken wlp = new WLPReceiptToken("Wrapped LP", "wLP", 18, admin);
        console2.log("WLPReceiptToken", address(wlp));

        PublicChainMintController mintCtl = new PublicChainMintController(address(wlp), chain138Locker, admin);
        console2.log("PublicChainMintController", address(mintCtl));

        WLPRedemptionGateway gateway = new WLPRedemptionGateway(address(wlp), admin);
        console2.log("WLPRedemptionGateway", address(gateway));

        WLPNAVOracle oracle = new WLPNAVOracle(admin, 3600);
        console2.log("WLPNAVOracle", address(oracle));

        address usdc = vm.envOr("USDC", address(0));
        if (usdc != address(0)) {
            WrappedLPNAVVault vault = new WrappedLPNAVVault(
                IERC20(usdc),
                "Wrapped LP NAV Vault",
                "wLPV",
                admin
            );
            console2.log("WrappedLPNAVVault", address(vault));
        }

        if (vm.envOr("WIRE_ROLES", false)) {
            address deployer = vm.addr(pk);
            require(deployer == admin, "WIRE_ROLES requires deployer==ADMIN");
            address relayerAddr = vm.envAddress("RELAYER_ADDRESS");
            address keeperAddr = vm.envOr("KEEPER_ADDRESS", relayerAddr);

            wlp.grantRole(wlp.MINTER_ROLE(), address(mintCtl));
            wlp.grantRole(wlp.BURNER_ROLE(), address(gateway));
            mintCtl.grantRole(mintCtl.RELAYER_ROLE(), relayerAddr);
            oracle.grantRole(oracle.KEEPER_ROLE(), keeperAddr);
            console2.log("Wired MINTER/BURNER/RELAYER/KEEPER");
        }

        vm.stopBroadcast();
    }
}
