import { execSync } from 'child_process';
import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import { CURSORCONNECT_DIR } from './paths.js';
const LABEL = 'com.cursorconnect.service';
const LAUNCH_AGENT = join(homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
const CURSOR_CDP_SCRIPT = join(CURSORCONNECT_DIR, 'bin', 'open-cursor-cdp.sh');
export function resolveCursorconnectBin() {
    try {
        return execSync('command -v cursorconnect', { encoding: 'utf-8' }).trim();
    }
    catch {
        return 'cursorconnect';
    }
}
function launchctlLoad() {
    execSync(`launchctl bootout gui/$(id -u) "${LAUNCH_AGENT}" 2>/dev/null || true`, {
        stdio: 'ignore',
        shell: '/bin/bash',
    });
    execSync(`launchctl bootstrap gui/$(id -u) "${LAUNCH_AGENT}"`, {
        stdio: 'inherit',
        shell: '/bin/bash',
    });
}
export function isAutostartInstalled() {
    return existsSync(LAUNCH_AGENT);
}
export function installMacAutostart() {
    mkdirSync(CURSORCONNECT_DIR, { recursive: true, mode: 0o700 });
    const bin = resolveCursorconnectBin();
    const plist = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${bin}</string>
    <string>run-service</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${join(CURSORCONNECT_DIR, 'launchd.out.log')}</string>
  <key>StandardErrorPath</key>
  <string>${join(CURSORCONNECT_DIR, 'launchd.err.log')}</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
  </dict>
</dict>
</plist>
`;
    mkdirSync(join(homedir(), 'Library', 'LaunchAgents'), { recursive: true });
    writeFileSync(LAUNCH_AGENT, plist, { mode: 0o644 });
    launchctlLoad();
}
export function uninstallMacAutostart() {
    if (existsSync(LAUNCH_AGENT)) {
        try {
            execSync(`launchctl bootout gui/$(id -u) "${LAUNCH_AGENT}" 2>/dev/null || true`, {
                stdio: 'ignore',
                shell: '/bin/bash',
            });
        }
        catch {
            /* ignore */
        }
        unlinkSync(LAUNCH_AGENT);
    }
}
/** Скрипт: Cursor с CDP (порт 9222) — положите в Dock вместо обычного Cursor. */
export function installCursorCdpLauncher() {
    mkdirSync(join(CURSORCONNECT_DIR, 'bin'), { recursive: true, mode: 0o700 });
    const script = `#!/bin/bash
# Запуск Cursor с --remote-debugging-port=9222 (нужен для Cursor Connect)
open -a Cursor --args --remote-debugging-port=9222
`;
    writeFileSync(CURSOR_CDP_SCRIPT, script, { mode: 0o755 });
    return CURSOR_CDP_SCRIPT;
}
