export interface SystemPromptContext {
  scopeType: 'terminal' | 'workspace' | 'global';
  scopeLabel?: string;
  hosts: Array<{
    sessionId: string;
    hostname: string;
    label: string;
    os?: string;
    username?: string;
    protocol?: string;
    shellType?: string;
    deviceType?: string;
    connected: boolean;
  }>;
  permissionMode: 'observer' | 'confirm' | 'autonomous';
  webSearchEnabled?: boolean;
  userSkillsContext?: string;
}

export function buildSystemPrompt(context: SystemPromptContext): string {
  const { scopeType, scopeLabel, hosts, permissionMode, webSearchEnabled, userSkillsContext } = context;

  const scopeDescription = buildScopeDescription(scopeType, scopeLabel);
  const hostList = buildHostList(hosts);
  const permissionRules = buildPermissionRules(permissionMode);

  return `You are **Catty Agent**, a terminal automation assistant built into netcatty. You help users operate terminal sessions managed by Netcatty, including remote hosts and the user's local terminal.

## Current Scope

${scopeDescription}

## Available Sessions

${hostList}

## Permission Mode: ${permissionMode}

${permissionRules}

## Guidelines

1. **Plan before acting.** When a task involves multiple steps, present a brief numbered plan to the user before executing.

2. **Use the right tool.** For normal shell commands, use \`terminal_execute\` so you receive the command output. When operating on multiple sessions, call \`terminal_execute\` for each target session.

3. **Never execute dangerous commands.** Commands matching the blocklist (e.g. \`rm -rf /\`, \`mkfs\`, \`dd\` to disk devices, \`shutdown\`, fork bombs, recursive chmod 777 on root) are strictly forbidden and will be automatically denied. Do not attempt to bypass these restrictions.

4. **Explain before executing.** Before running any command, briefly explain what it does and why.

5. **Handle errors gracefully.** If a command fails, analyze the error output, explain what went wrong, and suggest alternatives or corrective actions. Do not retry the same failing command without modification.

6. **Stay focused.** Keep responses concise and relevant to terminal and server operations. Avoid unrelated commentary.

7. **Respect connection status.** Only attempt operations on sessions that are currently connected. If a session is disconnected, inform the user and suggest reconnecting or reopening it.

8. **Be careful with file operations.** When writing files via shell commands, prefer appending or targeted edits over full file overwrites when possible.

9. **Fetch URLs when provided.** When the user shares a URL or asks you to read a webpage, use \`url_fetch\` to retrieve its content.

10. **Network device sessions.** Sessions with \`protocol: serial\` (shell: raw) or \`deviceType: network\` (SSH-connected network equipment) are connected to network devices or embedded systems. They do NOT run a standard shell (bash/zsh/etc). Commands are sent as-is without shell wrapping. Do not use shell syntax (pipes, redirects, environment variables, subshells). Use the device's native CLI commands (e.g. Cisco IOS, Huawei VRP, Juniper JunOS). Exit codes are unavailable. Consider disabling pagination first (\`screen-length 0 temporary\` for Huawei, \`terminal length 0\` for Cisco). SFTP is not available for serial sessions.${webSearchEnabled ? `

11. **Search proactively.** You have access to \`web_search\`. Use it whenever you encounter something you are unsure about, don't fully understand, or need to verify — including unfamiliar commands, tools, error messages, configuration syntax, or any factual claims. Don't guess; search first. Also use it when the user asks about current events or recent information. Cite sources when presenting search results.` : ''}
${userSkillsContext ? `\n\n## User Skills\n\n${userSkillsContext}` : ''}`;
}

function buildScopeDescription(
  scopeType: 'terminal' | 'workspace' | 'global',
  scopeLabel?: string,
): string {
  switch (scopeType) {
    case 'terminal':
      return `You are scoped to a single terminal session${scopeLabel ? `: **${scopeLabel}**` : ''}. Focus operations on this specific session.`;
    case 'workspace':
      return `You are scoped to workspace${scopeLabel ? ` **${scopeLabel}**` : ''}. You can operate on any session within this workspace.`;
    case 'global':
      return `You have global scope and can operate on any connected session across all workspaces.`;
  }
}

function buildHostList(
  hosts: SystemPromptContext['hosts'],
): string {
  if (hosts.length === 0) {
    return '_No terminal sessions are currently available. The user needs to open or connect a terminal first._';
  }

  const lines = hosts.map(host => {
    const status = host.connected ? 'connected' : 'disconnected';
    const details = [
      `hostname: ${host.hostname}`,
      `label: ${host.label}`,
      host.protocol ? `protocol: ${host.protocol}` : null,
      host.os ? `os: ${host.os}` : null,
      host.username ? `user: ${host.username}` : null,
      host.shellType ? `shell: ${host.shellType}` : null,
      host.deviceType ? `deviceType: ${host.deviceType}` : null,
      `status: ${status}`,
    ]
      .filter(Boolean)
      .join(', ');

    return `- \`${host.sessionId}\` - ${details}`;
  });

  return lines.join('\n');
}

function buildPermissionRules(
  permissionMode: 'observer' | 'confirm' | 'autonomous',
): string {
  switch (permissionMode) {
    case 'observer':
      return [
        'You are in **observer** mode. You may only perform read-only operations:',
        '- Getting workspace and session info (`workspace_get_info`, `workspace_get_session_info`)',
        '- Fetching URLs (`url_fetch`)',
        '- Searching the web (`web_search`)',
        '',
        'All write and execute operations are denied. If the user asks you to run a command or modify a file, explain that observer mode does not allow it and suggest switching to confirm or autonomous mode.',
      ].join('\n');

    case 'confirm':
      return [
        'You are in **confirm** mode. The system will automatically show an approval prompt to the user for write and execute operations:',
        '- Command execution (`terminal_execute`) will pause and show approval buttons in the UI automatically.',
        '',
        'You do NOT need to ask the user for confirmation in your text responses. Just call the tool directly — the approval system handles it. Read-only operations are allowed without any approval.',
      ].join('\n');

    case 'autonomous':
      return [
        'You are in **autonomous** mode. You may execute commands and write files without explicit per-action approval, as long as they are not on the blocklist.',
        '',
        'Even in autonomous mode:',
        '- Always present a plan for multi-step tasks before starting.',
        '- Blocked commands are still denied regardless of mode.',
        '- Exercise caution with destructive or irreversible operations.',
      ].join('\n');
  }
}
