'use strict';

const path = require('path');
const fs = require('fs-extra');
const chalk = require('chalk');
const { detect } = require('../stack-detector');
const logger = require('../logger');

async function project(description, options) {
  const targetDir = path.resolve(options.dir || process.cwd());

  if (!description || !description.trim()) {
    logger.error('Please provide a project description.');
    console.log(chalk.dim('  Example: claudeforge project "FastAPI REST API with PostgreSQL and Redis"'));
    process.exit(1);
  }

  if (!await fs.pathExists(path.join(targetDir, '.claude'))) {
    logger.error('No .claude/ directory found. Run `claudeforge init` first.');
    process.exit(1);
  }

  // Detect tech stack from existing files
  const { labels, context } = await detect(targetDir);

  // Write SETUP_CONTEXT.md so the /setup-project slash command can read it
  const contextContent = buildContextFile(description.trim(), labels, context, targetDir);
  const contextPath = path.join(targetDir, 'SETUP_CONTEXT.md');
  await fs.writeFile(contextPath, contextContent, 'utf8');

  // Print onboarding guide
  printGuide(description.trim(), labels, targetDir);
}

function buildContextFile(description, labels, context, targetDir) {
  const lines = [
    '# Project Setup Context',
    '',
    '> This file was generated by `claudeforge project`. It is read by the `/setup-project`',
    '> slash command in Claude Code. Delete it once setup is complete.',
    '',
    '## Project Description',
    '',
    description,
    '',
  ];

  if (labels.length > 0) {
    lines.push('## Detected Tech Stack', '');
    labels.forEach(l => lines.push(`- ${l}`));
    lines.push('');
  }

  if (context) {
    lines.push('## Key Project Files', '', '```', context, '```', '');
  }

  lines.push(
    '## What `/setup-project` Should Do',
    '',
    'Fill in the following files with content tailored to the project description above:',
    '',
    '1. **`CLAUDE.md`** — project name, real commands for the stack, architecture, code style, env vars, gotchas',
    '2. **`.claude/settings.json`** — add stack-appropriate permissions (test runner, build, linter)',
    '3. **`.env.example`** — real environment variables for this stack with descriptions',
    '4. **`.mcp.json`** — context7 plus any relevant MCP servers (database, browser, etc.)',
    '5. **`memory/project_ai_workflow.md`** — AI conventions specific to this project',
    '6. **New agents** in `.claude/agents/` — 2–4 specialized agents for this project type',
    '7. **New commands** in `.claude/commands/` — 2–4 slash commands for the workflow',
    '8. **`.gitignore`** — append tech-stack specific patterns',
    '',
    'Then delete this file (`SETUP_CONTEXT.md`) when done.',
  );

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

function printGuide(description, labels, targetDir) {
  console.log('');
  console.log(chalk.bold.cyan('  claudeforge') + chalk.dim('  —  Project Setup'));
  console.log(chalk.dim('  ─────────────────────────────────────────'));
  console.log('');
  console.log(`  ${chalk.green('✓')} Written ${chalk.cyan('SETUP_CONTEXT.md')} with your project description`);

  if (labels.length > 0) {
    console.log(`  ${chalk.green('✓')} Detected stack: ${chalk.white(labels.join(', '))}`);
  }

  console.log('');
  console.log(chalk.bold('  Next: open Claude Code and run the setup command'));
  console.log('');
  console.log(chalk.dim('  ┌─────────────────────────────────────────────────────────┐'));
  console.log(chalk.dim('  │') + chalk.bold.white('  In the Claude Code chat window, type:                  ') + chalk.dim('│'));
  console.log(chalk.dim('  │') + '                                                          ' + chalk.dim('│'));
  console.log(chalk.dim('  │') + '  ' + chalk.cyan.bold('/setup-project') + chalk.white(` "${truncate(description, 38)}"`) + '    ' + chalk.dim('│'));
  console.log(chalk.dim('  │') + '                                                          ' + chalk.dim('│'));
  console.log(chalk.dim('  └─────────────────────────────────────────────────────────┘'));
  console.log('');
  console.log(chalk.dim('  Claude will read SETUP_CONTEXT.md and fill in:'));
  console.log(chalk.dim('  • CLAUDE.md        — project commands, architecture, style'));
  console.log(chalk.dim('  • settings.json    — stack-appropriate permissions'));
  console.log(chalk.dim('  • .env.example     — real environment variables'));
  console.log(chalk.dim('  • .mcp.json        — MCP servers for your stack'));
  console.log(chalk.dim('  • agents/          — specialized sub-agents for your domain'));
  console.log(chalk.dim('  • commands/        — slash commands for your workflow'));
  console.log(chalk.dim('  • memory/          — project AI workflow conventions'));
  console.log('');
  console.log(chalk.dim('  Works with any Claude model — GitHub Copilot, Claude.ai, or'));
  console.log(chalk.dim('  any IDE with Claude Code extension. No API key required.'));
  console.log('');
  console.log(chalk.dim('  ─────────────────────────────────────────'));
  console.log(chalk.dim('  Other useful commands once in the IDE:'));
  console.log(chalk.dim('  /project-health  — audit your setup and get improvement tips'));
  console.log(chalk.dim('  /memory-sync     — update memory files after a work session'));
  console.log(chalk.dim('  /standup         — generate a standup from recent commits'));
  console.log('');
}

function truncate(str, max) {
  return str.length > max ? str.slice(0, max - 1) + '…' : str;
}

module.exports = project;
