# Migration Guide

Guide for migrating to DSS or upgrading between versions.

## Table of Contents

- [New Installation](#new-installation)
- [Migrating from Manual Token Management](#migrating-from-manual-token-management)
- [Migrating from Style Dictionary](#migrating-from-style-dictionary)
- [Upgrading Between Versions](#upgrading-between-versions)
- [Database Migrations](#database-migrations)

## New Installation

### Quick Start

```bash
# Clone repository
git clone https://github.com/your-org/dss.git
cd dss

# Run automated setup
./setup.sh

# Or manual setup:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

See [QUICKSTART.md](QUICKSTART.md) for detailed installation instructions.

## Migrating from Manual Token Management

### Before: Manual CSS Variables

```css
/* Old: Manually maintained CSS variables */
:root {
    --color-primary: #3B82F6;
    --color-secondary: #10B981;
    --spacing-sm: 8px;
}
```

### After: DSS-Managed Tokens

```python
from tools.ingest.css import CSSTokenSource
from tools.ingest.figma import FigmaTools

# 1. Ingest existing CSS
css_parser = CSSTokenSource()
css_tokens = await css_parser.extract("./styles/variables.css")

# 2. Ingest from Figma (source of truth)
figma = FigmaTools()
figma_tokens = await figma.extract_variables("FILE_KEY")

# 3. Merge with Figma as priority
from tools.ingest.merge import TokenMerger, MergeStrategy
merger = TokenMerger(strategy=MergeStrategy.PREFER_FIGMA)
result = merger.merge([css_tokens, figma_tokens])

# 4. Generate new CSS
from tools.output.css import CSSGenerator
css = CSSGenerator().generate(result.collection)
```

### Migration Checklist

- [ ] Inventory existing token sources (CSS, SCSS, JSON)
- [ ] Choose source of truth (recommend Figma Variables)
- [ ] Ingest all sources into DSS
- [ ] Review and resolve conflicts
- [ ] Generate standardized output
- [ ] Update build process to use DSS
- [ ] Remove manual token files
- [ ] Update documentation

## Migrating from Style Dictionary

DSS is compatible with Style Dictionary tokens format!

### Converting Style Dictionary Tokens

```javascript
// Old: Style Dictionary config.json
{
  "source": ["tokens/**/*.json"],
  "platforms": {
    "css": {
      "transformGroup": "css",
      "buildPath": "dist/",
      "files": [{
        "destination": "tokens.css",
        "format": "css/variables"
      }]
    }
  }
}
```

```python
# New: DSS equivalent
from tools.ingest.json_tokens import JSONTokenSource
import json

# 1. Ingest Style Dictionary tokens (W3C format)
parser = JSONTokenSource()
tokens = await parser.extract(json.dumps({
    "color": {
        "primary": {
            "value": "#3B82F6",
            "type": "color"
        }
    }
}))

# 2. Use DSS for additional features
# - Merge with Figma
# - Project analysis
# - Storybook integration
# - MCP tools for AI workflows
```

### Style Dictionary → DSS Benefits

| Feature | Style Dictionary | DSS |
|---------|------------------|-----|
| Token Formats | JSON only | CSS, SCSS, Tailwind, Figma, JSON |
| Merge Strategies | Manual | 6 automated strategies |
| Code Analysis | ❌ | ✅ React, quick wins, dependencies |
| Storybook | Manual | Auto-generate stories + theme |
| AI Integration | ❌ | ✅ 32 MCP tools |
| Conflict Resolution | Manual | Automated with tracking |

## Upgrading Between Versions

### v0.5.x → v0.6.x

**Breaking Changes:** None

**New Features:**
- requirements.txt for dependency management
- setup.sh for automated installation
- CONTRIBUTING.md for open source
- CHANGELOG.md for version tracking
- Pre-commit hooks
- Comprehensive documentation

**Migration Steps:**

```bash
# 1. Pull latest changes
git pull origin main

# 2. Update dependencies
pip install -r requirements.txt

# 3. (Optional) Setup pre-commit hooks
pip install pre-commit
pre-commit install

# 4. Review CHANGELOG
cat CHANGELOG.md
```

### v0.4.x → v0.5.x

**Breaking Changes:**
- ProjectScanner now has `use_cache` parameter (default: True)

**Migration:**

```python
# Old
scanner = ProjectScanner("./path")

# New (works same, but now cached)
scanner = ProjectScanner("./path", use_cache=True)

# Disable cache if needed
scanner = ProjectScanner("./path", use_cache=False)
```

### v0.3.x → v0.4.x

**Breaking Changes:** None

**New Features:**
- Performance optimizations
- Caching for project scans

**Migration:**
```bash
# No code changes needed
pip install -r requirements.txt
```

### v0.2.x → v0.3.x

**Breaking Changes:** None

**New Features:**
- Error handling improvements
- Better exception types

**Migration:**
```python
# Old: Bare except (deprecated)
try:
    result = parser.extract(content)
except:  # Don't do this
    pass

# New: Specific exceptions
try:
    result = parser.extract(content)
except (json.JSONDecodeError, KeyError) as e:
    logger.error(f"Parse failed: {e}")
```

### v0.1.x → v0.2.x

**Breaking Changes:**
- `TokenMerger.merge()` now returns `MergeResult` object
- Access tokens via `result.collection.tokens`

**Migration:**

```python
# Old (v0.1.x)
result = merger.merge([col1, col2])
for token in result.tokens:
    print(token)

# New (v0.2.x+)
result = merger.merge([col1, col2])
for token in result.collection.tokens:  # .collection added
    print(token)

# Access conflicts
print(f"Conflicts: {result.conflicts}")
```

## Database Migrations

### SQLite Schema Changes

DSS uses automatic schema migrations. Database will be upgraded automatically on first run after update.

### Manual Migration (if needed)

```bash
# Backup existing database
cp .dss/dss.db .dss/dss.db.backup

# Remove database (will be recreated)
rm .dss/dss.db

# Restart server (creates new schema)
python -m tools.api.server
```

### Exporting Data Before Upgrade

```python
import sqlite3
import json

# Export tokens
conn = sqlite3.connect('.dss/dss.db')
cursor = conn.execute('SELECT * FROM tokens')
tokens = cursor.fetchall()

# Save to JSON
with open('tokens_backup.json', 'w') as f:
    json.dump(tokens, f)

conn.close()
```

### Importing Data After Upgrade

```python
from tools.storage.database import TokenStorage
import json

# Load backup
with open('tokens_backup.json') as f:
    tokens = json.load(f)

# Import
storage = TokenStorage()
for token_data in tokens:
    storage.save_token(token_data)
```

## Common Migration Scenarios

### Scenario 1: CSS Variables → Figma Variables

**Goal**: Move from CSS to Figma as source of truth

**Steps**:
1. Create Variables in Figma
2. Map CSS vars to Figma names
3. Ingest both sources
4. Use PREFER_FIGMA strategy
5. Generate new CSS from Figma
6. Update references
7. Delete old CSS vars

### Scenario 2: Multiple SCSS Files → Single Source

**Goal**: Consolidate scattered SCSS variables

**Steps**:
1. Ingest all SCSS files
2. Merge with LAST strategy (or manual review)
3. Resolve naming conflicts
4. Generate single output file
5. Update imports
6. Delete old SCSS files

### Scenario 3: Adding Storybook to Existing Project

**Goal**: Add Storybook with DSS-generated theme

**Steps**:
1. Scan project for components
2. Extract existing tokens
3. Generate Storybook theme
4. Generate initial stories
5. Customize stories as needed

## Rollback Procedures

### If Migration Fails

```bash
# 1. Restore code
git checkout v0.5.2  # or previous version

# 2. Restore database
cp .dss/dss.db.backup .dss/dss.db

# 3. Restore dependencies
pip install -r requirements.txt

# 4. Verify
python test_quick.py
```

### Report Migration Issues

If you encounter migration issues:

1. **Backup your data** first
2. **Check CHANGELOG.md** for breaking changes
3. **Review TROUBLESHOOTING.md** for common issues
4. **Open an issue** with:
   - Current version
   - Target version
   - Error message
   - Migration steps attempted

## Getting Help

- **Documentation**: [QUICKSTART.md](QUICKSTART.md)
- **Troubleshooting**: [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
- **Issues**: https://github.com/your-org/dss/issues
- **Discussions**: https://github.com/your-org/dss/discussions

---

**Best Practice**: Always backup your database before upgrading!
