import { spawn } from 'node:child_process';
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { i as inquirer } from './index6.mjs';
import ora from './index8.mjs';
import { i18n } from './index2.mjs';
import { i as isDeviceBound, g as getBindingStatus, b as bindDevice } from '../shared/ccjk.DcMvE7lf.mjs';
import { l as logger } from '../shared/ccjk.8oaxX4iR.mjs';
import 'node:readline';
import '../shared/ccjk.BAGoDD49.mjs';
import 'stream';
import 'node:tty';
import 'node:process';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import '../shared/ccjk.DeWpAShp.mjs';
import 'node:url';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.D0g2ABGg.mjs';
import './constants.mjs';
import '../shared/ccjk.D6ycHbak.mjs';
import './fs-operations.mjs';
import 'node:fs/promises';
import 'node:buffer';
import './index5.mjs';

const DAEMON_CONFIG_PATH = join(homedir(), ".ccjk", "daemon.json");
async function setupRemote(options = {}) {
  const { nonInteractive = false, json = false, serverUrl, authToken, bindingCode } = options;
  if (!json) {
    console.log(i18n.t("remote:setup.title"));
  }
  let config = await ensureRemoteEnabled({ quiet: true, nonInteractive, serverUrl });
  if (!config) {
    if (json) {
      const result = {
        success: false,
        error: i18n.t("remote:setup.failed_enable")
      };
      console.log(JSON.stringify(result, null, 2));
      process.exitCode = 1;
    }
    return;
  }
  config = await ensureAuthTokenConfigured(config, { nonInteractive, authToken });
  if (!config) {
    if (json) {
      const result = {
        success: false,
        error: i18n.t("remote:setup.failed_auth")
      };
      console.log(JSON.stringify(result, null, 2));
      process.exitCode = 1;
    }
    return;
  }
  if (!isDeviceBound()) {
    const code = await resolveBindingCode(bindingCode, nonInteractive);
    if (!code) {
      if (json) {
        const result2 = {
          success: false,
          error: i18n.t("remote:setup.failed_bind_missing_code")
        };
        console.log(JSON.stringify(result2, null, 2));
        process.exitCode = 1;
      }
      return;
    }
    const result = await bindDevice(code);
    if (!result.success) {
      if (json) {
        const setupResult2 = {
          success: false,
          error: result.error || i18n.t("remote:setup.binding_failed")
        };
        console.log(JSON.stringify(setupResult2, null, 2));
      } else {
        console.log(i18n.t("remote:setup.binding_failed"));
        if (result.error) {
          console.log(`  ${result.error}`);
        }
      }
      process.exitCode = 1;
      return;
    }
    if (!json) {
      console.log(i18n.t("remote:setup.binding_success"));
    }
  }
  await startDaemon({ silent: json });
  const daemonRunning = await isDaemonRunning();
  const bindStatus = await getBindingStatus();
  const setupResult = {
    success: daemonRunning && bindStatus.bound,
    daemonRunning,
    bound: bindStatus.bound,
    serverUrl: config.serverUrl,
    machineId: config.machineId
  };
  if (json) {
    console.log(JSON.stringify(setupResult, null, 2));
    if (!setupResult.success) {
      process.exitCode = 1;
    }
    return;
  }
  if (daemonRunning && bindStatus.bound) {
    console.log(i18n.t("remote:setup.ready"));
    await remoteStatus();
    return;
  }
  console.log(i18n.t("remote:setup.partial"));
  await remoteStatus();
}
async function enableRemote() {
  console.log(i18n.t("remote:enable.title"));
  const enabledConfig = await ensureRemoteEnabled();
  if (!enabledConfig) {
    return;
  }
  console.log(i18n.t("remote:enable.success"));
  console.log(i18n.t("remote:enable.next_steps"));
}
async function ensureRemoteEnabled(options = {}) {
  const { quiet = false, nonInteractive = false, serverUrl } = options;
  const config = loadDaemonConfig();
  if (config.enabled) {
    if (!quiet) {
      console.log(i18n.t("remote:enable.already_enabled"));
    }
    return config;
  }
  let resolvedServerUrl = serverUrl?.trim();
  if (!resolvedServerUrl && nonInteractive) {
    console.log(i18n.t("remote:setup.non_interactive_missing_server_url"));
    return null;
  }
  if (resolvedServerUrl && !isValidRemoteServerUrl(resolvedServerUrl)) {
    console.log(i18n.t("remote:setup.invalid_server_url"));
    return null;
  }
  if (!resolvedServerUrl) {
    const promptResult = await inquirer.prompt([
      {
        type: "input",
        name: "serverUrl",
        message: i18n.t("remote:enable.server_url"),
        validate: (value) => {
          const trimmed = value?.trim() || "";
          if (!trimmed) {
            return i18n.t("remote:setup.server_url_required");
          }
          if (!isValidRemoteServerUrl(trimmed)) {
            return i18n.t("remote:setup.invalid_server_url");
          }
          return true;
        }
      }
    ]);
    resolvedServerUrl = promptResult.serverUrl.trim();
  }
  const machineId = `machine-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
  const newConfig = {
    enabled: true,
    serverUrl: resolvedServerUrl,
    machineId
  };
  saveDaemonConfig(newConfig);
  return newConfig;
}
async function ensureAuthTokenConfigured(config, options = {}) {
  const { nonInteractive = false, authToken } = options;
  if (config.authToken && config.authToken.trim().length > 0 && !authToken) {
    return config;
  }
  let resolvedAuthToken = authToken?.trim();
  if (!resolvedAuthToken && config.authToken) {
    resolvedAuthToken = config.authToken.trim();
  }
  if (!resolvedAuthToken && nonInteractive) {
    console.log(i18n.t("remote:setup.non_interactive_missing_auth_token"));
    return null;
  }
  if (!resolvedAuthToken) {
    console.log(i18n.t("remote:setup.auth_token_prompt"));
    const promptResult = await inquirer.prompt([
      {
        type: "password",
        name: "authToken",
        mask: "*",
        message: i18n.t("remote:setup.auth_token"),
        validate: (value) => {
          const trimmed = value?.trim() || "";
          if (!trimmed) {
            return i18n.t("remote:setup.auth_token_required");
          }
          return true;
        }
      }
    ]);
    resolvedAuthToken = promptResult.authToken.trim();
  }
  const updated = {
    ...config,
    authToken: resolvedAuthToken
  };
  saveDaemonConfig(updated);
  return updated;
}
async function disableRemote() {
  console.log(i18n.t("remote:disable.title"));
  const config = loadDaemonConfig();
  if (!config.enabled) {
    console.log(i18n.t("remote:disable.already_disabled"));
    return;
  }
  await stopDaemon();
  config.enabled = false;
  saveDaemonConfig(config);
  console.log(i18n.t("remote:disable.success"));
}
async function remoteStatus() {
  const config = loadDaemonConfig();
  console.log(i18n.t("remote:status.title"));
  console.log(`  ${i18n.t("remote:status.enabled")}: ${config.enabled ? "\u2705" : "\u274C"}`);
  if (config.enabled) {
    console.log(`  ${i18n.t("remote:status.server")}: ${config.serverUrl}`);
    console.log(`  ${i18n.t("remote:status.machine_id")}: ${config.machineId}`);
    const daemonRunning = await isDaemonRunning();
    console.log(`  ${i18n.t("remote:status.daemon")}: ${daemonRunning ? "\u{1F7E2} Running" : "\u{1F534} Stopped"}`);
  }
}
async function doctorRemote(options = {}) {
  const { json = false } = options;
  if (!json) {
    console.log(i18n.t("remote:doctor.title"));
  }
  const config = loadDaemonConfig();
  const checks = [];
  checks.push({
    label: i18n.t("remote:doctor.checks.enabled"),
    ok: config.enabled,
    detail: config.enabled ? i18n.t("remote:doctor.enabled_yes") : i18n.t("remote:doctor.enabled_no"),
    fixHint: config.enabled ? void 0 : i18n.t("remote:doctor.fix_enable")
  });
  const hasServerUrl = !!config.serverUrl;
  checks.push({
    label: i18n.t("remote:doctor.checks.server_url"),
    ok: hasServerUrl,
    detail: hasServerUrl ? config.serverUrl : i18n.t("remote:doctor.missing"),
    fixHint: hasServerUrl ? void 0 : i18n.t("remote:doctor.fix_setup")
  });
  const hasAuthToken = !!config.authToken?.trim();
  checks.push({
    label: i18n.t("remote:doctor.checks.auth_token"),
    ok: hasAuthToken,
    detail: hasAuthToken ? i18n.t("remote:doctor.present") : i18n.t("remote:doctor.missing"),
    fixHint: hasAuthToken ? void 0 : i18n.t("remote:doctor.fix_setup")
  });
  const hasMachineId = !!config.machineId;
  checks.push({
    label: i18n.t("remote:doctor.checks.machine_id"),
    ok: hasMachineId,
    detail: hasMachineId ? config.machineId : i18n.t("remote:doctor.missing"),
    fixHint: hasMachineId ? void 0 : i18n.t("remote:doctor.fix_setup")
  });
  const bound = isDeviceBound();
  checks.push({
    label: i18n.t("remote:doctor.checks.binding"),
    ok: bound,
    detail: bound ? i18n.t("remote:doctor.bound_yes") : i18n.t("remote:doctor.bound_no"),
    fixHint: bound ? void 0 : i18n.t("remote:doctor.fix_bind")
  });
  let cloudReachable = false;
  if (hasServerUrl) {
    cloudReachable = await isServerReachable(config.serverUrl);
  }
  checks.push({
    label: i18n.t("remote:doctor.checks.cloud_health"),
    ok: hasServerUrl && cloudReachable,
    detail: hasServerUrl ? cloudReachable ? i18n.t("remote:doctor.reachable") : i18n.t("remote:doctor.unreachable") : i18n.t("remote:doctor.skipped"),
    fixHint: hasServerUrl && !cloudReachable ? i18n.t("remote:doctor.fix_network") : void 0
  });
  const daemonRunning = await isDaemonRunning();
  checks.push({
    label: i18n.t("remote:doctor.checks.daemon"),
    ok: daemonRunning,
    detail: daemonRunning ? i18n.t("remote:doctor.daemon_running") : i18n.t("remote:doctor.daemon_stopped"),
    fixHint: daemonRunning ? void 0 : i18n.t("remote:doctor.fix_daemon")
  });
  let remoteStatusDetail = i18n.t("remote:doctor.skipped");
  if (bound) {
    const bindStatus = await getBindingStatus();
    remoteStatusDetail = bindStatus.bound ? i18n.t("remote:doctor.bound_yes") : i18n.t("remote:doctor.bound_no");
  }
  const hasFailures = checks.some((check) => !check.ok);
  const doctorResult = {
    success: !hasFailures,
    checks: checks.map((check) => ({
      label: check.label,
      ok: check.ok,
      detail: check.detail,
      fixHint: check.fixHint
    })),
    bindingStatus: remoteStatusDetail
  };
  if (json) {
    console.log(JSON.stringify(doctorResult, null, 2));
    if (hasFailures) {
      process.exitCode = 1;
    }
    return;
  }
  checks.forEach((check) => {
    const icon = check.ok ? "\u2705" : "\u274C";
    const detail = check.detail ? ` (${check.detail})` : "";
    console.log(`  ${icon} ${check.label}${detail}`);
    if (!check.ok && check.fixHint) {
      console.log(`     ${i18n.t("remote:doctor.fix_prefix")}${check.fixHint}`);
    }
  });
  console.log(`  \u2139\uFE0F ${i18n.t("remote:doctor.binding_status")}: ${remoteStatusDetail}`);
  if (hasFailures) {
    console.log(i18n.t("remote:doctor.summary_failed"));
    process.exitCode = 1;
    return;
  }
  console.log(i18n.t("remote:doctor.summary_ok"));
}
async function showQRCode() {
  const config = loadDaemonConfig();
  if (!config.enabled) {
    console.log(i18n.t("remote:qr.not_enabled"));
    return;
  }
  const pairingData = {
    serverUrl: config.serverUrl,
    machineId: config.machineId,
    timestamp: Date.now()
  };
  const pairingUrl = `ccjk://pair?data=${encodeURIComponent(JSON.stringify(pairingData))}`;
  console.log(i18n.t("remote:qr.title"));
  console.log(i18n.t("remote:qr.instructions"));
  console.log();
  console.log(`  ${pairingUrl}`);
  console.log();
  console.log(i18n.t("remote:qr.manual_entry"));
  console.log(`  Server: ${config.serverUrl}`);
  console.log(`  Machine ID: ${config.machineId}`);
}
async function startDaemon(options = {}) {
  const { silent = false } = options;
  const spinner = silent ? null : ora(i18n.t("remote:daemon.starting")).start();
  try {
    if (await isDaemonRunning()) {
      if (spinner) {
        spinner.warn(i18n.t("remote:daemon.already_running"));
      }
      return;
    }
    const daemon = spawn("ccjk-daemon", ["start"], {
      detached: true,
      stdio: "ignore"
    });
    daemon.unref();
    await new Promise((resolve) => setTimeout(resolve, 2e3));
    if (await isDaemonRunning()) {
      if (spinner) {
        spinner.succeed(i18n.t("remote:daemon.started"));
      }
    } else {
      if (spinner) {
        spinner.fail(i18n.t("remote:daemon.start_failed"));
      }
      process.exitCode = 1;
    }
  } catch (error) {
    if (spinner) {
      spinner.fail(i18n.t("remote:daemon.start_error"));
    }
    logger.error("Failed to start daemon:", error);
    process.exitCode = 1;
  }
}
async function resolveBindingCode(inputCode, nonInteractive) {
  const code = inputCode?.trim();
  if (code) {
    return code;
  }
  if (nonInteractive) {
    console.log(i18n.t("remote:setup.non_interactive_missing_binding_code"));
    return null;
  }
  console.log(i18n.t("remote:setup.binding_prompt"));
  const promptResult = await inquirer.prompt([
    {
      type: "input",
      name: "bindingCode",
      message: i18n.t("remote:setup.binding_code"),
      validate: (value) => {
        const trimmed = value?.trim() || "";
        if (!trimmed) {
          return i18n.t("remote:setup.binding_code_required");
        }
        if (trimmed.length < 4) {
          return i18n.t("remote:setup.binding_code_invalid");
        }
        return true;
      }
    }
  ]);
  return promptResult.bindingCode.trim();
}
async function stopDaemon() {
  const spinner = ora(i18n.t("remote:daemon.stopping")).start();
  try {
    if (!await isDaemonRunning()) {
      spinner.warn(i18n.t("remote:daemon.not_running"));
      return;
    }
    const response = await fetch("http://127.0.0.1:37821/stop", {
      method: "POST"
    });
    if (response.ok) {
      spinner.succeed(i18n.t("remote:daemon.stopped"));
    } else {
      spinner.fail(i18n.t("remote:daemon.stop_failed"));
    }
  } catch (error) {
    spinner.fail(i18n.t("remote:daemon.stop_error"));
    logger.error("Failed to stop daemon:", error);
  }
}
async function isDaemonRunning() {
  try {
    const response = await fetch("http://127.0.0.1:37821/health", {
      signal: AbortSignal.timeout(1e3)
    });
    return response.ok;
  } catch {
    return false;
  }
}
async function isServerReachable(baseUrl) {
  try {
    const response = await fetch(`${baseUrl.replace(/\/$/, "")}/health`, {
      signal: AbortSignal.timeout(3e3)
    });
    return response.ok;
  } catch {
    return false;
  }
}
function isValidRemoteServerUrl(url) {
  try {
    const parsed = new URL(url);
    return parsed.protocol === "http:" || parsed.protocol === "https:";
  } catch {
    return false;
  }
}
function loadDaemonConfig() {
  try {
    if (existsSync(DAEMON_CONFIG_PATH)) {
      return JSON.parse(readFileSync(DAEMON_CONFIG_PATH, "utf-8"));
    }
  } catch (error) {
    logger.error("Failed to load daemon config:", error);
  }
  return {
    enabled: false,
    serverUrl: ""
  };
}
function saveDaemonConfig(config) {
  try {
    const dir = join(homedir(), ".ccjk");
    if (!existsSync(dir)) {
      mkdirSync(dir, { recursive: true });
    }
    writeFileSync(DAEMON_CONFIG_PATH, JSON.stringify(config, null, 2));
  } catch (error) {
    logger.error("Failed to save daemon config:", error);
    throw error;
  }
}

export { disableRemote, doctorRemote, enableRemote, remoteStatus, setupRemote, showQRCode, startDaemon, stopDaemon };
