# Migration Guide - Unified Template Architecture

## 🎯 Overview

This guide helps you migrate from the previous template system to the new unified template architecture with layered override system. The new system provides:

- **Unified template management** across all project types
- **Layered override system** (Local > Feature > Template > Framework)  
- **Framework integrity protection** for safe updates
- **Feature-aware tooling** that adapts to enabled features
- **Complete tooling integration** (just, CSS, configs, scripts)

## 🚀 Quick Migration (5 Minutes)

For most projects, migration is automatic:

```bash
# 1. Update to latest Rustelo version
cargo install rustelo-cli --git https://github.com/your-org/rustelo

# 2. Run automatic migration
cargo rustelo migrate --from-legacy --backup

# 3. Validate integrity
cargo rustelo integrity validate --detailed

# 4. Test your project
just dev
```

## 📋 Migration Checklist

### Before Migration
- [ ] **Backup your project**: `cp -r my-project my-project-backup`
- [ ] **Document customizations**: Note any custom templates or overrides
- [ ] **Check git status**: Ensure working directory is clean
- [ ] **Update Rustelo**: Install latest version with new CLI

### During Migration  
- [ ] **Run migration tool**: `cargo rustelo migrate --interactive`
- [ ] **Review changes**: Check generated files and moved configurations
- [ ] **Update dependencies**: Run `cargo update` if needed
- [ ] **Test build**: Ensure project builds with `just build`

### After Migration
- [ ] **Validate integrity**: `cargo rustelo integrity validate`
- [ ] **Test functionality**: Verify all features work as expected
- [ ] **Update documentation**: Note any changes in project README
- [ ] **Commit changes**: Commit migrated project to version control

## 🔄 Specific Migration Scenarios

### Scenario 1: Basic Project (No Custom Templates)

**Before**: Standard Rustelo project with default templates
**After**: Uses unified template system automatically

```bash
# Migration is automatic
cargo rustelo migrate
```

**Changes**:
- Templates now resolved through layered system
- Configuration moved to `config/` directory structure
- Tooling commands available through layered justfile

### Scenario 2: Custom Templates in foundation/templates/

**Before**: Custom templates in `crates/foundation/templates/`
**After**: Templates moved to appropriate layer

```bash
# Interactive migration with template analysis
cargo rustelo migrate --interactive --analyze-templates

# Review suggested moves:
# foundation/templates/custom.html → config/local/templates/custom.html
# foundation/templates/build.rs → templates/shared/build.rs.template
```

**Manual Steps**:
1. Review template analysis report
2. Confirm template categorization (local vs shared)
3. Update template references in your code

### Scenario 3: Heavy Customization (Multiple Features)

**Before**: Extensively customized project with multiple features
**After**: Organized through layered override system

```bash
# Comprehensive migration with feature detection
cargo rustelo migrate --comprehensive --detect-features

# Features detected and organized:
# analytics/ → config/features/analytics/
# smart-build/ → config/features/smart-build/
# custom-routes/ → config/local/routes/
```

**Post-Migration Structure**:
```
my-project/
├── config/
│   ├── local/          # Your local overrides (highest precedence)
│   ├── features/       # Feature-specific configurations
│   └── templates/      # Base template configurations
├── src/                # Your application code
└── scripts/            # Organized automation scripts
```

### Scenario 4: Team Project with Multiple Developers

**Before**: Inconsistent template usage across team
**After**: Standardized layered system

```bash
# Team lead runs migration
cargo rustelo migrate --team-mode --create-shared-config

# Generates shared configuration for team
# Creates .rustelo/team-config.toml
# Updates .gitignore for proper sharing
```

**Team Benefits**:
- Consistent development environment
- Safe customization without breaking updates
- Clear separation of shared vs personal overrides

## 🛠️ New Workflows

### Development Workflow

```bash
# 1. Start development with all enabled features
just dev-full

# 2. Make changes to components/content/config
# Changes are hot-reloaded automatically

# 3. Quality check before committing  
just quality  # Runs formatting, linting, tests, and integrity validation

# 4. Commit with automatic validation
git add . && git commit -m "Your changes"
# Pre-commit hook runs integrity validation automatically
```

### Feature Management Workflow

```bash
# Add new feature to project
cargo rustelo add analytics

# What happens:
# - Feature dependencies added to Cargo.toml
# - Feature templates installed to config/features/analytics/
# - Justfile updated with analytics commands
# - UnoCSS config extended with analytics styles

# Remove feature cleanly
cargo rustelo remove analytics
# Removes all feature-specific configurations safely
```

### Customization Workflow

```bash
# 1. Override a template locally (highest precedence)
cargo rustelo override template justfile
# Creates config/local/justfile with current content
# Edit this file - your changes will take precedence

# 2. Override component behavior
cargo rustelo override component NavBar
# Creates src/components/local/NavBar.rs
# Implement your custom navigation bar

# 3. Add local configuration
echo 'theme_color = "#ff6b6b"' >> config/local/app.toml
# Local config overrides feature and base configs
```

### Update Workflow

```bash
# 1. Check update safety
cargo rustelo integrity validate --target-version 0.2.0

# 2. Safe update (if validation passes)
cargo rustelo update --version 0.2.0

# 3. If validation fails, repair first
cargo rustelo integrity repair --auto
cargo rustelo integrity validate
cargo rustelo update --version 0.2.0

# 4. Verify after update
just test-all
```

## 🗂️ New Directory Structure

### Before Migration
```
my-project/
├── crates/
│   └── foundation/
│       └── templates/     # Custom templates (problematic)
├── src/
├── config/               # Some configs
└── scripts/              # Some scripts
```

### After Migration
```
my-project/
├── config/
│   ├── local/            # Local overrides (highest precedence)
│   │   ├── justfile      # Custom commands
│   │   ├── app.toml      # App-specific config
│   │   └── templates/    # Local template overrides
│   ├── features/         # Feature-specific configurations
│   │   ├── analytics/
│   │   │   ├── justfile  # Analytics commands
│   │   │   ├── uno.config.ts # Analytics styles
│   │   │   └── package.json # Analytics dependencies
│   │   └── smart-build/
│   │       └── justfile  # Smart build commands
│   └── templates/        # Base template configurations
├── src/
│   ├── components/
│   │   ├── local/        # Local component overrides
│   │   └── features/     # Feature-specific components
│   └── content/
├── scripts/              # Organized by category
│   ├── local/           # Local automation
│   ├── features/        # Feature-specific scripts
│   └── templates/       # Base scripts
└── templates/           # Project template files
    └── shared/          # Shared templates for generation
```

## 🔧 CLI Command Changes

### Template Management
```bash
# OLD: No unified template management
# NEW: Comprehensive template system

cargo rustelo template list                    # List all available templates
cargo rustelo template show justfile          # Show template content
cargo rustelo template customize justfile     # Create local override
cargo rustelo template sync                   # Sync with latest templates
```

### Feature Management  
```bash
# OLD: Manual feature configuration
# NEW: Integrated feature system

cargo rustelo features list                   # List available features
cargo rustelo features enabled               # Show enabled features
cargo rustelo add analytics                  # Add feature with all configs
cargo rustelo remove smart-build            # Remove feature cleanly
cargo rustelo features sync                  # Update feature configurations
```

### Override Management
```bash
# NEW: Layered override system

cargo rustelo list-overrides                 # Show active overrides
cargo rustelo override template justfile     # Override template locally
cargo rustelo override component NavBar      # Override component locally
cargo rustelo trace template justfile        # Show resolution path
cargo rustelo remove-override template justfile # Remove local override
```

### Integrity Protection
```bash
# NEW: Framework integrity validation

cargo rustelo integrity validate             # Check integrity
cargo rustelo integrity validate --detailed  # Detailed validation report
cargo rustelo integrity repair              # Auto-repair violations
cargo rustelo integrity init                # Setup integrity protection
```

## 🚨 Common Issues and Solutions

### Issue 1: "Template not found" after migration

**Problem**: Old template references in code
**Solution**:
```bash
# Find old references
grep -r "foundation/templates" src/
# Update to use layered system
cargo rustelo trace template <template_name>
```

### Issue 2: Custom justfile commands missing

**Problem**: Commands defined in old locations
**Solution**:
```bash
# Create local override
cargo rustelo override template justfile
# Add your custom commands to config/local/justfile
```

### Issue 3: Integrity validation fails

**Problem**: Code violates framework boundaries  
**Solution**:
```bash
# Get detailed violation report
cargo rustelo integrity validate --detailed

# Auto-repair common issues
cargo rustelo integrity repair

# Manual fixes for critical violations
# (Follow suggestions in validation report)
```

### Issue 4: Feature conflicts after migration

**Problem**: Multiple features providing conflicting configurations
**Solution**:
```bash
# Check feature status
cargo rustelo features status

# Resolve conflicts through local overrides
cargo rustelo override config <conflicting_config>
```

### Issue 5: Build performance regression

**Problem**: New layered system seems slower
**Solution**:
```bash
# Enable smart-build feature
cargo rustelo add smart-build

# Use cached builds
just build-cached

# Optimize cache
just cache-optimize
```

## 📊 Benefits Comparison

### Development Experience

| Aspect | Before | After |
|--------|---------|-------|
| Template Management | Manual files | Unified system with CLI |
| Feature Integration | Manual configuration | Automatic with `rustelo add` |
| Customization | Risky modifications | Safe layered overrides |
| Team Collaboration | Inconsistent setups | Standardized configurations |
| Framework Updates | Often broke customizations | Protected integrity system |

### Code Quality

| Aspect | Before | After |
|--------|---------|-------|
| Consistency | Manual enforcement | Automated validation |
| Documentation | Scattered | Centralized and generated |
| Testing | Project-specific | Integrated test patterns |
| Performance | Variable | Optimized with smart-build |

## 🎓 Learning Path

### Week 1: Basic Usage
- [ ] Complete migration checklist
- [ ] Learn new CLI commands (`rustelo --help`)
- [ ] Practice override system (`rustelo override --help`)
- [ ] Understand layered precedence (Local > Feature > Template > Framework)

### Week 2: Advanced Features
- [ ] Add your first feature (`rustelo add analytics`)
- [ ] Customize feature configuration
- [ ] Learn integrity validation (`rustelo integrity validate`)
- [ ] Practice safe update workflow

### Week 3: Team Integration
- [ ] Set up shared team configuration
- [ ] Document team-specific overrides
- [ ] Implement CI/CD with integrity checks
- [ ] Train team members on new workflows

### Month 2+: Mastery
- [ ] Create custom features
- [ ] Contribute to framework templates
- [ ] Optimize build performance with smart caching
- [ ] Help other teams migrate

## 💡 Tips and Best Practices

### Template Customization
- **DO**: Use local overrides for project-specific changes
- **DON'T**: Modify framework core files directly
- **TIP**: Use `cargo rustelo trace` to understand resolution

### Configuration Management
- **DO**: Keep sensitive config in environment variables
- **DON'T**: Commit secrets to configuration files
- **TIP**: Use `.env.example` for configuration templates

### Feature Integration
- **DO**: Add features through CLI for proper integration
- **DON'T**: Manually copy feature files
- **TIP**: Check feature compatibility before adding multiple features

### Update Safety
- **DO**: Run integrity validation before updates
- **DON'T**: Force updates when validation fails
- **TIP**: Use auto-repair for common violations

### Team Collaboration
- **DO**: Share feature configurations through version control
- **DON'T**: Share local overrides unless specifically needed
- **TIP**: Document team conventions in project README

## 📞 Getting Help

### Self-Service Resources
1. **CLI Help**: `cargo rustelo help <command>` 
2. **Template Documentation**: `cargo rustelo template docs`
3. **Integrity Reports**: `cargo rustelo integrity validate --detailed`
4. **Feature Guide**: `cargo rustelo features docs`

### Community Support
1. **GitHub Issues**: Report bugs and request features
2. **Discussions**: Ask questions and share experiences
3. **Discord/Slack**: Real-time help from community
4. **Documentation**: Comprehensive guides and examples

### Professional Support
1. **Migration Assistance**: Paid migration support for complex projects
2. **Custom Features**: Development of organization-specific features
3. **Training**: Team training on new architecture
4. **Consulting**: Architecture review and optimization

---

**Remember**: Migration is designed to be safe and incremental. Start small, validate often, and don't hesitate to ask for help if you encounter issues.
