import type { Project } from '../classes.project.js';
import * as plugins from './mod.plugins.js';
import { logger } from '../gitzone.logging.js';

export const run = async (projectArg: Project) => {
  const gitzoneConfig = await projectArg.gitzoneConfig;
  
  // Get copy configuration from npmextra.json
  const npmextraConfig = new plugins.npmextra.Npmextra();
  const copyConfig = npmextraConfig.dataFor<any>('gitzone.format.copy', {
    patterns: []
  });
  
  if (!copyConfig.patterns || copyConfig.patterns.length === 0) {
    logger.log('info', 'No copy patterns configured in npmextra.json');
    return;
  }
  
  for (const pattern of copyConfig.patterns) {
    if (!pattern.from || !pattern.to) {
      logger.log('warn', 'Invalid copy pattern - missing "from" or "to" field');
      continue;
    }
    
    try {
      // Handle glob patterns
      const files = await plugins.smartfile.fs.listFileTree('.', pattern.from);
      
      for (const file of files) {
        const sourcePath = file;
        let destPath = pattern.to;
        
        // If destination is a directory, preserve filename
        if (pattern.to.endsWith('/')) {
          const filename = plugins.path.basename(file);
          destPath = plugins.path.join(pattern.to, filename);
        }
        
        // Handle template variables in destination path
        if (pattern.preservePath) {
          const relativePath = plugins.path.relative(
            plugins.path.dirname(pattern.from.replace(/\*/g, '')), 
            file
          );
          destPath = plugins.path.join(pattern.to, relativePath);
        }
        
        // Ensure destination directory exists
        await plugins.smartfile.fs.ensureDir(plugins.path.dirname(destPath));
        
        // Copy file
        await plugins.smartfile.fs.copy(sourcePath, destPath);
        logger.log('info', `Copied ${sourcePath} to ${destPath}`);
      }
    } catch (error) {
      logger.log('error', `Failed to copy pattern ${pattern.from}: ${error.message}`);
    }
  }
};

/**
 * Example npmextra.json configuration:
 * {
 *   "gitzone": {
 *     "format": {
 *       "copy": {
 *         "patterns": [
 *           {
 *             "from": "src/assets/*",
 *             "to": "dist/assets/",
 *             "preservePath": true
 *           },
 *           {
 *             "from": "config/*.json",
 *             "to": "dist/"
 *           }
 *         ]
 *       }
 *     }
 *   }
 * }
 */