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

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

  if (state.mode === 'quick') {
    state.tools.gitProviders = [];
    state.tools.credentialsLocation = DEFAULTS.credentialsLocation;
    state.tools.customToolsSection = DEFAULTS.customToolsSection;
    return;
  }

  p.separator();
  p.note(
    'Tool configuration tells agents about your git providers,\n' +
      'credential locations, and custom tools.\n' +
      'This creates TOOLS.md.',
    'Tool Reference',
  );

  const addProviders = await p.confirm({
    message: 'Configure git providers?',
    initialValue: false,
  });

  state.tools.gitProviders = [];
  if (addProviders) {
    let addMore = true;
    while (addMore) {
      const name = await p.text({
        message: 'Provider name',
        placeholder: 'e.g., Gitea, GitHub',
      });
      const url = await p.text({
        message: 'Provider URL',
        placeholder: 'e.g., https://github.com',
      });
      const cli = await p.select<string>({
        message: 'CLI tool',
        options: [
          { value: 'gh', label: 'gh (GitHub CLI)' },
          { value: 'tea', label: 'tea (Gitea CLI)' },
          { value: 'glab', label: 'glab (GitLab CLI)' },
        ],
      });
      const purpose = await p.text({
        message: 'Purpose',
        placeholder: 'e.g., Primary code hosting',
        defaultValue: 'Code hosting',
      });

      state.tools.gitProviders.push({
        name,
        url,
        cli,
        purpose,
      } satisfies GitProvider);

      addMore = await p.confirm({
        message: 'Add another provider?',
        initialValue: false,
      });
    }
  }

  state.tools.credentialsLocation = await p.text({
    message: 'Credential file path',
    placeholder: "e.g., ~/.secrets/credentials.env, or 'none'",
    defaultValue: DEFAULTS.credentialsLocation,
  });
}
