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

import {Script, console} from "forge-std/Script.sol";

interface IAggregatorRefresh {
    function updateAnswer(uint256 answer) external;
}

interface IOraclePriceFeedWireUsdc {
    function setAggregator(address asset, address aggregator, uint256 multiplier) external;
    function updatePriceFeed(address asset) external;
    function aggregators(address asset) external view returns (address);
}

/// @notice Refresh stale USD/USD mirror aggregator + wire official USDC on OraclePriceFeed + sync pegged feeds.
contract RefreshChain138UsdFeedsAndWireUsdc is Script {
    uint256 internal constant MULT = 1e10;
    uint256 internal constant USD_1E8 = 100_000_000;

    address internal constant USD_AGG = 0x34EEd677b6D7CDc84FC23c7dA8480C41C776b1E0;
    address internal constant CUSDT = 0x93E66202A11B1772E55407B32B44e5Cd8eda7f22;
    address internal constant CUSDC = 0xf22258f57794CC8E06237084b353Ab30fFfa640b;
    address internal constant USDC = 0x71D6687F38b93CCad569Fa6352c876eea967201b;
    address internal constant USDT = 0x004b63A7B5b0E06f6bB6adb4a5F9f590BF3182D1;

    function run() external {
        require(block.chainid == 138, "ChainID 138 only");

        uint256 pk = vm.envUint("PRIVATE_KEY");
        address opf = vm.envAddress("ORACLE_PRICE_FEED");

        console.log("=== Refresh USD aggregator + wire official USDC ===");
        console.log("OraclePriceFeed:", opf);
        console.log("USD aggregator:", USD_AGG);

        vm.startBroadcast(pk);

        IAggregatorRefresh(USD_AGG).updateAnswer(USD_1E8);
        console.log("USD aggregator refreshed at $1.00");

        IOraclePriceFeedWireUsdc feed = IOraclePriceFeedWireUsdc(opf);
        if (feed.aggregators(USDC) == address(0)) {
            feed.setAggregator(USDC, USD_AGG, MULT);
            console.log("Wired official USDC -> USD aggregator");
        } else {
            console.log("Official USDC already wired");
        }

        if (feed.aggregators(USDT) == address(0)) {
            feed.setAggregator(USDT, USD_AGG, MULT);
            console.log("Wired official USDT -> USD aggregator");
        } else {
            console.log("Official USDT already wired");
        }

        address[4] memory assets = [CUSDT, CUSDC, USDC, USDT];
        for (uint256 i = 0; i < assets.length; i++) {
            feed.updatePriceFeed(assets[i]);
            console.log("ReserveSystem synced:", assets[i]);
        }

        vm.stopBroadcast();
        console.log("=== Done ===");
    }
}
