package ai.testers.junit5;

import ai.testers.AnalysisResult;
import ai.testers.Config;
import ai.testers.Sinks;
import ai.testers.TestersAI;
import org.junit.jupiter.api.extension.*;

import java.util.List;
import java.util.function.Consumer;

/**
 * JUnit 5 extension. Inject {@link TestersAIFacade} into your tests:
 *
 * <pre>{@code
 *   @ExtendWith(TestersAIExtension.class)
 *   class MyTest {
 *     @Test void t(TestersAIFacade ta) { ta.screenshot(path); }
 *   }
 * }</pre>
 */
public final class TestersAIExtension implements ParameterResolver, AfterTestExecutionCallback {

    private static final ExtensionContext.Namespace NS = ExtensionContext.Namespace.create("testersai");

    @Override
    public boolean supportsParameter(ParameterContext pc, ExtensionContext ec) {
        return pc.getParameter().getType() == TestersAIFacade.class;
    }

    @Override
    public Object resolveParameter(ParameterContext pc, ExtensionContext ec) {
        Config cfg = Config.fromEnv();
        TestersAI client = new TestersAI(cfg);
        Consumer<AnalysisResult> log = r -> ec.publishReportEntry(
                "testersai:" + r.kind,
                "ok=" + r.ok + " skipped=" + r.skipped + " issues=" + r.issues.size());
        List<Consumer<AnalysisResult>> sinks = Sinks.build(cfg, log);
        TestersAIFacade f = new TestersAIFacade(client, sinks);
        ec.getStore(NS).put("facade", f);
        return f;
    }

    @Override
    public void afterTestExecution(ExtensionContext ec) { /* nothing mandatory */ }
}
