/* eslint-disable @typescript-eslint/no-require-imports */
const fs = require('fs');
const path = require('path');
const { execSync } = require('node:child_process');

// Directory to start from (project root)
const ROOT_DIR = process.cwd();
// Output file path
const OUTPUT_FILE = path.join(ROOT_DIR, 'docs', 'project-structure.txt');

// Function to check if a path is ignored by git
function isGitIgnored(filePath) {
  try {
    // git check-ignore -q returns 0 if ignored, 1 if not
    execSync(`git check-ignore -q "${filePath}"`, {
      cwd: ROOT_DIR,
      stdio: 'ignore'
    });
    return true; // Ignored
  } catch (e) {
    return false; // Not ignored
  }
}

// Function to generate tree structure
function generateTree(dir, prefix = '', isRoot = true) {
  let structure = '';
  
  // Add root directory name if it's the root
  if (isRoot) {
    structure += `${path.basename(dir)}/\n`;
  }
  
  let items;
  try {
    items = fs.readdirSync(dir);
  } catch (e) {
    console.error(`Error reading directory ${dir}: ${e.message}`);
    return structure;
  }
  
  // Sort items: directories first, then files
  const dirs = [];
  const files = [];
  
  items.forEach(item => {
    const itemPath = path.join(dir, item);
    
    // Explicitly skip .git directory and husky internal directory
    if (item === '.git' && dir === ROOT_DIR) {
      return;
    }
    if (item === '_' && path.basename(dir) === '.husky') {
      return;
    }
    
    // Skip if ignored by git
    if (isGitIgnored(itemPath)) {
      return;
    }
    
    try {
      const stat = fs.statSync(itemPath);
      if (stat.isDirectory()) {
        dirs.push(item);
      } else {
        files.push(item);
      }
    } catch (e) {
      // Skip items we can't stat
    }
  });
  
  // Sort directories and files alphabetically
  dirs.sort();
  files.sort();
  
  const allItems = [...dirs, ...files];
  
  allItems.forEach((item, index) => {
    const isLast = index === allItems.length - 1;
    const connector = isLast ? '└── ' : '├── ';
    const itemPath = path.join(dir, item);
    
    structure += `${prefix}${connector}${item}${dirs.includes(item) ? '/' : ''}\n`;
    
    // Recurse into directories
    if (dirs.includes(item)) {
      const newPrefix = prefix + (isLast ? '    ' : '│   ');
      structure += generateTree(itemPath, newPrefix, false);
    }
  });
  
  return structure;
}

try {
  console.log('🗺️ Generating project structure...');
  
  // Ensure docs directory exists
  const docsDir = path.join(ROOT_DIR, 'docs');
  if (!fs.existsSync(docsDir)) {
    fs.mkdirSync(docsDir, { recursive: true });
    console.log('📁 Created docs directory');
  }
  
  // Generate tree
  const tree = generateTree(ROOT_DIR, '', true);
  
  // Write to file
  fs.writeFileSync(OUTPUT_FILE, tree);
  console.log(`✅ Project structure updated: ${OUTPUT_FILE}`);
  
} catch (err) {
  console.error(`❌ Error generating project structure: ${err.message}`);
  process.exit(1);
}
