# /designfast:create-design-system Command

## Description
创建可重用的设计系统，包括颜色、字体、间距、断点等设计令牌，以及组件规范。

## Syntax
```
# /designfast:create-design-system Command

## Description
创建可重用的设计系统，包括颜色、字体、间距、断点等设计令牌，以及组件规范。

## Syntax
```
/designfast:create-design-system --name="系统名称" [options]
```

## Parameters

### Required
- `--name=<name>`: 设计系统名称

### Optional
- `--description=<desc>`: 设计系统描述
- `--project-id=<id>`: 关联的项目ID（可选）
- `--output=<path>`: 输出路径（默认：workspace/designs/design-systems/）
- `--base-system=<system>`: 基于现有系统创建（ID或名称）

## Implementation

### Parameter Parsing
```powershell
param(
    [Parameter(Mandatory=$true)]
    [string]$Name,
    
    [Parameter(Mandatory=$false)]
    [string]$Description,
    
    [Parameter(Mandatory=$false)]
    [string]$ProjectId,
    
    [Parameter(Mandatory=$false)]
    [string]$OutputPath = "workspace/designs/design-systems",
    
    [Parameter(Mandatory=$false)]
    [string]$BaseSystem
)

# Validate required parameters
if ([string]::IsNullOrWhiteSpace($Name)) {
    Write-Error "Design system name is required. Use --name=""System Name"""
    exit 1
}

# Validate name length
if ($Name.Length -lt 3 -or $Name.Length -gt 100) {
    Write-Error "Design system name must be between 3-100 characters"
    exit 1
}
```

### Workflow Execution

#### Stage 1: Input Validation
```powershell
# Check for existing design system with same name
$existingSystems = & "$PSScriptRoot\..\scripts\design-system-manager.ps1" -Action list
$duplicateSystem = $existingSystems | Where-Object { $_.name -eq $Name }

if ($duplicateSystem) {
    Write-Error "Design system with name '$Name' already exists (ID: $($duplicateSystem.id))"
    exit 1
}

# Validate base system if specified
if ($BaseSystem) {
    $baseSystemData = $null
    if ([guid]::TryParse($BaseSystem, [ref]$null)) {
        # BaseSystem is an ID
        $baseSystemData = & "$PSScriptRoot\..\scripts\design-system-manager.ps1" -Action read -DesignSystemId $BaseSystem
    } else {
        # BaseSystem is a name - find by name
        $baseSystemData = $existingSystems | Where-Object { $_.name -eq $BaseSystem }
    }
    
    if (-not $baseSystemData) {
        Write-Error "Base design system not found: $BaseSystem"
        exit 1
    }
    
    Write-Host "✓ Using base system: $($baseSystemData.name)" -ForegroundColor Green
}
```

#### Stage 2: Design System Creation
```powershell
Write-Host "Creating design system: $Name" -ForegroundColor Cyan

# Create design system using manager script
$systemData = & "$PSScriptRoot\..\scripts\design-system-manager.ps1" `
    -Action create `
    -Name $Name `
    -Description $Description `
    -ProjectId $ProjectId

if (-not $systemData) {
    Write-Error "Failed to create design system"
    exit 1
}

Write-Host "✓ Design system created with ID: $($systemData.id)" -ForegroundColor Green
```

#### Stage 3: Documentation Generation
```powershell
# Prepare template data
$templateData = @{
    system = $systemData
    generation = @{
        timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    }
    version = "1.0.0"  # DesignFast version
}

# Generate documentation using Handlebars
$templatePath = "$PSScriptRoot\..\templates\design-system-template.md"
$systemDir = "$OutputPath\$($systemData.id)"
$outputPath = "$systemDir\design-system.md"

# Ensure system directory exists
if (-not (Test-Path $systemDir)) {
    New-Item -ItemType Directory -Path $systemDir -Force | Out-Null
}

# Generate documentation
$dataJson = $templateData | ConvertTo-Json -Depth 10 -Compress
$handlebarsScript = @"
const Handlebars = require('handlebars');
const fs = require('fs');

try {
    const template = Handlebars.compile(fs.readFileSync('$templatePath', 'utf8'));
    const result = template($dataJson);
    fs.writeFileSync('$outputPath', result, 'utf8');
    console.log('✓ Design system documentation generated');
} catch (error) {
    console.error('✗ Failed to generate documentation:', error.message);
    process.exit(1);
}
"@

# Execute Handlebars generation
$handlebarsScript | node

if ($LASTEXITCODE -ne 0) {
    Write-Error "Failed to generate design system documentation"
    exit 1
}

Write-Host "✓ Documentation generated: $outputPath" -ForegroundColor Green
```

#### Stage 4: Token Extraction (Optional)
```powershell
# Extract tokens to separate JSON file for easy consumption
$tokensPath = "$systemDir\tokens.json"
$systemData.tokens | ConvertTo-Json -Depth 10 | Out-File -FilePath $tokensPath -Encoding utf8 -NoNewline

# Extract components to separate JSON file
$componentsPath = "$systemDir\components.json"
$systemData.components | ConvertTo-Json -Depth 10 | Out-File -FilePath $componentsPath -Encoding utf8 -NoNewline

Write-Host "✓ Token files extracted" -ForegroundColor Green
```

#### Stage 5: Validation & Summary
```powershell
# Validate generated files
$filesToCheck = @($systemData.PSObject.Properties.Name | Where-Object { $_ -match '\.json$' } | ForEach-Object { "$systemDir\$_" })
$filesToCheck += $outputPath

foreach ($file in $filesToCheck) {
    if (-not (Test-Path $file)) {
        Write-Warning "Expected file not found: $file"
    }
}

# Display summary
Write-Host "`n🎉 Design system '$Name' created successfully!" -ForegroundColor Green
Write-Host "System ID: $($systemData.id)" -ForegroundColor White
Write-Host "Location: $systemDir" -ForegroundColor White
Write-Host "Documentation: $outputPath" -ForegroundColor White

# Return system data for potential chaining
return $systemData
```
```

## Parameters

### Required
- `--name=<name>`: 设计系统名称

### Optional
- `--description=<desc>`: 设计系统描述
- `--project-id=<id>`: 关联的项目ID（可选）
- `--base-system=<system>`: 基于现有系统创建（ID或名称）
- `--output=<path>`: 输出路径（默认：workspace/designs/design-systems/）

## Workflow

### Stage 1: Input Validation
1. 检查设计系统名称是否唯一
2. 验证名称长度（3-100字符）
3. 如果指定base-system，检查其存在性

### Stage 2: Design System Creation
1. 调用design-system-manager脚本
2. 创建设计系统实体
3. 生成默认令牌和组件规范

```powershell
# 示例PowerShell实现
$systemData = & "$PSScriptRoot\..\scripts\design-system-manager.ps1" `
    -Action create `
    -Name $Name `
    -Description $Description `
    -ProjectId $ProjectId
```

### Stage 3: Token Generation
1. 生成颜色调色板
2. 定义字体层级
3. 设置间距比例
4. 配置响应式断点

```powershell
# 令牌生成逻辑已在design-system-manager.ps1中实现
# 这里主要处理基于现有系统的令牌继承
if ($baseSystemData) {
    # 继承基础系统的令牌，但允许覆盖
    Write-Host "Inheriting tokens from base system: $($baseSystemData.name)" -ForegroundColor Blue
    # 合并逻辑已在manager脚本中处理
}
```

### Stage 4: Component Definitions
1. 定义基础组件（按钮、输入框等）
2. 设置组件变体和尺寸
3. 生成组件使用指南

```powershell
# 组件定义已在design-system-manager.ps1中实现
# 基础组件包括：按钮、输入框、卡片等
```

### Stage 5: Documentation Generation
1. 使用Handlebars模板
2. 生成设计系统文档
3. 创建使用指南

```powershell
# 已在上面的实现中完成
```

### Stage 6: Validation
1. 验证令牌完整性
2. 检查组件定义
3. 确保JSON格式正确

```powershell
# 验证令牌完整性
function Test-DesignSystemTokens {
    param($tokens)
    
    # 检查必需的颜色令牌
    $requiredColors = @('primary', 'secondary', 'neutral', 'background', 'text')
    foreach ($color in $requiredColors) {
        if (-not $tokens.colors.$color) {
            Write-Warning "Missing required color token: $color"
        }
    }
    
    # 检查字体大小
    if (-not $tokens.typography.fontSize.base) {
        Write-Warning "Missing base font size"
    }
    
    # 检查间距
    if (-not $tokens.spacing.'4') {
        Write-Warning "Missing standard spacing token (4)"
    }
    
    # 检查断点
    if (-not $tokens.breakpoints.md) {
        Write-Warning "Missing medium breakpoint"
    }
}

# 执行验证
Test-DesignSystemTokens -tokens $systemData.tokens
```

## Examples

### Basic Usage
```bash
/designfast:create-design-system --name="My Design System"
```

### With Description
```bash
/designfast:create-design-system --name="Corporate Brand System" --description="企业品牌设计系统"
```

### Linked to Project
```bash
/designfast:create-design-system --name="E-commerce System" --project-id="123e4567-e89b-12d3-a456-426614174000"
```

### Based on Existing System
```bash
/designfast:create-design-system --name="Mobile Variant" --base-system="existing-system-id"
```

## Output

创建以下文件结构：
```
workspace/designs/design-systems/{system-id}/
├── {system-id}.json          # 设计系统数据
├── design-system.md          # 文档和使用指南
├── tokens.json               # 提取的令牌（可选）
└── components.json           # 组件规范（可选）
```

## Error Handling

- **名称冲突**: 如果名称已存在，返回错误
- **无效令牌**: 验证颜色格式、单位等
- **模板错误**: 检查Handlebars模板是否存在
- **文件权限**: 确保输出目录可写

## Dependencies

- design-system-manager.ps1
- Handlebars.js (for documentation generation)
- Node.js runtime

## Related Commands

- `/designfast:apply-design-system`: 将设计系统应用到项目
- `/designfast:list-design-systems`: 列出所有设计系统
- `/designfast:export-design-system`: 导出设计系统