import { spawn, execSync } from 'child_process';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const AGENT_ROOT = join(__dirname, '..');
const DEFAULT_WORKSPACE = join(AGENT_ROOT, 'workspaces', 'default');

export const name = 'copilot';

export const modelMap = {
  fast: 'claude-haiku-4.5',
  balanced: 'claude-sonnet-4.5',
  powerful: 'gpt-5'
};

function resolveModel(model) {
  const key = String(model || 'balanced').trim().toLowerCase();
  if (key === 'fast' || key === 'balanced' || key === 'powerful') {
    return modelMap[key];
  }
  return String(model || modelMap.balanced);
}

// Resolved full path to the CLI binary (set by isAvailable)
let resolvedBin = 'copilot';

/**
 * Platform-aware spawn helper.
 * Uses the resolved binary path from isAvailable() to avoid ENOENT when
 * the CLI is installed in a directory not in Node's default PATH.
 */
function spawnCopilot(args, options = {}) {
  if (process.platform === 'win32') {
    return spawn('cmd.exe', ['/d', '/s', '/c', resolvedBin, ...args], {
      ...options,
      shell: false
    });
  }
  return spawn(resolvedBin, args, {
    ...options,
    shell: false
  });
}

export function isAvailable() {
  try {
    if (process.platform === 'win32') {
      resolvedBin = execSync('where copilot.cmd 2>nul || where copilot', { encoding: 'utf-8' }).trim().split(/\r?\n/)[0];
    } else {
      resolvedBin = execSync('which copilot', { encoding: 'utf-8' }).trim();
    }
    return true;
  } catch {
    return false;
  }
}

/**
 * Run Copilot CLI in non-interactive (headless) mode and return the result.
 *
 * Uses -p for prompt and -s for silent (agent response only, no usage stats).
 * Copilot CLI does not have a --json/--output-format flag — output is plain text.
 *
 * @param {string} prompt
 * @param {object} opts
 * @param {string} opts.model
 * @param {number} opts.timeout - ms before killing
 * @param {boolean} opts.sandboxed - if true (default), run in workspace/
 * @param {function} opts.onStream - callback(partialText) for streaming updates
 */
export async function ask(prompt, { model = 'balanced', timeout = 600_000, sandboxed = true, onStream } = {}) {
  return new Promise((resolve, reject) => {
    const selectedModel = resolveModel(model);
    const args = [
      '-s',               // silent: output only agent response (no usage stats)
      '-p', prompt,       // non-interactive prompt
      '--model', selectedModel,
      '--stream', 'on',
      '--no-auto-update',
      '--no-ask-user'     // autonomous: don't prompt for user input mid-task
    ];

    const proc = spawnCopilot(args, {
      cwd: sandboxed ? DEFAULT_WORKSPACE : AGENT_ROOT,
      env: { ...process.env },
      stdio: ['pipe', 'pipe', 'pipe']
    });

    let accumulatedText = '';
    let killed = false;

    const timer = setTimeout(() => {
      killed = true;
      proc.kill('SIGTERM');
      setTimeout(() => proc.kill('SIGKILL'), 5000);
    }, timeout);

    proc.stdout.on('data', (chunk) => {
      const text = chunk.toString();
      accumulatedText += text;
      if (onStream) onStream(accumulatedText);
    });

    let stderr = '';
    proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });

    proc.on('close', (code) => {
      clearTimeout(timer);
      const result = accumulatedText.trim();

      if (killed) {
        reject(new Error(`Copilot CLI timed out after ${timeout}ms`));
      } else if (code !== 0 && !result) {
        reject(new Error(`Copilot CLI exited with code ${code}\n${stderr}`));
      } else if (code === 0 && !result) {
        reject(new Error(`Copilot CLI returned empty output\n${stderr}`.trim()));
      } else {
        resolve(result);
      }
    });

    proc.on('error', (err) => {
      clearTimeout(timer);
      reject(new Error(`Copilot CLI spawn error: ${err.message}`));
    });

    proc.stdin.end();
  });
}

/**
 * Spawn Copilot in interactive mode (for meta-develop).
 * Returns the spawned child process.
 */
export function spawnInteractive({ cwd, model = 'balanced' } = {}) {
  const selectedModel = resolveModel(model);
  return spawnCopilot([
    '--model', selectedModel,
    '--yolo'  // auto-approve all tool calls
  ], {
    cwd: cwd || DEFAULT_WORKSPACE,
    env: { ...process.env },
    stdio: ['pipe', 'pipe', 'pipe']
  });
}
