import type { WizardPrompter } from '../prompter/interface.js';
import type { AgentIntent, WizardState } from '../types.js';
import { INTENT_PRESETS } from '../constants.js';

/**
 * Agent intent + naming stage — deterministic (no LLM required).
 *
 * The user picks an intent category from presets, the system proposes a
 * thematic name, and the user confirms or overrides it.
 *
 * In headless mode, reads from `MOSAIC_AGENT_INTENT` and `MOSAIC_AGENT_NAME`.
 */
export async function agentIntentStage(p: WizardPrompter, state: WizardState): Promise<void> {
  const isHeadless = process.env['MOSAIC_ASSUME_YES'] === '1' || !process.stdin.isTTY;

  if (isHeadless) {
    const intentEnv = process.env['MOSAIC_AGENT_INTENT'] ?? 'general';
    const nameEnv = process.env['MOSAIC_AGENT_NAME'];
    const preset = INTENT_PRESETS[intentEnv] ?? INTENT_PRESETS['general']!;
    state.agentIntent ??= (intentEnv in INTENT_PRESETS ? intentEnv : 'general') as AgentIntent;
    // Respect existing agentName (e.g. from CLI overrides) — only set from
    // env/preset if not already populated.
    state.soul.agentName ??= nameEnv ?? preset.suggestedName;
    return;
  }

  p.separator();
  p.note(
    'Tell us what this agent will primarily help you with.\n' +
      "We'll suggest a name based on your choice — you can always change it.",
    'Agent Identity',
  );

  const intentOptions = Object.entries(INTENT_PRESETS).map(([value, info]) => ({
    value: value as AgentIntent,
    label: info.label,
    hint: info.hint,
  }));

  const intent = await p.select<AgentIntent>({
    message: 'What will this agent primarily help you with?',
    options: intentOptions,
    initialValue: 'general' as AgentIntent,
  });

  state.agentIntent = intent;

  const preset = INTENT_PRESETS[intent];
  const suggestedName = preset?.suggestedName ?? 'Mosaic';

  const name = await p.text({
    message: `Your agent will be named "${suggestedName}". Press Enter to accept or type a new name`,
    initialValue: suggestedName,
    defaultValue: suggestedName,
    validate: (v) => {
      if (v.length === 0) return 'Name cannot be empty';
      if (v.length > 50) return 'Name must be under 50 characters';
      return undefined;
    },
  });

  state.soul.agentName = name;
  p.log(`Agent name set to: ${name}`);
}
