import { readdir, readFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { getWorkspaceRoot } from './workspace.mjs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const INSPIRATION_DIR = join(__dirname, 'inspiration');

/**
 * List all available inspiration files.
 * Scans both inspiration/ (seed library) and workspaceRoot (agent's own work).
 * Returns objects with { name, dir } so we know where each file lives.
 */
export async function listInspirationFiles() {
  const results = [];

  try {
    const files = await readdir(INSPIRATION_DIR);
    for (const f of files) {
      if (f.endsWith('.html')) results.push({ name: f, dir: INSPIRATION_DIR });
    }
  } catch {}

  const workspaceDir = getWorkspaceRoot();
  try {
    const files = await readdir(workspaceDir);
    for (const f of files) {
      if (!f.endsWith('.html')) continue;
      if (!results.some(r => r.name === f)) {
        results.push({ name: f, dir: workspaceDir });
      }
    }
  } catch {}

  return results;
}

export async function listInspirationFileNames() {
  const files = await listInspirationFiles();
  return files.map(f => f.name);
}

export async function pickRandom(count = 3) {
  const files = await listInspirationFiles();
  if (!files.length) return [];
  const shuffled = files.sort(() => Math.random() - 0.5);
  return shuffled.slice(0, Math.min(count, files.length));
}

/**
 * Read an inspiration file's content (truncated for prompt use).
 * Searches inspiration/ first, then workspace.
 */
export async function readInspirationFile(filename, maxChars = 4000) {
  try {
    const content = await readFile(join(INSPIRATION_DIR, filename), 'utf-8');
    return content.slice(0, maxChars);
  } catch {}

  const workspaceDir = getWorkspaceRoot();
  try {
    const content = await readFile(join(workspaceDir, filename), 'utf-8');
    return content.slice(0, maxChars);
  } catch {}

  throw new Error(`Inspiration file not found: ${filename}`);
}

export async function getInspirationContext({ sampleCount = 1, listCount = 15 } = {}) {
  const all = await listInspirationFiles();
  if (!all.length) return '';

  const listed = all.sort(() => Math.random() - 0.5).slice(0, listCount);
  const names = listed.map(f => f.name.replace('.html', ''));

  let sampleContent = '';
  if (sampleCount > 0) {
    const samples = await pickRandom(sampleCount);
    for (const sample of samples) {
      try {
        const content = await readInspirationFile(sample.name, 3000);
        sampleContent += `\n--- Reference: ${sample.name} (excerpt) ---\n${content}\n--- end ---\n`;
      } catch {}
    }
  }

  return `## Inspiration Library
You have a collection of ${all.length} interactive HTML pages to draw inspiration from. Some examples:
${names.join(', ')}

These are self-contained HTML files with embedded CSS/JS - games, simulations, art, tools, music, and more. Use them as inspiration for style, structure, and ideas. Don't copy them directly, but let them inform your creative choices.
${sampleContent}`;
}

