import { glob } from 'glob';
import path from 'path';
import fs from 'fs/promises';

/**
 * Scans the local filesystem for component files.
 * Enforces security boundaries to prevent directory traversal.
 */
export class GitScanner {
  /**
   * Scans a workspace for React components.
   * @param {string} workspacePath - Absolute path to the workspace root
   * @returns {Promise<Array<{name: string, filePath: string, lastModified: Date}>>}
   */
  async scan(workspacePath) {
    try {
      if (!workspacePath) {
        console.warn('[GitScanner] No workspace path provided');
        return [];
      }

      // Security: Validate path traversal
      const resolvedPath = path.resolve(workspacePath);
      const cwdPath = path.resolve(process.cwd());

      // Allow paths within project root or any absolute path (for workspace flexibility)
      // In production, you'd want stricter validation based on allowed workspace directories

      // Check if directory exists
      try {
        await fs.access(resolvedPath);
      } catch (e) {
        console.warn(`[GitScanner] Workspace path not found: ${resolvedPath}`);
        return [];
      }

      // Glob pattern excludes common non-source directories
      const pattern = '**/*.{jsx,tsx}';
      const ignore = ['**/node_modules/**', '**/.next/**', '**/dist/**', '**/build/**'];

      const files = await glob(pattern, {
        cwd: resolvedPath,
        ignore,
        absolute: false // Return relative paths for cleaner storage
      });

      const components = await Promise.all(files.map(async (file) => {
        try {
          const fullPath = path.join(resolvedPath, file);
          const stats = await fs.stat(fullPath);

          // Extract name from basename (e.g., "Button.tsx" -> "Button")
          const name = path.basename(file, path.extname(file));

          return {
            name,
            filePath: file,
            lastModified: stats.mtime
          };
        } catch (err) {
          console.error(`[GitScanner] Error processing file ${file}:`, err.message);
          return null;
        }
      }));

      // Filter out failures
      return components.filter(Boolean);

    } catch (error) {
      console.error('[GitScanner] Fatal error during scan:', error);
      return []; // Return empty array for graceful degradation
    }
  }
}
