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

import "forge-std/Script.sol";
import {RWATokenRegistry} from "../../../contracts/rwa/RWATokenRegistry.sol";
import {RWATokenFactory} from "../../../contracts/rwa/RWATokenFactory.sol";
import {IRWATokenFactory} from "../../../contracts/rwa/IRWATokenFactory.sol";
import {RWAToken} from "../../../contracts/rwa/RWAToken.sol";

/**
 * @title RedeployLiIndexPublisher138
 * @notice Operator recovery when Gnosis Safe co-signer keys are unavailable:
 *         deactivate Li* in registry, redeploy with deployer as INDEX_PUBLISHER, publish index level.
 *
 * Env: LI_TICKER (LiXAU|LiPMG|LiBMG1|LiBMG2|LiBMG3), PRIVATE_KEY, RWA_TOKEN_REGISTRY, RWA_TOKEN_FACTORY
 *      REBASE_INDEX_VALUE (optional), OWNER, COMPLIANCE_ADMIN, INDEX_PUBLISHER, RWA_METHODOLOGY_HASH
 */
contract RedeployLiIndexPublisher138 is Script {
    struct LiProduct {
        string indexTicker;
        string name;
        string symbol;
        string assetGroup;
        string instrumentType;
        string underlyingAsset;
        uint256 defaultIndexValue;
    }

    function run() external {
        string memory ticker = vm.envString("LI_TICKER");
        LiProduct memory p = _product(ticker);

        uint256 pk = vm.envUint("PRIVATE_KEY");
        address deployer = vm.addr(pk);
        address registryAddr = vm.envAddress("RWA_TOKEN_REGISTRY");
        address factoryAddr = vm.envAddress("RWA_TOKEN_FACTORY");
        address owner = vm.envOr("OWNER", vm.envOr("OMNL_COMPLIANCE_MULTISIG", deployer));
        address compliance = vm.envOr("COMPLIANCE_ADMIN", vm.envOr("OMNL_GNOSIS_SAFE_ADMIN", deployer));
        address publisher = vm.envOr("INDEX_PUBLISHER", deployer);
        uint256 rebaseValue = vm.envOr("REBASE_INDEX_VALUE", p.defaultIndexValue);
        bytes32 methodologyHash = vm.parseBytes32(
            vm.envOr("RWA_METHODOLOGY_HASH", string("0x6b6e599d0ba31d048b49302e263a12f0c59502f67a35100ad5c65b503b1d4b82"))
        );

        RWATokenRegistry registry = RWATokenRegistry(registryAddr);
        RWATokenFactory factory = RWATokenFactory(factoryAddr);

        vm.startBroadcast(pk);

        if (registry.isRegistered(p.indexTicker)) {
            registry.deactivateIndex(p.indexTicker);
            console.log("Deactivated", p.indexTicker, "in registry");
        }

        address token = factory.deployRWAIndex(
            IRWATokenFactory.RWAProductConfig({
                indexTicker: p.indexTicker,
                name: p.name,
                symbol: p.symbol,
                decimals: 6,
                assetClass: "Commodities",
                assetGroup: p.assetGroup,
                instrumentType: p.instrumentType,
                underlyingAsset: p.underlyingAsset,
                gruLayer: "M00",
                jurisdiction: "International",
                initialOwner: owner,
                complianceAdmin: compliance,
                indexPublisher: publisher,
                initialIndexValue: p.defaultIndexValue,
                initialSupply: 0,
                methodologyDocumentHash: methodologyHash,
                registerInUniversalAssetRegistry: false
            })
        );

        if (rebaseValue != p.defaultIndexValue) {
            RWAToken(token).updateIndexValue(rebaseValue);
        }

        vm.stopBroadcast();

        console.log("Li* redeployed", p.indexTicker, token);
        console.log("indexValue", RWAToken(token).indexValue());
        console.log("indexPublisher", publisher);
    }

    function _product(string memory ticker) internal pure returns (LiProduct memory p) {
        bytes32 h = keccak256(bytes(ticker));
        if (h == keccak256("LiXAU")) {
            return LiProduct({
                indexTicker: "LiXAU",
                name: "XAU Liquidity Index (M00)",
                symbol: "LiXAU",
                assetGroup: "Precious Metals",
                instrumentType: "Commodity Index",
                underlyingAsset: "Gold",
                defaultIndexValue: 1_000_000
            });
        }
        if (h == keccak256("LiPMG")) {
            return LiProduct({
                indexTicker: "LiPMG",
                name: "Precious Metals Group Index (M00)",
                symbol: "LiPMG",
                assetGroup: "Precious Metals",
                instrumentType: "Basket Index",
                underlyingAsset: "Precious Metals",
                defaultIndexValue: 1_000_000
            });
        }
        if (h == keccak256("LiBMG1")) {
            return LiProduct({
                indexTicker: "LiBMG1",
                name: "Base Metals Group Index 1 (M00)",
                symbol: "LiBMG1",
                assetGroup: "Industrial Metals",
                instrumentType: "Basket Index",
                underlyingAsset: "Base Metals",
                defaultIndexValue: 1_000_000
            });
        }
        if (h == keccak256("LiBMG2")) {
            return LiProduct({
                indexTicker: "LiBMG2",
                name: "Base Metals Group Index 2 (M00)",
                symbol: "LiBMG2",
                assetGroup: "Industrial Metals",
                instrumentType: "Basket Index",
                underlyingAsset: "Battery Metals",
                defaultIndexValue: 1_000_000
            });
        }
        if (h == keccak256("LiBMG3")) {
            return LiProduct({
                indexTicker: "LiBMG3",
                name: "Base Metals Group Index 3 (M00)",
                symbol: "LiBMG3",
                assetGroup: "Industrial Metals",
                instrumentType: "Basket Index",
                underlyingAsset: "Building Metals",
                defaultIndexValue: 1_000_000
            });
        }
        revert("RedeployLiIndexPublisher138: unsupported LI_TICKER");
    }
}
