import fs from 'fs-extra';
import path from 'path';
import ignore, { Ignore } from 'ignore';

const DEFAULT_EXCLUDES = [
  'node_modules',
  '.git',
  'vendor',
  '__pycache__',
  'dist',
  'build',
  'target',
  '.DS_Store',
];

export class IgnoreManager {
  private ig: Ignore;

  constructor(workspacePath: string, depth: 'normal' | 'all' = 'normal') {
    this.ig = ignore();

    if (depth === 'normal') {
      // Normal mode: Respect default excludes and .gitignore
      this.ig.add(DEFAULT_EXCLUDES);

      const gitignorePath = path.join(workspacePath, '.gitignore');
      if (fs.existsSync(gitignorePath)) {
        this.ig.add(fs.readFileSync(gitignorePath, 'utf-8'));
      }
    } else {
      // 'all' mode: Only ignore critical system directories
      this.ig.add(['.git', '.DS_Store']);
    }

    // Always respect .owstraignore (renamed from .shieldignore)
    const owstraignorePath = path.join(workspacePath, '.owstraignore');
    if (fs.existsSync(owstraignorePath)) {
      this.ig.add(fs.readFileSync(owstraignorePath, 'utf-8'));
    }
  }

  /**
   * Returns true if the path should be ignored
   */
  shouldIgnore(relativePath: string): boolean {
    if (relativePath === '' || relativePath === '.') return false;
    return this.ig.ignores(relativePath);
  }
}
