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

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

/**
 * @title PerformUpkeep
 * @notice Script to perform keeper upkeep
 * @dev Can be called by keeper services or manually
 */
contract PerformUpkeep is Script {
    function run() external {
        uint256 chainId = block.chainid;
        require(chainId == 138, "This script is for ChainID 138 only");

        uint256 keeperPrivateKey = vm.envUint("KEEPER_PRIVATE_KEY");
        vm.startBroadcast(keeperPrivateKey);

        address keeperAddress = vm.envAddress("PRICE_FEED_KEEPER_ADDRESS");
        PriceFeedKeeper keeper = PriceFeedKeeper(keeperAddress);

        console.log("=== Perform Keeper Upkeep ===");
        console.log("Keeper Address:", keeperAddress);
        console.log("");

        // Check if upkeep is needed
        (bool needsUpdate, address[] memory assets) = keeper.checkUpkeep();

        if (!needsUpdate || assets.length == 0) {
            console.log("No updates needed");
            vm.stopBroadcast();
            return;
        }

        console.log("Assets needing update:", assets.length);
        for (uint256 i = 0; i < assets.length; i++) {
            console.log("  ", i + 1, ":", assets[i]);
        }
        console.log("");

        // Perform upkeep
        console.log("Performing upkeep...");
        (bool success, address[] memory updatedAssets) = keeper.performUpkeep();

        if (success) {
            console.log("Upkeep successful");
            console.log("Updated assets:", updatedAssets.length);
            for (uint256 i = 0; i < updatedAssets.length; i++) {
                console.log("  ", i + 1, ":", updatedAssets[i]);
            }
        } else {
            console.log("Upkeep failed");
            revert("Upkeep failed");
        }

        vm.stopBroadcast();
    }
}

