#!/bin/bash

# Composite Skill Creator
# Creates a skill that composes multiple existing skills

set -e

if [ $# -lt 2 ]; then
    echo "Usage: $0 <composite_skill_name> <skill1> <skill2> ..."
    echo ""
    echo "Example: $0 fullstack-testing bdd_testing unit_testing integration_testing"
    exit 1
fi

COMPOSITE_NAME=$1
shift
COMPONENT_SKILLS=("$@")

COMPOSITE_DIR=".vibe/skills/${COMPOSITE_NAME}"

# Convert underscores to hyphens for the skill name
COMPOSITE_NAME_HYPHENATED=$(echo "$COMPOSITE_NAME" | tr '_' '-')

echo "🛠️  Creating composite skill: ${COMPOSITE_NAME_HYPHENATED}"
echo "📦 Composing skills: ${COMPONENT_SKILLS[*]}"
echo ""

# Create skill directory
mkdir -p "$COMPOSITE_DIR"
mkdir -p "$COMPOSITE_DIR/scripts"
mkdir -p "$COMPOSITE_DIR/references"
mkdir -p "$COMPOSITE_DIR/assets"

# Create SKILL.md with composite pattern
cat > "$COMPOSITE_DIR/SKILL.md" <<EOL
---
name: ${COMPOSITE_NAME_HYPHENATED}
description: Composite skill combining multiple skills for [purpose]. Use when you need to perform [complex workflow] that requires [list capabilities].
license: MIT
metadata:
  author: [Your Name or Organization]
  version: "1.0.0"
  composes:
EOL

# Add composed skills to metadata
for skill in "${COMPONENT_SKILLS[@]}"; do
    echo "    - ${skill}" >> "$COMPOSITE_DIR/SKILL.md"
done

# Complete the SKILL.md
cat >> "$COMPOSITE_DIR/SKILL.md" <<'EOL'
  compatibility: ">=1.0.0"
---

# [Composite Skill Name]

This composite skill combines the capabilities of multiple skills to provide a comprehensive solution for [describe purpose].

## Component Skills

EOL

# Document component skills
for skill in "${COMPONENT_SKILLS[@]}"; do
    echo "### ${skill}" >> "$COMPOSITE_DIR/SKILL.md"
    echo "" >> "$COMPOSITE_DIR/SKILL.md"
    echo "[Brief description of what this skill contributes]" >> "$COMPOSITE_DIR/SKILL.md"
    echo "" >> "$COMPOSITE_DIR/SKILL.md"
done

cat >> "$COMPOSITE_DIR/SKILL.md" <<'EOL'
## Workflows

### Complete Workflow

1. **Step 1**: [Description using ${skill1}]
2. **Step 2**: [Description using ${skill2}]
3. **Step 3**: [Description using ${skill3}]

### Example Usage

```bash
# Use the composite skill
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh

# Or use individual components
.vibe/skills/${skill1}/scripts/script.sh
.vibe/skills/${skill2}/scripts/script.sh
```

## Best Practices

1. **Use the composite workflow** for standard operations
2. **Access individual skills** when you need specific capabilities
3. **Follow component skill guidelines** for each part
4. **Check all dependencies** before using the composite skill

## References

EOL

# Add references to component skills
for skill in "${COMPONENT_SKILLS[@]}"; do
    echo "- [${skill}](../${skill}/SKILL.md) - [Brief description]" >> "$COMPOSITE_DIR/SKILL.md"
done

cat >> "$COMPOSITE_DIR/SKILL.md" <<'EOL'

## Troubleshooting

### Component Skill Issues

If you encounter issues with a specific component:

1. **Check the component skill directly**:
   ```bash
   .vibe/skills/skill_creator/scripts/validate_skill.sh .vibe/skills/[component]
   ```

2. **Review component documentation**:
   ```bash
   cat .vibe/skills/[component]/README.md
   ```

3. **Test component independently**:
   ```bash
   .vibe/skills/[component]/scripts/test.sh
   ```

### Composite Skill Issues

If the composite skill itself has issues:

1. **Validate the composite structure**:
   ```bash
   .vibe/skills/skill_creator/scripts/validate_skill.sh .vibe/skills/${COMPOSITE_NAME_HYPHENATED}
   ```

2. **Check component compatibility**:
   ```bash
   # Verify all components are present and valid
   for skill in ${COMPONENT_SKILLS[@]}; do
       .vibe/skills/skill_creator/scripts/validate_skill.sh .vibe/skills/$skill
   done
   ```

## Assets

- **workflow-diagram.md**: Visual representation of the composite workflow
- **integration-guide.md**: How to integrate this composite skill with other systems
- **examples/**: Complete examples of using the composite skill
EOL

# Create main script that orchestrates the workflow
cat > "$COMPOSITE_DIR/scripts/main.sh" <<EOL
#!/bin/bash

# Composite Skill: ${COMPOSITE_NAME_HYPHENATED}
# Orchestrates the workflow using component skills

set -e

echo "🚀 Running composite skill: ${COMPOSITE_NAME_HYPHENATED}"
echo "================================================"
echo ""

# Step 1: Validate all component skills
echo "🔍 Validating component skills..."
for skill in ${COMPONENT_SKILLS[@]}; do
    echo "  - Validating: $skill"
    .vibe/skills/skill_creator/scripts/validate_skill.sh ".vibe/skills/$skill"
done
echo "✅ All component skills validated"
echo ""

# Step 2: Execute component skills in order
echo "📋 Executing workflow..."
EOL

# Add placeholder for component execution
for i in "${!COMPONENT_SKILLS[@]}"; do
    skill="${COMPONENT_SKILLS[$i]}"
    step=$((i+1))
    cat >> "$COMPOSITE_DIR/scripts/main.sh" <<EOL
# Step ${step}: Run ${skill}
echo "  Step ${step}/${#COMPONENT_SKILLS[@]}: Running ${skill}"
# .vibe/skills/${skill}/scripts/main.sh
# Add actual command to run ${skill}
echo "  ✅ Completed: ${skill}"
echo ""
EOL
done

cat >> "$COMPOSITE_DIR/scripts/main.sh" <<'EOL'
# Step N: Final integration
echo "🎯 Final integration and validation"
# Add final integration logic here

echo ""
echo "✨ Composite skill execution complete!"
echo "📊 Results:"
echo "  - Component skills executed: ${#COMPONENT_SKILLS[@]}"
echo "  - Workflow steps completed: [X]"
echo "  - Status: Success"
EOL

chmod +x "$COMPOSITE_DIR/scripts/main.sh"

# Create integration guide
cat > "$COMPOSITE_DIR/references/INTEGRATION.md" <<EOL
# Integration Guide for ${COMPOSITE_NAME_HYPHENATED}

## Overview

This guide explains how to integrate the ${COMPOSITE_NAME_HYPHENATED} composite skill with your workflows and systems.

## Integration Patterns

### Pattern 1: Direct Usage

```bash
# Run the complete workflow
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh
```

### Pattern 2: Selective Usage

```bash
# Use only specific components
.vibe/skills/${COMPONENT_SKILLS[0]}/scripts/script.sh
.vibe/skills/${COMPONENT_SKILLS[1]}/scripts/script.sh
```

### Pattern 3: Programmatic Integration

```go
// Call from Go code
package main

import (
    "os"
    "os/exec"
)

func runCompositeSkill() error {
    cmd := exec.Command(".vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    return cmd.Run()
}
```

### Pattern 4: CI/CD Integration

```yaml
# GitHub Actions example
- name: Run composite skill
  run: .vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh
```

## Customization

### Adding New Components

To add a new skill to the composite:

1. **Update SKILL.md**:
   ```yaml
   metadata:
     composes:
       - existing-skill
       - new-skill  # Add this
   ```

2. **Update main.sh**:
   ```bash
   # Add step to execute new-skill
   echo "  Step X: Running new-skill"
   .vibe/skills/new-skill/scripts/main.sh
   ```

3. **Document the component**:
   ```markdown
   ### new-skill
   
   [Description of what new-skill contributes]
   ```

### Modifying Workflow

To change the execution order or add conditional logic:

```bash
# Example: Conditional execution
if [ "$SKIP_STEP" != "true" ]; then
    echo "  Running optional component"
    .vibe/skills/optional-skill/scripts/main.sh
fi
```

## Configuration

### Environment Variables

```bash
# Set configuration via environment variables
export COMPOSITE_CONFIG="value"
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh
```

### Configuration File

```yaml
# config.yaml
composite:
  ${COMPOSITE_NAME_HYPHENATED}:
    enabled: true
    components:
      ${COMPONENT_SKILLS[0]}:
        config: value1
      ${COMPONENT_SKILLS[1]}:
        config: value2
```

## Best Practices

### 1. Start Simple

Begin with a basic composite and add complexity as needed.

### 2. Validate Components

Always validate component skills before creating composites.

### 3. Document Dependencies

Clearly document all dependencies and requirements.

### 4. Test Incrementally

Test each component and the composite as a whole.

### 5. Provide Escape Hatches

Allow users to access individual components when needed.

### 6. Monitor Performance

Track execution time and resource usage.

### 7. Plan for Updates

Consider how component updates affect the composite.

## Troubleshooting

### Component Not Found

**Error:** `skill not found: missing-skill`

**Solution:**
1. Verify the skill exists
2. Check the skill name spelling
3. Ensure the skill is in the correct directory

### Version Mismatch

**Error:** `version mismatch: expected >=1.0.0, found 0.9.0`

**Solution:**
1. Update the component skill
2. Adjust version requirements
3. Check compatibility

### Circular Dependencies

**Error:** `circular dependency detected: skill-a → skill-b → skill-a`

**Solution:**
1. Restructure the composite
2. Remove circular references
3. Use intermediate skills if needed

### Performance Issues

**Symptom:** Composite execution is slow

**Solutions:**
1. Profile execution time
2. Optimize component skills
3. Run components in parallel (if possible)
4. Cache intermediate results

## Examples

### Example 1: Testing Composite

```bash
# Create a testing composite
.vibe/skills/skill_creator/scripts/create_composite_skill.sh \
  fullstack-testing \
  bdd_testing \
  unit_testing \
  integration_testing

# Run the testing workflow
.vibe/skills/fullstack-testing/scripts/main.sh
```

### Example 2: Deployment Composite

```bash
# Create a deployment composite
.vibe/skills/skill_creator/scripts/create_composite_skill.sh \
  ci-cd-pipeline \
  build \
  test \
  package \
  deploy \
  monitor

# Run the deployment pipeline
.vibe/skills/ci-cd-pipeline/scripts/main.sh
```

## Advanced Patterns

### Dynamic Composition

```bash
#!/bin/bash
# Dynamically compose skills based on requirements

REQUIRED_SKILLS=()

if [ "$NEED_TESTING" = "true" ]; then
    REQUIRED_SKILLS+=("bdd_testing" "unit_testing")
fi

if [ "$NEED_DEPLOYMENT" = "true" ]; then
    REQUIRED_SKILLS+=("deployment" "monitoring")
fi

# Create dynamic composite
.vibe/skills/skill_creator/scripts/create_composite_skill.sh \
  dynamic-workflow \
  "${REQUIRED_SKILLS[@]}"
```

### Conditional Execution

```bash
# main.sh with conditional logic
if [ "$SKIP_TESTS" = "true" ]; then
    echo "Skipping tests"
else
    echo "Running tests"
    .vibe/skills/bdd_testing/scripts/run-tests.sh
fi
```

### Parallel Execution

```bash
# Run components in parallel (when possible)
echo "Running components in parallel..."

.vibe/skills/component1/scripts/main.sh &
COMPONENT1_PID=$!

.vibe/skills/component2/scripts/main.sh &
COMPONENT2_PID=$!

wait $COMPONENT1_PID $COMPONENT2_PID

echo "All components completed"
```

## Conclusion

Composite skills provide a powerful way to combine multiple capabilities into cohesive workflows. By following these integration patterns and best practices, you can create robust composite skills that enhance productivity and maintainability.

**Next Steps:**
1. Customize the main workflow script
2. Add component-specific configuration
3. Implement error handling and recovery
4. Add monitoring and logging
5. Document the composite skill thoroughly
EOL

# Create workflow diagram
cat > "$COMPOSITE_DIR/assets/workflow-diagram.md" <<EOL
# Workflow Diagram for ${COMPOSITE_NAME_HYPHENATED}

## Text-Based Diagram

```
${COMPOSITE_NAME_HYPHENATED} Workflow
┌─────────────────────────────────────────────────┐
│                                                 │
│  1. Validate Component Skills                 │
│     ├─ ${COMPONENT_SKILLS[0]}                  │
│     ├─ ${COMPONENT_SKILLS[1]}                  │
│     └─ ...                                     │
│                                                 │
│  2. Execute Component Workflows                │
│     ├─ Step 1: ${COMPONENT_SKILLS[0]}           │
│     ├─ Step 2: ${COMPONENT_SKILLS[1]}           │
│     └─ ...                                     │
│                                                 │
│  3. Final Integration                          │
│     └─ Combine results                        │
│                                                 │
└─────────────────────────────────────────────────┘
```

## Mermaid Diagram

```mermaid
graph TD
    A[Start ${COMPOSITE_NAME_HYPHENATED}] --> B[Validate Components]
    B --> C[Execute ${COMPONENT_SKILLS[0]}]
    C --> D[Execute ${COMPONENT_SKILLS[1]}]
    D --> E[...]
    E --> F[Final Integration]
    F --> G[Complete]
```

## Sequence Diagram

```mermaid
sequenceDiagram
    participant User
    participant Composite
    participant Component1
    participant Component2
    
    User->>Composite: Run workflow
    Composite->>Component1: Validate
    Composite->>Component2: Validate
    Component1-->>Composite: Ready
    Component2-->>Composite: Ready
    
    Composite->>Component1: Execute
    Composite->>Component2: Execute
    Component1-->>Composite: Results
    Component2-->>Composite: Results
    
    Composite->>Composite: Integrate results
    Composite-->>User: Final output
```

## Component Details

EOL

# Add component details
for i in "${!COMPONENT_SKILLS[@]}"; do
    skill="${COMPONENT_SKILLS[$i]}"
    step=$((i+1))
    cat >> "$COMPOSITE_DIR/assets/workflow-diagram.md" <<EOL
### Step ${step}: ${skill}

**Purpose**: [Brief description]

**Inputs**:
- Input 1: [Description]
- Input 2: [Description]

**Outputs**:
- Output 1: [Description]
- Output 2: [Description]

**Dependencies**:
- [List any dependencies]

**Configuration**:
- [Configuration options]
EOL
done

cat >> "$COMPOSITE_DIR/assets/workflow-diagram.md" <<'EOL'

## Integration Points

### Data Flow

```
Component1 → [Data] → Composite → [Data] → Component2
Component2 → [Results] → Composite → [Final Output] → User
```

### Error Handling

```
Component1 → [Error] → Composite → [Recovery] → Continue/Fail
Component2 → [Error] → Composite → [Recovery] → Continue/Fail
```

## Usage Examples

### Example 1: Linear Workflow

```
Step 1 → Step 2 → Step 3 → Final Output
```

### Example 2: Parallel Workflow

```
      → Step 2a →
     /           \
Start            → Integrate → Final Output
     \           /
      → Step 2b →
```

### Example 3: Conditional Workflow

```
Start → Check Condition
     → True → Step A → End
     → False → Step B → End
```

## Best Practices for Workflow Design

1. **Keep it simple**: Start with linear workflows
2. **Add parallelism**: When components are independent
3. **Handle errors**: Graceful degradation where possible
4. **Validate inputs**: At each step
5. **Document outputs**: For each component
6. **Monitor progress**: Log key milestones
7. **Optimize performance**: Identify bottlenecks
8. **Plan for failure**: Recovery strategies
9. **Test thoroughly**: All code paths
10. **Document clearly**: For future maintenance
EOL

# Create README
cat > "$COMPOSITE_DIR/README.md" <<EOL
# ${COMPOSITE_NAME_HYPHENATED} - Composite Skill

## Overview

This composite skill combines the capabilities of multiple skills to provide a comprehensive solution for [describe purpose].

**Component Skills:**
EOL

# List component skills in README
for skill in "${COMPONENT_SKILLS[@]}"; do
    echo "- [${skill}](.vibe/skills/${skill}/) - [Brief description]" >> "$COMPOSITE_DIR/README.md"
done

cat >> "$COMPOSITE_DIR/README.md" <<'EOL'

## Features

- **Unified Workflow**: Single command executes multiple skills
- **Modular Design**: Access individual components when needed
- **Flexible Configuration**: Customize behavior via environment variables
- **Robust Error Handling**: Graceful handling of component failures
- **Comprehensive Logging**: Detailed execution logs

## Installation

The composite skill is already available in your project:

```bash
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/
```

## Usage

### Basic Usage

```bash
# Run the complete workflow
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh
```

### Advanced Usage

```bash
# With environment variables
export CONFIG_VAR="value"
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh

# With custom options
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh --option1 --option2
```

### Individual Components

```bash
# Access individual component skills
.vibe/skills/${COMPONENT_SKILLS[0]}/scripts/script.sh
.vibe/skills/${COMPONENT_SKILLS[1]}/scripts/script.sh
```

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `CONFIG_VAR` | [Description] | `value` |
| `DEBUG` | Enable debug logging | `false` |
| `SKIP_STEP` | Skip optional steps | `false` |

### Configuration File

```yaml
# .vibe/skills/${COMPOSITE_NAME_HYPHENATED}/config.yaml
components:
  ${COMPONENT_SKILLS[0]}:
    enabled: true
    config:
      key: value
  ${COMPONENT_SKILLS[1]}:
    enabled: true
    config:
      key: value
```

## Examples

### Example 1: Basic Workflow

```bash
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh
```

### Example 2: Custom Configuration

```bash
export CUSTOM_CONFIG="my-value"
.vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh
```

### Example 3: Selective Execution

```bash
# Run only specific components
.vibe/skills/${COMPONENT_SKILLS[0]}/scripts/script.sh
.vibe/skills/${COMPONENT_SKILLS[1]}/scripts/script.sh
```

## Workflow

```mermaid
graph LR
    A[Start] --> B[Validate Components]
    B --> C[Execute Components]
    C --> D[Integrate Results]
    D --> E[Complete]
```

## Best Practices

1. **Start with the composite workflow** for standard operations
2. **Use individual components** when you need specific capabilities
3. **Configure appropriately** for your use case
4. **Monitor execution** for performance and errors
5. **Update components** to get the latest features
6. **Document customizations** for team reference
7. **Test changes** before deploying to production
8. **Share feedback** to improve the composite skill

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Component not found | Verify skill exists and is valid |
| Version mismatch | Update component or adjust requirements |
| Permission denied | Check file permissions |
| Slow execution | Optimize components or run in parallel |

### Debugging

```bash
# Validate the composite skill
.vibe/skills/skill_creator/scripts/validate_skill.sh .vibe/skills/${COMPOSITE_NAME_HYPHENATED}

# Validate individual components
for skill in ${COMPONENT_SKILLS[@]}; do
    .vibe/skills/skill_creator/scripts/validate_skill.sh .vibe/skills/$skill
done

# Run with verbose logging
DEBUG=true .vibe/skills/${COMPOSITE_NAME_HYPHENATED}/scripts/main.sh
```

## Development

### Extending the Composite

To add new components:

1. **Update SKILL.md**: Add to the `composes` list
2. **Update main.sh**: Add execution step
3. **Document**: Add component description
4. **Test**: Verify the updated workflow

### Customizing Workflow

Modify `scripts/main.sh` to:
- Change execution order
- Add conditional logic
- Implement parallel execution
- Add custom validation

### Testing

```bash
# Test the composite skill
.vibe/skills/skill_creator/scripts/validate_skill.sh .vibe/skills/${COMPOSITE_NAME_HYPHENATED}

# Test individual components
for skill in ${COMPONENT_SKILLS[@]}; do
    .vibe/skills/skill_creator/scripts/validate_skill.sh .vibe/skills/$skill
done
```

## Contributing

To improve this composite skill:

1. **Fork** the repository
2. **Create** a feature branch
3. **Make** your changes
4. **Test** thoroughly
5. **Submit** a pull request

## License

MIT License - See the `license` field in SKILL.md for details.

## Support

For issues or questions:
1. Check the [troubleshooting](#troubleshooting) section
2. Review component skill documentation
3. Consult the [integration guide](references/INTEGRATION.md)
4. Ask the team for assistance

## Related Skills

EOL

# Add related skills
for skill in "${COMPONENT_SKILLS[@]}"; do
    echo "- [${skill}](.vibe/skills/${skill}/SKILL.md) - Component skill" >> "$COMPOSITE_DIR/README.md"
done

cat >> "$COMPOSITE_DIR/README.md" <<'EOL'

## Changelog

### 1.0.0 (Current)
- Initial release
- Combined ${#COMPONENT_SKILLS[@]} component skills
- Basic workflow implementation

## Roadmap

### Future Enhancements
- [ ] Parallel execution of independent components
- [ ] Advanced error handling and recovery
- [ ] Configuration validation
- [ ] Performance monitoring
- [ ] Usage analytics

## Success Metrics

Track these metrics to measure the composite skill's effectiveness:

1. **Adoption Rate**: Number of teams using the composite
2. **Execution Time**: Total workflow duration
3. **Success Rate**: Percentage of successful executions
4. **Error Rate**: Frequency of failures
5. **Time Saved**: Productivity improvements

## Conclusion

This composite skill provides a powerful way to combine multiple capabilities into a cohesive workflow. By leveraging the strengths of each component skill, it delivers a comprehensive solution that's greater than the sum of its parts.

**Next Steps:**
1. Review the [integration guide](references/INTEGRATION.md)
2. Customize the workflow for your needs
3. Test the composite skill thoroughly
4. Share feedback to help improve it
5. Contribute enhancements back to the project
EOL

echo "✅ Created composite skill: ${COMPOSITE_NAME_HYPHENATED}"
echo "📁 Skill directory: ${COMPOSITE_DIR}"
echo ""
echo "Created files:"
echo "  ✅ SKILL.md - Main skill file with composite metadata"
echo "  ✅ scripts/main.sh - Workflow orchestration script"
echo "  ✅ references/INTEGRATION.md - Integration guide"
echo "  ✅ assets/workflow-diagram.md - Visual workflow diagrams"
echo "  ✅ README.md - Comprehensive usage guide"
echo ""
echo "Next steps:"
echo "  1. Edit SKILL.md to add specific descriptions"
echo "  2. Customize scripts/main.sh with your workflow logic"
echo "  3. Update references/INTEGRATION.md with integration details"
echo "  4. Test the composite skill: .vibe/skills/skill_creator/scripts/validate_skill.sh ${COMPOSITE_DIR}"
echo "  5. Document any customizations in README.md"
echo ""
echo "Composite skill composition:"
echo "  Components: ${#COMPONENT_SKILLS[@]}"
for i in "${!COMPONENT_SKILLS[@]}"; do
    echo "    $((i+1)). ${COMPONENT_SKILLS[$i]}"
done