import fs from 'fs';
import path from 'path';

const INJECTED_WORKSPACE_FILES = [
  'AGENTS.md',
  'SOUL.md',
  'IDENTITY.md',
  'USER.md',
  'BOOTSTRAP.md',
] as const;

export interface WorkspaceContextFile {
  name: string;
  injectedChars: number;
  truncated: boolean;
  missing: boolean;
}

export interface WorkspaceContextBuildResult {
  text: string;
  files: WorkspaceContextFile[];
}

export function buildWorkspaceContextAppend(
  groupDir: string,
  options: {
    maxFileChars?: number;
    maxTotalChars?: number;
    heading?: string;
    tagName?: string;
  } = {},
): WorkspaceContextBuildResult {
  const maxFileChars = options.maxFileChars ?? 8_000;
  const maxTotalChars = options.maxTotalChars ?? 24_000;
  const heading = options.heading ?? '## Project Context';
  const tagName = options.tagName ?? 'workspace_context';
  const blocks: string[] = [];
  const files: WorkspaceContextFile[] = [];
  let total = 0;

  for (const fileName of INJECTED_WORKSPACE_FILES) {
    const filePath = path.join(groupDir, fileName);
    if (!fs.existsSync(filePath)) {
      files.push({ name: fileName, injectedChars: 0, truncated: false, missing: true });
      continue;
    }

    const raw = fs.readFileSync(filePath, 'utf-8').replace(/\r\n/g, '\n').trim();
    const remaining = Math.max(0, maxTotalChars - total);
    const injected = raw.slice(0, Math.min(maxFileChars, remaining));
    const truncated = injected.length < raw.length;
    files.push({
      name: fileName,
      injectedChars: injected.length,
      truncated,
      missing: false,
    });
    if (!injected) continue;
    blocks.push(
      `<file name="${fileName}"${truncated ? ' truncated="true"' : ''}>\n${injected}\n</file>`,
    );
    total += injected.length;
    if (total >= maxTotalChars) break;
  }

  if (blocks.length === 0) {
    return { text: '', files };
  }

  return {
    text: [
      '## Workspace Contract',
      '- `AGENTS.md` = operating instructions. `SOUL.md` and `IDENTITY.md` = persona/profile. `USER.md` = user facts/preferences.',
      '- `MEMORY.md` and `memory/` hold durable memory. Do not use `AGENTS.md` as a general memory log.',
      '- Platform rules may also be appended separately at runtime; AGENTS edits do not replace them.',
      '- When confirming memory/profile/onboarding updates, describe the outcome plainly and do not mention file names or paths unless asked.',
      '- Report sandbox-visible memory/swap/disk only. Do not claim CPU counts from `nproc`, `/proc/cpuinfo`, or stale values.',
      '',
      '## Available Tools',
      '- Use `Bash` for shell work and prefer `rg` for fast search.',
      '- Relevant tools available when needed include `chromium`, `ffmpeg`, `whisper-cli`, `edge-tts`, `qwen-tts`, `claude`, and `codex`.',
      '- Use `tc` CLI for platform operations: credentials, app deployment, tasks, messaging, groups, hooks, and more. Run `tc --help` to explore.',
      '- Use `df -h /workspace/group` for disk checks.',
      '',
      '## Hosted App Rule',
      '- If a user asks to build, create, scaffold, run, deploy, host, or expose an app, site, frontend, backend, or API, treat that as a hosted-app request by default.',
      '- Hosted app requests must place source in `/workspace/apps/<app>/`, write `app.yml` there, send `app-apply`, and verify the real public URL responds before reporting success.',
      '- Do not stop at local files or tell the user to run the app themselves with `npm start`, `node`, Docker Compose, or similar handoff steps unless they explicitly asked for local-only work.',
      '- Do not scaffold hosted apps under `/workspace/group/` unless the user explicitly asked for local-only files.',
      '',
      '## Formatting',
      '- Discord does not render markdown tables. Use bullet lists instead of pipe-delimited tables when presenting data.',
      '',
      heading,
      `<${tagName}>`,
      ...blocks,
      `</${tagName}>`,
      '',
    ].join('\n'),
    files,
  };
}
