import fs from 'node:fs';
import { readConfig } from '../config/store';
import { claudeSettingsPath } from '../config/paths';
import { pingApi, fetchStatus, ApiError } from '../api/client';
import { pendingCount } from '../storage/queue';
import { isManagedCommand } from '../hooks/install';

interface Check {
  label: string;
  ok: boolean;
  detail?: string;
}

export async function doctor(): Promise<void> {
  const checks: Check[] = [];
  const config = readConfig();

  checks.push({ label: 'Logged in', ok: !!config, detail: config ? config.organizationSlug : 'run `prompt-agent login`' });

  if (config) {
    const reachable = await pingApi(config.apiBaseUrl);
    checks.push({ label: 'API reachable', ok: reachable, detail: config.apiBaseUrl });

    if (reachable) {
      try {
        await fetchStatus(config.apiBaseUrl, config.deviceToken);
        checks.push({ label: 'Device token valid', ok: true });
      } catch (error) {
        checks.push({
          label: 'Device token valid',
          ok: false,
          detail: error instanceof ApiError ? error.message : 'unknown error',
        });
      }
    }
  }

  const settingsExists = fs.existsSync(claudeSettingsPath());
  const hooksInstalled = settingsExists && isManagedCommand(fs.readFileSync(claudeSettingsPath(), 'utf8'));
  checks.push({ label: 'Claude Code hooks installed', ok: hooksInstalled, detail: claudeSettingsPath() });

  checks.push({ label: 'Offline queue readable', ok: true, detail: `${pendingCount()} pending` });

  let allOk = true;

  for (const check of checks) {
    allOk &&= check.ok;
    console.log(`[${check.ok ? 'OK' : 'FAIL'}] ${check.label}${check.detail ? ` - ${check.detail}` : ''}`);
  }

  if (!allOk) {
    process.exitCode = 1;
  }
}
