import { buildWorkspaceContextAppend } from './workspace-context.js';

export interface RuntimeAdapterResult {
  systemPromptAppend?: string;
  injectedSummary?: string;
}

export interface RuntimePromptAdapter {
  buildPromptContext(params: {
    groupDir: string;
    globalPromptAppend?: string;
  }): RuntimeAdapterResult;
}

export class WorkspaceRuntimePromptAdapter implements RuntimePromptAdapter {
  buildPromptContext(params: {
    groupDir: string;
    globalPromptAppend?: string;
  }): RuntimeAdapterResult {
    const workspaceContext = buildWorkspaceContextAppend(params.groupDir);
    const sections = [workspaceContext];

    const injectedSummary = sections.flatMap((section) => section.files)
      .filter((file) => !file.missing)
      .map((file) => `${file.name}:${file.injectedChars}${file.truncated ? 't' : ''}`)
      .join(', ');

    const tenantName = process.env.TENANT_NAME;
    const tenantDiscordUserId = process.env.TENANT_DISCORD_USER_ID;
    const groupFolder = process.env.NANOCLAW_GROUP_FOLDER ?? '';
    const isHooksSession = groupFolder.startsWith('hook-');

    let platformIdentity: string | undefined;
    if (tenantName || tenantDiscordUserId) {
      if (isHooksSession) {
        platformIdentity = [
          '<platform_context>',
          `Tenant owner: ${tenantName || 'unknown'}`,
          'This request was made via the Treehouse Hooks API. The caller may be any HTTP client — a desktop app, script, or service.',
          '</platform_context>',
        ].join('\n');
      } else {
        platformIdentity = [
          '<platform_context>',
          `Tenant owner: ${tenantName || 'unknown'}${tenantDiscordUserId ? ` (Discord user ID: ${tenantDiscordUserId})` : ''}`,
          'The messages you receive may come from multiple Discord users. Each <message> has a sender (display name), sender_id, and is_owner attribute. If is_owner="true" the message is from the tenant owner; if is_owner="false" it is from a guest. Always address people by their sender name.',
          '</platform_context>',
        ].join('\n');
      }
    }

    const systemPromptAppend = [
      platformIdentity,
      params.globalPromptAppend,
      ...sections.map((section) => section.text),
    ]
      .filter(Boolean)
      .join('\n\n');

    return {
      systemPromptAppend: systemPromptAppend || undefined,
      injectedSummary: injectedSummary || undefined,
    };
  }
}

export const ClaudeRuntimePromptAdapter = WorkspaceRuntimePromptAdapter;
