package org.example.klab;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.integratedmodelling.common.configuration.CommonConfiguration;
import org.integratedmodelling.common.services.client.engine.EngineImpl;
import org.integratedmodelling.klab.api.Klab;
import org.integratedmodelling.klab.api.knowledge.SemanticType;
import org.integratedmodelling.klab.api.knowledge.observation.Observation;
import org.integratedmodelling.klab.api.scope.ContextScope;
import org.integratedmodelling.klab.api.services.Reasoner;
import org.integratedmodelling.klab.api.services.RuntimeService;

public final class ObserveQuality {
    public static void main(String[] args) throws Exception {
        if (args.length == 0 || "--help".equals(args[0])) {
            System.out.println("ObserveQuality RUNTIME_ID [TWIN_ID [SUBJECT_ID 'QUALITY']]");
            System.out.println("One argument lists twins. Two list root observations. Four submit a quality.");
            return;
        }
        if (args.length != 1 && args.length != 2 && args.length != 4) {
            throw new IllegalArgumentException("Use --help for the supported arguments.");
        }

        Klab.INSTANCE.setConfiguration(new CommonConfiguration());
        var available = new CompletableFuture<RuntimeService>();
        var engine = new EngineImpl(null, (service, status) -> {
            if (service instanceof RuntimeService runtime && args[0].equals(runtime.serviceId())
                    && status.isOperational()) {
                available.complete(runtime);
            }
        });
        try {
            var user = engine.authenticate();
            if (user == null || user.getUser() == null || user.getUser().isAnonymous()
                    || !user.getUser().isAuthenticated()) {
                throw new IllegalStateException("Configure the intended user's certificate first.");
            }
            engine.boot();
            for (var runtime : user.getServices(RuntimeService.class)) {
                if (args[0].equals(runtime.serviceId()) && runtime.status().isOperational()) {
                    available.complete(runtime);
                    break;
                }
            }
            var runtime = available.get(60, TimeUnit.SECONDS);
            if (args.length == 1) {
                for (var info : runtime.getContextInfo(user)) {
                    var configuration = info.getConfiguration();
                    System.out.printf("%s  %s%n", configuration.getId(), configuration.getName());
                }
                return;
            }

            var configuration = runtime.getConfiguration(args[1], user);
            if (configuration == null || configuration.isEmpty() || !args[1].equals(configuration.getId())) {
                throw new IllegalArgumentException("The selected Runtime could not return that twin.");
            }
            var twin = user.connect(configuration);
            if (twin == null) {
                throw new IllegalStateException("Check access rights and Runtime status.");
            }
            if (args.length == 2) {
                for (var observation : twin.getObservations()) {
                    System.out.printf("%d  %s%n", observation.getId(), observation.getUrn());
                }
                return;
            }

            var submission = submit(twin, Long.parseLong(args[2]), args[3]);
            Observation result;
            try {
                result = submission.get(2, TimeUnit.MINUTES);
            } catch (TimeoutException timeout) {
                throw new IllegalStateException("Inspect the twin's activity before retrying the submission.", timeout);
            }
            result.getNotifications().forEach(n -> System.out.println(n.getMessage()));
            if (result.isEmpty()) {
                throw new IllegalStateException("The request returned an empty observation.");
            }
            System.out.printf("Observation %d in twin %s: %s%n",
                    result.getId(), twin.getId(), result.getObservable().getUrn());
        } finally {
            engine.shutdown();
        }
    }

    /** Submit a quality in the geometry of a specific, existing subject in this twin. */
    public static CompletableFuture<Observation> submit(ContextScope twin, long subjectId, String declaration) {
        var subject = twin.getObservation(subjectId);
        if (subject == null || subject.isEmpty() || subject.getObservable() == null
                || subject.getObservable().getSemantics() == null || !subject.getObservable().is(SemanticType.SUBJECT)
                || subject.getObservable().getSemantics().isCollective()
                || subject.getGeometry() == null || subject.getGeometry().isEmpty()) {
            throw new IllegalArgumentException("Choose a visible individual subject with geometry.");
        }
        var context = twin.within(subject);
        var reasoner = context.getService(Reasoner.class);
        if (reasoner == null) {
            throw new IllegalStateException("The context has no available Reasoner.");
        }
        var quality = reasoner.resolveObservable(declaration);
        if (quality == null || quality.getSemantics() == null || !quality.is(SemanticType.QUALITY)
                || quality.is(SemanticType.NOTHING)) {
            throw new IllegalArgumentException("Choose a quality recognized by this worldview.");
        }
        return context.observation(quality).geometry(subject.getGeometry()).submit();
    }
}
