package com.openosrs.client.scripting.examples;

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

/**
 * Combat training script.
 */
public class CombatTrainingScript extends AbstractScript {
    private final int targetNpcId;
    private final boolean eatFood;
    private final int foodId;
    private final int healthThreshold;
    
    public CombatTrainingScript(int targetNpcId, boolean eatFood, int foodId, int healthThreshold) {
        this.targetNpcId = targetNpcId;
        this.eatFood = eatFood;
        this.foodId = foodId;
        this.healthThreshold = healthThreshold;
    }
    
    @Override
    protected void run(ScriptContext context) throws Exception {
        AgentAPI api = context.getAPI();
        
        logger.info("Starting combat training script targeting NPC ID: {}", targetNpcId);
        
        while (!context.shouldStop()) {
            context.checkContinue();
            
            // Check if we need to eat
            if (eatFood && api.getHitpoints() < healthThreshold) {
                if (!eatFood(api)) {
                    logger.warn("No food available, stopping script");
                    break;
                }
                continue;
            }
            
            // If not in combat, find a target
            if (!api.isInCombat()) {
                NPC target = findTarget(api);
                if (target == null) {
                    logger.warn("No targets found");
                    sleep(2000);
                    continue;
                }
                
                // Attack the target
                logger.debug("Attacking NPC: {}", target.getName());
                api.interactWithNPC(target, "Attack").get();
                sleep(1000);
            }
            
            // Wait while in combat
            while (api.isInCombat() && !context.shouldStop()) {
                context.checkContinue();
                
                // Check if we need to eat during combat
                if (eatFood && api.getHitpoints() < healthThreshold) {
                    eatFood(api);
                }
                
                sleep(600);
            }
            
            sleep(1000);
        }
        
        logger.info("Combat training script stopped");
    }
    
    private NPC findTarget(AgentAPI api) {
        List<NPC> npcs = api.getNPCsById(targetNpcId);
        Position playerPos = api.getPlayerPosition();
        
        return npcs.stream()
            .filter(npc -> !npc.isInteracting()) // Not already in combat
            .filter(npc -> npc.getHitpoints() > 0) // Not dead
            .filter(npc -> npc.distanceToPlayer(playerPos) < 15) // Within range
            .min((n1, n2) -> Double.compare(
                n1.distanceToPlayer(playerPos), 
                n2.distanceToPlayer(playerPos)))
            .orElse(null);
    }
    
    private boolean eatFood(AgentAPI api) throws Exception {
        int foodSlot = api.findItemSlot(foodId);
        if (foodSlot == -1) {
            return false;
        }
        
        logger.debug("Eating food");
        api.useItem(foodSlot).get();
        sleep(1800); // Food delay
        return true;
    }
    
    @Override
    public ScriptMetadata getMetadata() {
        return new ScriptMetadata(
            "Combat Training",
            "Trains combat skills by fighting NPCs",
            "OpenOSRS Agent",
            "1.0",
            Arrays.asList("Combat", "Training", "PVE")
        );
    }
}