import { ensureDevContainer, execInDevContainer } from "@/lib/dev-container";
import { authSession } from "@/lib/auth/session-server";

/**
 * Builds a fast, high-level summary of the active project's codebase
 * to inject into the system prompt. This prevents the AI from having
 * to blind-search the repo to figure out the tech stack on every turn.
 */
export async function buildCodebaseSummary(
  projectId: string,
  projectSlug: string,
): Promise<string> {
  if (!projectId || !projectSlug) return "";

  try {
    const session = (await authSession()) as unknown as {
      workspace?: import("@/lib/workspaces").VibnWorkspace;
    };
    if (!session?.workspace) return "";

    // Ensure the container is actually running before we try to exec inside it
    await ensureDevContainer({
      projectId,
      projectSlug,
      projectName: projectSlug,
      workspace: session.workspace,
    });
    // We run a fast bash script inside the dev container that finds package.json,
    // checks for Prisma/Drizzle schemas, and lists the root folders.
    // Time to execute: ~50ms.
    const bashScript = `
      cd /workspace/${projectSlug} 2>/dev/null || exit 0

      echo "=== DEPENDENCIES ==="
      if [ -f package.json ]; then
        node -e "const pkg=require('./package.json'); console.log('Dependencies:', Object.keys(pkg.dependencies||{}).join(', ')); console.log('DevDependencies:', Object.keys(pkg.devDependencies||{}).join(', '));" 2>/dev/null || echo "Found package.json"
      else
        echo "No package.json found"
      fi

      echo -e "\\n=== ARCHITECTURE ==="
      if [ -d src/app ] || [ -d app ]; then echo "- Next.js App Router"; fi
      if [ -f prisma/schema.prisma ]; then echo "- Prisma ORM (prisma/schema.prisma)"; fi
      if [ -f drizzle.config.ts ]; then echo "- Drizzle ORM"; fi
      if [ -d .svelte-kit ]; then echo "- SvelteKit"; fi
      if [ -f vite.config.ts ] || [ -f vite.config.js ]; then echo "- Vite SPA"; fi
      if [ -f docker-compose.yml ]; then echo "- Docker Compose deployed"; fi

      echo -e "\\n=== DIRECTORY TREE ==="
      # Generate a tree up to 3 levels deep, ignoring heavy/noisy folders.
      # This gives the AI an instant map of the codebase without needing to run fs_tree manually.
      find . -maxdepth 4 -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/.next/*" -not -path "*/dist/*" -not -path "*/build/*" | sort | sed -e "s/[^-][^\\/]*\\// |/g" -e "s/|\\([^ ]\\)/|-\\1/" | head -n 300
    `;

    const result = await execInDevContainer({
      projectId,
      command: bashScript,
    });

    if (result.code !== 0 || !result.stdout.trim()) {
      return "";
    }

    return `\n## CODEBASE SUMMARY (Auto-detected)
This is a real-time map of the files currently existing in \`/workspace/${projectSlug}/\`:
\`\`\`text
${result.stdout.trim().slice(0, 4000)}
\`\`\`
Use this directory tree to orient yourself. You do not need to run fs_list or fs_tree to find where files live. Do not guess the stack; if it says Next.js and Prisma, use Next.js and Prisma.`;
  } catch (error) {
    console.warn("[Codebase Summary] Failed to generate summary:", error);
    return "";
  }
}
