import readline from 'node:readline/promises';
import { registerDevice, ApiError } from '../api/client';
import { detectDevice } from '../device/fingerprint';
import { writeConfig } from '../config/store';
import { AGENT_VERSION } from '../version';

export interface LoginOptions {
  apiBaseUrl?: string;
  organizationSlug?: string;
  activationToken?: string;
  deviceName?: string;
}

async function prompt(question: string): Promise<string> {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

  try {
    return (await rl.question(question)).trim();
  } finally {
    rl.close();
  }
}

export async function login(options: LoginOptions): Promise<void> {
  const apiBaseUrl = options.apiBaseUrl ?? process.env.PROMPT_AGENT_API_URL ?? 'http://127.0.0.1:8000';
  const organizationSlug = options.organizationSlug ?? (await prompt('Enter organization code: '));
  const activationToken = options.activationToken ?? (await prompt('Enter activation token: '));

  const fingerprint = detectDevice();
  const deviceName = options.deviceName ?? `${fingerprint.hostname}-${fingerprint.os}`;

  try {
    const response = await registerDevice(apiBaseUrl, {
      organizationSlug,
      activationToken,
      deviceName,
      hostname: fingerprint.hostname,
      os: fingerprint.os,
      osVersion: fingerprint.osVersion,
      agentVersion: AGENT_VERSION,
    });

    writeConfig({
      apiBaseUrl,
      organizationSlug,
      developerName: '',
      developerEmail: '',
      deviceId: response.data.device_id,
      deviceToken: response.data.device_token,
      agentVersion: AGENT_VERSION,
      enabled: true,
      excludedProjects: [],
      excludedDirectories: [],
    });

    console.log(`Logged in as device "${response.data.device_name}" (${response.data.device_id}).`);
    console.log('Run `prompt-agent install` to register the Claude Code hooks.');
  } catch (error) {
    if (error instanceof ApiError) {
      console.error(`Login failed: ${error.message}`);
    } else {
      console.error('Login failed: unexpected error.', error);
    }

    process.exitCode = 1;
  }
}
