package click.kamil.springstatemachineexporter.analysis.service;

import click.kamil.springstatemachineexporter.analysis.model.CallChain;
import click.kamil.springstatemachineexporter.analysis.model.LinkResolution;
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import click.kamil.springstatemachineexporter.model.Transition;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.nio.file.Path;

import static click.kamil.springstatemachineexporter.analysis.service.CentralDispatcherTestSupport.*;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * Robustness probes for allocation-sensitive getType — cases that historically bypassed
 * or partially bypassed CIC→param narrowing.
 */
class AllocationSensitiveRobustnessPipelineTest {

    private static final String MACHINE_CONFIG = "com.example.OrderStateMachineConfig";
    private static final String EVENT_TYPE = "com.example.OrderEvent";
    private static final String STATE_TYPE = "com.example.OrderState";

    private static final String TAIL = """
            interface RichEvent { String getType(); }
            class PayRichEvent implements RichEvent {
                public String getType() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getType() { return OrderEvent.SHIP.name(); }
            }
            class StateMachine { public void sendEvent(OrderEvent e) {} }
            enum OrderEvent { PAY, SHIP, CANCEL }
            enum OrderState { NEW, PAID, SHIPPED, CANCELLED }
            class OrderStateMachineConfig {}
            """;

    @Test
    void threeHopParamForward(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Outer outer;
                public void pay() { outer.accept(new PayRichEvent()); }
            }
            class Outer {
                Mid mid;
                void accept(RichEvent e) { mid.forward(e); }
            }
            class Mid {
                Dispatcher dispatcher;
                void forward(RichEvent e) { dispatcher.fire(e); }
            }
            class Dispatcher {
                StateMachine machine;
                void fire(RichEvent e) {
                    machine.sendEvent(OrderEvent.valueOf(e.getType()));
                }
            }
            """ + TAIL;
        assertResolvedPay(source, tempDir);
    }

    @Test
    void fieldAssignedFromParamThenGetType(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay() { dispatcher.fire(new PayRichEvent()); }
            }
            class Dispatcher {
                StateMachine machine;
                void fire(RichEvent e) {
                    RichEvent carrier = e;
                    machine.sendEvent(OrderEvent.valueOf(carrier.getType()));
                }
            }
            """ + TAIL;
        assertResolvedPay(source, tempDir);
    }

    @Test
    void castThroughInterface(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay() { dispatcher.fire(new PayRichEvent()); }
            }
            class Dispatcher {
                StateMachine machine;
                void fire(Object o) {
                    RichEvent e = (RichEvent) o;
                    machine.sendEvent(OrderEvent.valueOf(e.getType()));
                }
            }
            """ + TAIL;
        assertResolvedPay(source, tempDir);
    }

    @Test
    void anonymousRichEventStaysFailClosed(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay() {
                    dispatcher.fire(new RichEvent() {
                        public String getType() { return OrderEvent.PAY.name(); }
                    });
                }
            }
            class Dispatcher {
                StateMachine machine;
                void fire(RichEvent e) {
                    machine.sendEvent(OrderEvent.valueOf(e.getType()));
                }
            }
            """ + TAIL;
        assertFailClosed(source, "pay", tempDir);
    }

    private static void assertResolvedPay(String source, Path tempDir) throws Exception {
        CodebaseContext context = scanSource(source, tempDir);
        Transition pay = transition("NEW", "PAID", EVENT_TYPE + ".PAY");
        Transition ship = transition("PAID", "SHIPPED", EVENT_TYPE + ".SHIP");
        Transition cancel = transition("NEW", "CANCELLED", EVENT_TYPE + ".CANCEL");
        CallChain linked = resolveLinkAndAssertSingleMatch(
                context,
                "com.example.ApiController",
                "pay",
                "com.example.StateMachine",
                "sendEvent",
                MACHINE_CONFIG,
                EVENT_TYPE,
                STATE_TYPE,
                EVENT_TYPE + ".PAY",
                EngineKind.JDT,
                pay,
                ship,
                cancel);
        assertThat(linked.getLinkResolution()).isEqualTo(LinkResolution.RESOLVED);
    }

    private static void assertFailClosed(String source, String entryMethod, Path tempDir) throws Exception {
        CodebaseContext context = scanSource(source, tempDir);
        Transition pay = transition("NEW", "PAID", EVENT_TYPE + ".PAY");
        Transition ship = transition("PAID", "SHIPPED", EVENT_TYPE + ".SHIP");
        CallChain raw = resolveChain(context, "com.example.ApiController", entryMethod,
                "com.example.StateMachine", "sendEvent", EngineKind.JDT);
        CallChain linked = linkChain(context, raw, MACHINE_CONFIG, EVENT_TYPE, STATE_TYPE, pay, ship);
        assertThat(linked.getMatchedTransitions()).isNullOrEmpty();
        assertThat(linked.getLinkResolution())
                .isIn(LinkResolution.AMBIGUOUS_WIDEN, LinkResolution.NO_MATCH, LinkResolution.UNRESOLVED_EXTERNAL);
    }
}
