package com.ai.trackwalker.capability.uav;

import java.util.Map;
import java.util.Set;

public final class MissionStateMachine {
    private static final Map<String, Set<String>> TRANSITIONS = Map.ofEntries(
            Map.entry("READY", Set.of("DISPATCHING", "CANCELLED")),
            Map.entry("DISPATCHING", Set.of("DISPATCHED", "DISPATCH_FAILED")),
            Map.entry("DISPATCHED", Set.of("PREPARING", "FLYING", "CANCELLED")),
            Map.entry("PREPARING", Set.of("FLYING", "FAILED", "CANCELLED")),
            Map.entry("FLYING", Set.of("PAUSED", "RETURNING", "UPLOADING", "COMPLETED", "ABORTED", "FAILED")),
            Map.entry("PAUSED", Set.of("FLYING", "RETURNING", "CANCELLED", "ABORTED")),
            Map.entry("RETURNING", Set.of("UPLOADING", "COMPLETED", "FAILED")),
            Map.entry("UPLOADING", Set.of("COMPLETED", "FAILED"))
    );

    private MissionStateMachine() {
    }

    public static boolean canTransition(String from, String to) {
        if (from == null || to == null || from.equals(to)) {
            return from != null && from.equals(to);
        }
        return TRANSITIONS.getOrDefault(from, Set.of()).contains(to);
    }

    public static String targetForCommand(String current, String command) {
        return switch (command.toUpperCase()) {
            case "MISSION_START" -> "FLYING";
            case "MISSION_PAUSE" -> "PAUSED";
            case "MISSION_RESUME" -> "FLYING";
            case "MISSION_CANCEL" -> "CANCELLED";
            case "RETURN_HOME" -> "RETURNING";
            case "MISSION_COMPLETE" -> "COMPLETED";
            case "SIMULATE_PROGRESS" -> current;
            default -> throw new IllegalArgumentException("不支持的飞行任务命令: " + command);
        };
    }
}
