import type { WizardPrompter } from '../prompter/interface.js';
import type { WizardState } from '../types.js';
import { DEFAULTS } from '../constants.js';
import { buildCommunicationPrefs } from '../template/builders.js';

export async function userSetupStage(p: WizardPrompter, state: WizardState): Promise<void> {
  if (state.installAction === 'keep') return;

  p.separator();
  p.note(
    'Your user profile helps agents understand your context,\n' +
      'accessibility needs, and communication preferences.\n' +
      'This creates USER.md.',
    'User Profile',
  );

  if (!state.user.userName) {
    state.user.userName = await p.text({
      message: 'Your name',
      placeholder: 'How agents should address you',
      defaultValue: '',
    });
  }

  if (!state.user.pronouns) {
    state.user.pronouns = await p.text({
      message: 'Your pronouns',
      placeholder: 'e.g., He/Him, She/Her, They/Them',
      defaultValue: DEFAULTS.pronouns,
    });
  }

  // Auto-detect timezone
  let detectedTz: string;
  try {
    detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
  } catch {
    detectedTz = DEFAULTS.timezone;
  }

  if (!state.user.timezone) {
    state.user.timezone = await p.text({
      message: 'Your timezone',
      placeholder: `e.g., ${detectedTz}`,
      defaultValue: detectedTz,
    });
  }

  if (state.mode === 'advanced') {
    state.user.background = await p.text({
      message: 'Professional background (brief)',
      placeholder: 'e.g., Full-stack developer, 10 years TypeScript/React',
      defaultValue: DEFAULTS.background,
    });

    state.user.accessibilitySection = await p.text({
      message: 'Neurodivergence / accessibility accommodations',
      placeholder: 'e.g., ADHD-friendly chunking, or press Enter to skip',
      defaultValue: DEFAULTS.accessibilitySection,
    });

    state.user.personalBoundaries = await p.text({
      message: 'Personal boundaries for agents',
      placeholder: 'e.g., No unsolicited career advice, or press Enter to skip',
      defaultValue: DEFAULTS.personalBoundaries,
    });
  } else {
    state.user.background = DEFAULTS.background;
    state.user.accessibilitySection = DEFAULTS.accessibilitySection;
    state.user.personalBoundaries = DEFAULTS.personalBoundaries;
  }

  // Derive communication preferences from SOUL style
  state.user.communicationPrefs = buildCommunicationPrefs(
    state.soul.communicationStyle ?? 'direct',
  );
}
