package com.openosrs.client.scripting.examples;

import com.openosrs.client.scripting.*;
import com.openosrs.client.api.*;
import java.util.Arrays;

/**
 * Simple woodcutting script.
 */
public class WoodcuttingScript extends AbstractScript {
    private static final int TREE_ID = 1278; // Oak tree
    private static final int AXE_ID = 1351; // Bronze axe
    private static final int LOG_ID = 1521; // Oak logs
    
    @Override
    protected void run(ScriptContext context) throws Exception {
        AgentAPI api = context.getAPI();
        
        logger.info("Starting woodcutting script");
        
        // Check if we have an axe
        if (!api.hasItem(AXE_ID)) {
            logger.error("No axe found in inventory");
            return;
        }
        
        while (!context.shouldStop()) {
            context.checkContinue();
            
            // If inventory is full, drop logs
            if (api.isInventoryFull()) {
                dropLogs(api);
                continue;
            }
            
            // Find a tree to cut
            GameObject tree = api.getClosestGameObject(TREE_ID);
            if (tree == null) {
                logger.warn("No trees found");
                sleep(2000);
                continue;
            }
            
            // Walk to tree if not close enough
            Position playerPos = api.getPlayerPosition();
            if (tree.distanceToPlayer(playerPos) > 1.0) {
                logger.debug("Walking to tree");
                api.walkTo(tree.getPosition()).get();
                sleep(1000);
                continue;
            }
            
            // Cut the tree
            logger.debug("Cutting tree");
            api.interactWithObject(tree, "Chop down").get();
            
            // Wait for animation to start
            waitFor(() -> api.getCurrentAnimation() != -1, 3000);
            
            // Wait for woodcutting to finish
            waitFor(() -> api.getCurrentAnimation() == -1, 10000);
            
            sleep(1000);
        }
        
        logger.info("Woodcutting script stopped");
    }
    
    private void dropLogs(AgentAPI api) throws Exception {
        logger.debug("Dropping logs");
        
        for (int i = 0; i < 28; i++) {
            Item item = api.getInventorySlot(i);
            if (item != null && item.getItemId() == LOG_ID) {
                api.dropItem(i).get();
                sleep(200);
            }
        }
    }
    
    @Override
    public ScriptMetadata getMetadata() {
        return new ScriptMetadata(
            "Woodcutting",
            "Cuts oak trees and drops logs",
            "OpenOSRS Agent",
            "1.0",
            Arrays.asList("Woodcutting", "Skilling", "AFK")
        );
    }
}