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

import "forge-std/Script.sol";
import {RWATokenFactory} from "../../../contracts/rwa/RWATokenFactory.sol";
import {RWATokenRegistry} from "../../../contracts/rwa/RWATokenRegistry.sol";
import {PolicyProfileRegistry} from "../../../contracts/universal-resource/PolicyProfileRegistry.sol";
import {OMNLJurisdictionPolicyRegistry} from "../../../contracts/hybx-omnl/OMNLJurisdictionPolicyRegistry.sol";

/**
 * @title WireRWATokenFactoryWeb3Controls138
 * @notice Post-deploy: C-W3-01 jurisdiction policy, C-W3-08 profile hash, C-W3-04 multisig roles, C-W3-07 governance admin.
 * Env: RWA_TOKEN_FACTORY, RWA_TOKEN_REGISTRY, POLICY_PROFILE_REGISTRY, OMNL_JURISDICTION_REGISTRY,
 *      ID_JURISDICTION_POLICY_HASH, M00_PROFILE_CONTENT_HASH, OMNL_COMPLIANCE_MULTISIG, GOVERNANCE_CONTROLLER
 */
contract WireRWATokenFactoryWeb3Controls138 is Script {
    function run() external {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address factoryAddr = vm.envAddress("RWA_TOKEN_FACTORY");
        address multisig = vm.envOr("OMNL_COMPLIANCE_MULTISIG", vm.envOr("MULTISIG_ADMIN", address(0)));
        address governance = vm.envOr("GOVERNANCE_CONTROLLER", address(0));

        vm.startBroadcast(pk);

        RWATokenFactory factory = RWATokenFactory(factoryAddr);

        if (multisig != address(0)) {
            if (!factory.hasRole(factory.DEPLOYER_ROLE(), multisig)) {
                factory.grantRole(factory.DEPLOYER_ROLE(), multisig);
            }
            console.log("DEPLOYER_ROLE ->", multisig);
        }

        if (governance != address(0)) {
            if (!factory.hasRole(factory.DEFAULT_ADMIN_ROLE(), governance)) {
                factory.grantRole(factory.DEFAULT_ADMIN_ROLE(), governance);
            }
            console.log("DEFAULT_ADMIN_ROLE ->", governance);
        }

        address pprAddr = vm.envOr("POLICY_PROFILE_REGISTRY", address(0));
        if (pprAddr != address(0)) {
            bytes32 profileHash = vm.envBytes32("M00_PROFILE_CONTENT_HASH");
            PolicyProfileRegistry(pprAddr).publishProfile(
                "m00_commodity_index_v1",
                profileHash,
                1,
                block.timestamp
            );
            console.log("Published m00_commodity_index_v1 on PolicyProfileRegistry");
        }

        address jurAddr = vm.envOr("OMNL_JURISDICTION_REGISTRY", address(0));
        if (jurAddr != address(0)) {
            bytes32 idPolicyHash = vm.envBytes32("ID_JURISDICTION_POLICY_HASH");
            bytes32 jurisdictionId = keccak256("ID");
            OMNLJurisdictionPolicyRegistry(jurAddr).publishPolicy(
                jurisdictionId,
                idPolicyHash,
                3,
                2,
                2,
                true
            );
            console.log("Published ID jurisdiction policy");
        }

        vm.stopBroadcast();
    }
}
