import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';

const SDD_DIR = '.sdd';

export function toSlug(name) {
  return name.normalize('NFD').replace(/[̀-ͯ]/g, '')
    .toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}

export async function saveBrief(specName, brief) {
  try {
    const dir = path.join(process.cwd(), SDD_DIR, 'specs', specName);
    await mkdir(dir, { recursive: true });
    const sections = ['# Brief: ' + brief.featureName + '\n'];
    if (brief.what)  sections.push('## O que os usuários poderão fazer\n' + brief.what + '\n');
    if (brief.who)   sections.push('## Quem vai usar\n' + brief.who + '\n');
    if (brief.done)  sections.push('## Critérios de aceite\n' + brief.done + '\n');
    if (brief.rules) sections.push('## Restrições e regras de negócio\n' + brief.rules + '\n');
    if (brief.comments?.length) {
      const lines = brief.comments.map(c => `- **${c.author}** (${c.date}): ${c.text}`).join('\n');
      sections.push('## Comentários do Work Item\n' + lines + '\n');
    }
    if (brief.attachments?.length) {
      const lines = brief.attachments.map(a => `- [${a.name}](${a.url})`).join('\n');
      sections.push('## Anexos do Work Item\n' + lines + '\n');
    }
    await writeFile(path.join(dir, 'brief.md'), sections.join('\n'), 'utf8');
  } catch { /* non-fatal */ }
}

export async function initSpec(specName, featureName, brief) {
  const dir = path.join(process.cwd(), SDD_DIR, 'specs', specName);
  await mkdir(dir, { recursive: true });

  const timestamp = new Date().toISOString();
  const specJson = {
    feature_name: specName,
    created_at: timestamp,
    updated_at: timestamp,
    language: 'pt-BR',
    phase: 'initialized',
    approvals: {
      requirements: { generated: false, approved: false },
      design: { generated: false, approved: false },
      tasks: { generated: false, approved: false },
    },
    ready_for_implementation: false,
  };
  await writeFile(path.join(dir, 'spec.json'), JSON.stringify(specJson, null, 2), 'utf8');

  const desc = ['# Requirements Document', '', '## Project Description (Input)', featureName || specName];
  if (brief?.what)  desc.push('', '### O que os usuários poderão fazer', brief.what);
  if (brief?.who)   desc.push('', '### Quem vai usar', brief.who);
  if (brief?.done)  desc.push('', '### Critérios de aceite', brief.done);
  if (brief?.rules) desc.push('', '### Restrições e regras de negócio', brief.rules);
  desc.push('', '## Requirements', '<!-- Will be generated by spec-requirements -->');
  await writeFile(path.join(dir, 'requirements.md'), desc.join('\n'), 'utf8');
}

export function buildSteps(featureName, specName, projectType, includeTasks) {
  const base = '.sdd/specs/' + specName + '/';
  const steps = [
    {
      id: 'requirements',
      title: 'Gerar Requisitos',
      role: 'tech',
      command: '/sdd:spec-requirements ' + specName,
      note: 'A IA usa o brief para gerar os Requisitos da feature — revise com o time de Business antes de continuar',
      ado: 'ADO → Crie a Feature e importe as User Stories do requirements.md',
      files: [base + 'requirements.md'],
    },
  ];
  if (projectType === 'existing') {
    steps.push({
      id: 'gap',
      title: 'Analisar código existente',
      role: 'tech',
      command: '/sdd:validate-gap ' + specName,
      note: 'Identifica o que já existe no código e o que precisa ser criado ou alterado',
      files: [base + 'gap-analysis.md'],
    });
  }
  steps.push({
    id: 'design',
    title: 'Arquitetura técnica',
    role: 'tech',
    command: '/sdd:spec-design ' + specName + ' -y',
    note: 'Define componentes, tecnologias, fluxos e contratos de API — revise com o time técnico antes de aprovar',
    ado: 'ADO → Atualize a descrição da Feature com as decisões do design.md',
    files: [base + 'design.md'],
  });
  if (includeTasks !== false) {
    steps.push({
      id: 'tasks',
      title: 'Gerar Tasks',
      role: 'tech',
      command: '/sdd:spec-tasks ' + specName + ' -y',
      note: 'Cria as Tasks de implementação para cada User Story — Kanban pronto para uso',
      ado: 'ADO → Importe as Tasks do tasks.md e linke às User Stories',
      files: [base + 'tasks.md'],
    });
  }
  steps.push({
    id: 'impl',
    title: 'Implementar',
    role: 'dev',
    command: '/sdd:spec-impl ' + specName,
    note: 'A IA implementa as tasks uma por uma seguindo TDD — revise cada entrega',
    devNote: 'Para continuar: abra o terminal na pasta do projeto → execute claude → cole o comando acima no Claude Code.',
  });
  return steps;
}
