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;

/**
 * Adversarial coverage for claimed AFP fail-closed / PostConstruct rules.
 */
class AllocationCoverageBugHuntTest {

    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 COMMON_TAIL = """
            class StateMachine { public void sendEvent(OrderEvent e) {} }
            enum OrderEvent { PAY, SHIP, CANCEL }
            enum OrderState { NEW, PAID, SHIPPED, CANCELLED }
            class OrderStateMachineConfig {}
            """;

    @Test
    void postConstructUniqueFieldWriteResolves(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            import javax.annotation.PostConstruct;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay() { dispatcher.fire(); }
            }
            class Dispatcher {
                StateMachine machine;
                RichEvent carrier;
                @PostConstruct
                void init() {
                    this.carrier = new PayRichEvent();
                }
                void fire() {
                    machine.sendEvent(OrderEvent.valueOf(carrier.getA()));
                }
            }
            interface RichEvent { String getA(); }
            class PayRichEvent implements RichEvent {
                public String getA() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getA() { return OrderEvent.SHIP.name(); }
            }
            """ + COMMON_TAIL;
        assertResolvedPay(source, tempDir);
    }

    @Test
    void sameTypeMultiFieldWriteStaysFailClosed(@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;
                RichEvent carrier;
                void fire(RichEvent e) {
                    this.carrier = e;
                    this.carrier = new PayRichEvent();
                    machine.sendEvent(OrderEvent.valueOf(carrier.getA()));
                }
            }
            interface RichEvent { String getA(); }
            class PayRichEvent implements RichEvent {
                public String getA() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getA() { return OrderEvent.SHIP.name(); }
            }
            """ + COMMON_TAIL;
        assertFailClosed(source, "pay", tempDir);
    }

    @Test
    void sequentialLocalReassignmentLastWriteWins(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay() { dispatcher.fire(); }
            }
            class Dispatcher {
                StateMachine machine;
                void fire() {
                    RichEvent e = new PayRichEvent();
                    e = new ShipRichEvent();
                    machine.sendEvent(OrderEvent.valueOf(e.getA()));
                }
            }
            interface RichEvent { String getA(); }
            class PayRichEvent implements RichEvent {
                public String getA() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getA() { return OrderEvent.SHIP.name(); }
            }
            """ + COMMON_TAIL;
        assertResolvedShip(source, tempDir);
    }

    @Test
    void branchingLocalAssignmentStaysFailClosed(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay(boolean flag) { dispatcher.fire(flag); }
            }
            class Dispatcher {
                StateMachine machine;
                void fire(boolean flag) {
                    RichEvent e;
                    if (flag) {
                        e = new PayRichEvent();
                    } else {
                        e = new ShipRichEvent();
                    }
                    machine.sendEvent(OrderEvent.valueOf(e.getA()));
                }
            }
            interface RichEvent { String getA(); }
            class PayRichEvent implements RichEvent {
                public String getA() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getA() { return OrderEvent.SHIP.name(); }
            }
            """ + COMMON_TAIL;
        assertFailClosed(source, "pay", tempDir);
    }

    @Test
    void cicTernaryDifferentConcretesStaysFailClosed(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay(boolean flag) { dispatcher.fire(flag); }
            }
            class Dispatcher {
                StateMachine machine;
                void fire(boolean flag) {
                    RichEvent e = flag ? new PayRichEvent() : new ShipRichEvent();
                    machine.sendEvent(OrderEvent.valueOf(e.getA()));
                }
            }
            interface RichEvent { String getA(); }
            class PayRichEvent implements RichEvent {
                public String getA() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getA() { return OrderEvent.SHIP.name(); }
            }
            """ + COMMON_TAIL;
        assertFailClosed(source, "pay", tempDir);
    }

    private static void assertResolvedPay(String source, Path tempDir) throws Exception {
        assertResolvedEvent(source, tempDir, "pay", EVENT_TYPE + ".PAY", "PAY");
    }

    private static void assertResolvedShip(String source, Path tempDir) throws Exception {
        assertResolvedEvent(source, tempDir, "pay", EVENT_TYPE + ".SHIP", "SHIP");
    }

    private static void assertResolvedEvent(
            String source,
            Path tempDir,
            String entryMethod,
            String expectedEventFqn,
            String expectedToken) 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",
                entryMethod,
                "com.example.StateMachine",
                "sendEvent",
                MACHINE_CONFIG,
                EVENT_TYPE,
                STATE_TYPE,
                expectedEventFqn,
                EngineKind.JDT,
                pay,
                ship,
                cancel);
        assertThat(linked.getLinkResolution()).isEqualTo(LinkResolution.RESOLVED);
        assertThat(linked.getTriggerPoint().getPolymorphicEvents())
                .filteredOn(pe -> pe != null && (pe.contains("PAY") || pe.contains("SHIP") || pe.contains("CANCEL")))
                .allMatch(pe -> pe.contains(expectedToken));
    }

    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);
    }
}
