package org.openautonomousconnection.webserver;

import dev.unlegitdqrk.unlegitlibrary.network.system.utils.Transport;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.*;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebRequestPacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebResponsePacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream.WebStreamChunkPacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream.WebStreamEndPacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream.WebStreamStartPacket;
import org.openautonomousconnection.protocol.side.web.ConnectedWebClient;
import org.openautonomousconnection.protocol.side.web.ProtocolWebServer;
import org.openautonomousconnection.protocol.side.web.managers.RuleManager;
import org.openautonomousconnection.protocol.side.web.managers.SessionManager;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.webserver.api.SessionContext;
import org.openautonomousconnection.webserver.runtime.JavaPageDispatcher;

import java.io.*;
import java.nio.file.Files;
import java.util.*;

@ProtocolInfo(protocolSide = ProtocolVersion.ProtocolSide.WEB)
public final class WebServer extends ProtocolWebServer {

    private static final int STREAM_CHUNK_SIZE = 64 * 1024;
    private static final long STREAM_THRESHOLD = 2L * 1024 * 1024;

    public WebServer(File authFile, File rulesFile, int tcpPort, int udpPort,
                     int sessionExpire, int maxUpload) throws Exception {
        super(authFile, rulesFile, tcpPort, udpPort, sessionExpire, maxUpload);
    }

    @Override
    public WebResponsePacket onWebRequest(ConnectedWebClient client, WebRequestPacket request) {
        try {
            String path = request.getPath() == null ? "/" : request.getPath();

            if (RuleManager.isDenied(path)) return new WebResponsePacket(403, "text/plain", Map.of(), "Forbidden".getBytes());

            if (RuleManager.requiresAuth(path)) {
                SessionContext ctx = SessionContext.from(client, this, request.getHeaders());
                if (!ctx.isValid()) return new WebResponsePacket(401, "text/plain", Map.of(), "Authentication required".getBytes());
            }

            WebResponsePacket javaResp = JavaPageDispatcher.dispatch(client, this, request);
            if (javaResp != null) return javaResp;

            return serveFile(client, path);

        } catch (Exception e) {
            return new WebResponsePacket(500, "text/plain", Map.of(), ("Internal Error: " + e.getMessage()).getBytes());
        }
    }

    private WebResponsePacket serveFile(ConnectedWebClient client, String path) throws Exception {
        if (path.startsWith("/")) path = path.substring(1);
        if (path.isEmpty()) path = "index.html";

        File root = getContentFolder().getCanonicalFile();
        File file = new File(root, path).getCanonicalFile();

        if (!file.getPath().startsWith(root.getPath())) return new WebResponsePacket(403, "text/plain", Map.of(), "Forbidden".getBytes());
        if (!file.exists() || !file.isFile()) return new WebResponsePacket(404, "text/plain", Map.of(), "Not found".getBytes());

        String contentType = ContentTypeResolver.resolve(file.getName());
        long size = file.length();

        if (size >= STREAM_THRESHOLD) {
            streamFile(client, file, contentType);
            return null;
        }

        byte[] data = Files.readAllBytes(file.toPath());
        return new WebResponsePacket(200, contentType, Map.of(), data);
    }

    private void streamFile(ConnectedWebClient client, File file, String contentType) throws IOException, ClassNotFoundException {
        long total = file.length();

        client.getConnection().sendPacket(new WebStreamStartPacket(200, contentType, Map.of("name", file.getName()), total), Transport.TCP);

        try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buf = new byte[STREAM_CHUNK_SIZE];
            int seq = 0;
            int r;
            while ((r = in.read(buf)) != -1) {
                byte[] chunk = (r == buf.length) ? buf : Arrays.copyOf(buf, r);
                client.getConnection().sendPacket(new WebStreamChunkPacket(seq++, chunk),
                        ContentTypeResolver.isVideoFile(file.getName()) ? Transport.UDP : Transport.TCP);
            }
        }

        client.getConnection().sendPacket(new WebStreamEndPacket(true), Transport.TCP);
    }
}
