package com.foxx.androidcast.remoteaccess;

import android.content.Context;
import android.util.Log;

import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.shell.ProcessShellFactory;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;

import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Embedded SSH/SFTP on {@code 127.0.0.1:8022} for RSSH reverse forward target.
 * Operator reaches this via bastion forwarded port (same username/password).
 */
public final class RsshLocalSshServer {
    private static final String TAG = "RsshLocalSsh";

    private static volatile SshServer server;
    private static volatile String activeUser = "";
    private static final AtomicBoolean running = new AtomicBoolean(false);

    private RsshLocalSshServer() {}

    public static boolean start(Context context, String username, String password, int port) {
        stop();
        if (context == null || username == null || username.isEmpty()
                || password == null || password.isEmpty()) {
            return false;
        }
        if (port <= 0 || port > 65535) {
            port = 8022;
        }
        final String user = username;
        final String pass = password;
        final int listenPort = port;
        try {
            RsshSecuritySetup.ensureReady(context);
            java.nio.file.Path hostKey = context.getCacheDir().toPath().resolve("rssh_host.key");
            SshServer sshd = SshServer.setUpDefaultServer();
            sshd.setHost("127.0.0.1");
            sshd.setPort(listenPort);
            sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(hostKey));
            sshd.setPasswordAuthenticator((PasswordAuthenticator) (u, p, session) ->
                    user.equals(u) && pass.equals(p));
            sshd.setShellFactory(new ProcessShellFactory("/system/bin/sh", "-"));
            sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
            sshd.start();
            server = sshd;
            activeUser = user;
            running.set(true);
            Log.i(TAG, "local SSH/SFTP listening 127.0.0.1:" + listenPort + " user=" + user);
            return true;
        } catch (Throwable e) {
            Log.e(TAG, "local SSH start failed: " + e.getMessage(), e);
            stop();
            return false;
        }
    }

    public static void stop() {
        running.set(false);
        activeUser = "";
        SshServer local = server;
        server = null;
        if (local != null) {
            try {
                local.stop(true);
            } catch (Exception e) {
                Log.d(TAG, "local SSH stop: " + e.getMessage());
            }
        }
    }

    public static boolean isRunning() {
        SshServer local = server;
        return running.get() && local != null && local.isStarted();
    }

    public static String activeUsername() {
        return activeUser != null ? activeUser : "";
    }
}
