// Forge v1: Scaffolding engine
import { join } from 'path';
import { mkdirSync, writeFileSync } from 'fs';
export function createScaffoldPlan(opportunity, options) {
    const { outputType, outputName } = options;
    if (outputType === 'tool') {
        return createToolScaffoldPlan(opportunity, outputName);
    }
    else {
        return createAppScaffoldPlan(opportunity, outputName);
    }
}
function createToolScaffoldPlan(opportunity, toolName) {
    const model = opportunity.primaryModel;
    const dataset = opportunity.supportingDataset;
    const files = [
        {
            path: 'README.md',
            content: generateToolReadme(opportunity, toolName)
        },
        {
            path: 'tool.json',
            content: generateToolManifest(opportunity, toolName)
        },
        {
            path: 'tool.ts',
            content: generateToolCode(opportunity, toolName)
        },
        {
            path: 'package.json',
            content: generatePackageJson(toolName)
        },
        {
            path: 'test-data/example.txt',
            content: generateExampleData(opportunity)
        }
    ];
    const integrationNotes = `To use this tool with Clawx:
1. Build the tool: npm install && npm run build
2. Copy the generated .js file to ~/.clawx/forge/tools/
3. Restart Clawx or reload tools

The tool will appear as "${toolName}" in Clawx's available tools.`;
    return {
        opportunityId: opportunity.id,
        outputType: 'tool',
        outputName: toolName,
        files,
        integrationNotes
    };
}
function createAppScaffoldPlan(opportunity, appName) {
    const model = opportunity.primaryModel;
    const dataset = opportunity.supportingDataset;
    const files = [
        {
            path: 'README.md',
            content: generateAppReadme(opportunity, appName)
        },
        {
            path: 'app.py',
            content: generatePythonApp(opportunity, appName)
        },
        {
            path: 'requirements.txt',
            content: generateRequirements(opportunity)
        },
        {
            path: 'config.yaml',
            content: generateConfig(opportunity)
        },
        {
            path: 'examples/example_usage.py',
            content: generateExampleUsage(opportunity)
        }
    ];
    return {
        opportunityId: opportunity.id,
        outputType: 'app',
        outputName: appName,
        files
    };
}
export function executeScaffoldPlan(plan, outputDir) {
    console.log(`🏗️  Scaffolding ${plan.outputType}: ${plan.outputName}`);
    console.log(`📁 Output directory: ${outputDir}`);
    // Create output directory
    mkdirSync(outputDir, { recursive: true });
    // Create all files
    for (const file of plan.files) {
        const filePath = join(outputDir, file.path);
        // Create subdirectories if needed
        const dirPath = join(outputDir, file.path.split('/').slice(0, -1).join('/'));
        if (dirPath !== outputDir) {
            mkdirSync(dirPath, { recursive: true });
        }
        writeFileSync(filePath, file.content, 'utf8');
        console.log(`  📄 Created: ${file.path}`);
    }
    // Show integration notes if tool
    if (plan.integrationNotes) {
        console.log('\n🔧 Integration notes:');
        console.log(plan.integrationNotes);
    }
    console.log(`\n✅ Scaffolding complete!`);
    console.log(`Next steps: cd ${outputDir} and follow the README`);
}
// Content generators
function generateToolReadme(opportunity, toolName) {
    const model = opportunity.primaryModel;
    const dataset = opportunity.supportingDataset;
    return `# ${toolName}

${opportunity.description}

## Model
- **Name**: ${model.name}
- **Author**: ${model.author}
- **Task**: ${model.task || 'N/A'}
- **Modality**: ${model.modality || 'N/A'}
- **License**: ${model.license || 'N/A'}

${dataset ? `## Dataset
- **Name**: ${dataset.name}
- **Author**: ${dataset.author}
- **Task**: ${dataset.task || 'N/A'}
` : ''}

## Setup
\`\`\`bash
npm install
npm run build
\`\`\`

## Usage with Clawx
1. Copy the generated \`tool.js\` to \`~/.clawx/forge/tools/\`
2. Restart Clawx
3. The tool will be available as "${toolName}"

## Development
- Edit \`tool.ts\` to customize the implementation
- Update \`tool.json\` to modify the tool definition
- Add tests in \`test-data/\`

## Notes
- This is a starter project generated by Clawx Forge
- You may need to install additional dependencies
- Consider hardware requirements: ${model.hardware?.gpu ? 'GPU recommended' : 'CPU only'}
`;
}
function generateToolManifest(opportunity, toolName) {
    const model = opportunity.primaryModel;
    return JSON.stringify({
        name: toolName.toLowerCase().replace(/\s+/g, '_'),
        label: toolName,
        description: opportunity.description,
        parameters: {
            input: {
                type: "string",
                description: `Input ${model.modality || 'data'} to process`
            }
        },
        implementation: {
            type: "custom",
            file: "./tool.js"
        },
        metadata: {
            model: model.id,
            task: model.task,
            generatedBy: "clawx-forge",
            generatedAt: new Date().toISOString()
        }
    }, null, 2);
}
function generateToolCode(opportunity, toolName) {
    const model = opportunity.primaryModel;
    return `// ${toolName} - Generated by Clawx Forge
// Model: ${model.id}
// Task: ${model.task || 'N/A'}

import { AgentTool } from '@mariozechner/pi-agent-core';

export function createTool(): AgentTool<any> {
  return {
    name: '${toolName.toLowerCase().replace(/\s+/g, '_')}',
    label: '${toolName}',
    description: \`${opportunity.description}\`,
    
    parameters: {
      type: 'object',
      properties: {
        input: {
          type: 'string',
          description: 'Input to process'
        }
      },
      required: ['input']
    },
    
    async execute(toolCallId, args, context) {
      const input = args.input;
      
      // TODO: Implement actual model inference
      // For now, return a simulated result
      
      return {
        toolCallId,
        content: [{
          type: 'text',
          text: \`Processed input using ${model.name}\\n\\nInput: "\${input}"\\n\\nResult: Simulated output (replace with real inference)\`
        }],
        details: {
          model: '${model.id}',
          simulated: true,
          note: 'Replace with actual model inference'
        }
      };
    }
  };
}
`;
}
function generatePackageJson(toolName) {
    return JSON.stringify({
        name: toolName.toLowerCase().replace(/\s+/g, '-'),
        version: "0.1.0",
        description: `Clawx tool: ${toolName}`,
        main: "tool.js",
        scripts: {
            build: "tsc tool.ts --outDir . --module commonjs --target es2020",
            test: "echo 'No tests yet'"
        },
        dependencies: {
            "@mariozechner/pi-agent-core": "^0.1.0"
        },
        devDependencies: {
            "typescript": "^5.0.0"
        }
    }, null, 2);
}
function generateExampleData(opportunity) {
    const model = opportunity.primaryModel;
    if (model.modality === 'text') {
        return "This is example text to classify or process.\nReplace with your own data.";
    }
    else if (model.modality === 'image') {
        return "# Example image data would go here\n# Use actual image files for testing";
    }
    else {
        return `Example data for ${model.modality || 'unknown'} modality`;
    }
}
function generateAppReadme(opportunity, appName) {
    const model = opportunity.primaryModel;
    const dataset = opportunity.supportingDataset;
    return `# ${appName}

${opportunity.description}

## Quick Start
\`\`\`bash
# Install dependencies
pip install -r requirements.txt

# Run the app
python app.py
\`\`\`

## Model Details
- **Name**: ${model.name}
- **Author**: ${model.author}
- **Task**: ${model.task || 'N/A'}
- **Downloads**: ${model.downloads.toLocaleString()}

${dataset ? `## Dataset
- **Name**: ${dataset.name}
- **Downloads**: ${dataset.downloads.toLocaleString()}
` : ''}

## Configuration
Edit \`config.yaml\` to customize:
- Model parameters
- Input/output settings
- Hardware preferences

## Examples
See \`examples/\` directory for usage examples.

## Hardware Requirements
${model.hardware?.gpu ? '⚠️ GPU recommended for best performance' : '✅ CPU should work fine'}
${model.hardware?.memory === 'high' ? '⚠️ High memory required (>8GB RAM)' : ''}

## License
${model.license ? `Model license: ${model.license}` : 'Check model license on Hugging Face Hub'}
`;
}
function generatePythonApp(opportunity, appName) {
    const model = opportunity.primaryModel;
    const modelTask = model.task || 'N/A';
    return `#!/usr/bin/env python3
"""
${appName} - Generated by Clawx Forge
Model: ${model.id}
"""

import yaml
import argparse
from pathlib import Path

def load_config():
    """Load configuration from config.yaml"""
    config_path = Path(__file__).parent / 'config.yaml'
    with open(config_path, 'r') as f:
        return yaml.safe_load(f)

def main():
    """Main application entry point"""
    parser = argparse.ArgumentParser(description='${opportunity.description}')
    parser.add_argument('--input', type=str, help='Input to process')
    parser.add_argument('--output', type=str, help='Output file path')
    args = parser.parse_args()
    
    config = load_config()
    
    print(f"Starting ${appName}")
    print(f"Model: ${model.id}")
    print(f"Task: ${modelTask}")
    
    if args.input:
        print(f"Processing input: {args.input}")
        # TODO: Add actual model inference here
        result = f"Simulated result for: {args.input}"
        
        if args.output:
            with open(args.output, 'w') as f:
                f.write(result)
            print(f"Result saved to: {args.output}")
        else:
            print(f"Result: {result}")
    else:
        print("No input provided. Use --input <text> to process data.")
        print("Example: python app.py --input 'Hello world'")

if __name__ == '__main__':
    main()
`;
}
function generateRequirements(opportunity) {
    const model = opportunity.primaryModel;
    let requirements = [
        "PyYAML>=6.0",
        "argparse"
    ];
    // Add model-specific requirements
    if (model.task === 'text-classification' || model.task === 'text-generation') {
        requirements.push("transformers>=4.30.0");
        requirements.push("torch>=2.0.0");
    }
    if (model.modality === 'image') {
        requirements.push("Pillow>=9.0.0");
    }
    return requirements.join('\n');
}
function generateConfig(opportunity) {
    const model = opportunity.primaryModel;
    return `# ${opportunity.title}
# Generated by Clawx Forge

model:
  id: "${model.id}"
  name: "${model.name}"
  task: "${model.task || 'N/A'}"
  
inference:
  device: "auto"  # auto, cpu, cuda
  batch_size: 1
  max_length: 512
  
output:
  format: "text"  # text, json, yaml
  save_to_file: true
  
logging:
  level: "INFO"
  file: "app.log"
`;
}
function generateExampleUsage(opportunity) {
    const model = opportunity.primaryModel;
    return `# Example usage for ${opportunity.title}

import sys
sys.path.append('..')

from app import main

# Example 1: Basic usage
print("Example 1: Process text")
# python app.py --input "Your text here"

# Example 2: Save to file
print("Example 2: Save output to file")
# python app.py --input "Your text" --output result.txt

# Example 3: Batch processing (conceptual)
print("Example 3: Batch processing")
# for text in texts:
#     result = process(text)
#     print(result)
`;
}
//# sourceMappingURL=scaffold.js.map