# Troubleshooting Guide

Common issues and solutions for DSS (Design System Server).

## Table of Contents

- [Installation Issues](#installation-issues)
- [Server Issues](#server-issues)
- [Figma Integration Issues](#figma-integration-issues)
- [Token Ingestion Issues](#token-ingestion-issues)
- [Test Failures](#test-failures)
- [Performance Issues](#performance-issues)
- [Database Issues](#database-issues)

## Installation Issues

### Python Version Error

**Problem**: `Python 3.10+ is required`

**Solution**:
```bash
# Check your Python version
python3 --version

# Install Python 3.10+ if needed (Ubuntu/Debian)
sudo apt update
sudo apt install python3.10 python3.10-venv python3-pip

# Or use pyenv
pyenv install 3.10.0
pyenv local 3.10.0
```

### pip Install Fails

**Problem**: `error: externally-managed-environment`

**Solution**:
```bash
# Use virtual environment (recommended)
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

# Or use --break-system-packages (not recommended)
pip install --break-system-packages -r requirements.txt
```

### Permission Denied on setup.sh

**Problem**: `Permission denied: ./setup.sh`

**Solution**:
```bash
chmod +x setup.sh
./setup.sh
```

## Server Issues

### Port Already in Use

**Problem**: `Address already in use: 3456`

**Solution**:
```bash
# Find process using port 3456
lsof -i :3456

# Kill the process
kill -9 <PID>

# Or use different port
PORT=3457 python -m tools.api.server
```

### ModuleNotFoundError

**Problem**: `ModuleNotFoundError: No module named 'tools'`

**Solution**:
```bash
# Ensure you're in project root
cd /path/to/dss

# Activate virtual environment
source .venv/bin/activate

# Verify Python path
python3 -c "import sys; print(sys.path)"

# Run from project root
python3 -m tools.api.server
```

### Server Starts But Can't Connect

**Problem**: Server starts but `curl http://localhost:3456/status` fails

**Solution**:
```bash
# Check server is actually running
ps aux | grep "tools.api.server"

# Check logs for errors
tail -f .dss/logs/server.log

# Verify port binding
netstat -tulpn | grep 3456

# Try 127.0.0.1 instead of localhost
curl http://127.0.0.1:3456/status
```

## Figma Integration Issues

### Figma API Returns Empty

**Problem**: `extract_variables()` returns 0 tokens

**Possible Causes & Solutions**:

1. **No Variables in File**
   ```bash
   # Check if file has Variables (requires Figma Pro/Org)
   # Variables are different from Styles
   ```

2. **Wrong File Key**
   ```bash
   # Get file key from URL:
   # https://figma.com/file/FILE_KEY/...
   # Use FILE_KEY, not the file name
   ```

3. **Invalid Token**
   ```bash
   # Verify token is valid
   curl -H "X-Figma-Token: $FIGMA_TOKEN" \
        https://api.figma.com/v1/me

   # Should return your user info
   ```

4. **Use Styles Instead**
   ```python
   # For community files, use styles
   result = await suite.extract_styles(file_key)
   ```

### Figma API Rate Limiting

**Problem**: `429 Too Many Requests`

**Solution**:
```bash
# Increase cache TTL
export FIGMA_CACHE_TTL=600  # 10 minutes

# Add delay between requests
import asyncio
await asyncio.sleep(1)
```

### Figma Token Not Found

**Problem**: `FigmaToken environment variable not set`

**Solution**:
```bash
# Add to .env file
echo "FIGMA_TOKEN=figd_your_token_here" >> .env

# Or export directly
export FIGMA_TOKEN=figd_your_token_here

# Verify
echo $FIGMA_TOKEN
```

## Token Ingestion Issues

### Tailwind Parser Returns 0 Tokens

**Problem**: Tailwind config parsed but no tokens extracted

**Known Issue**: Regex doesn't match all config formats

**Workaround**:
```python
# Use JSON tokens instead
import json
from tools.ingest.json_tokens import JSONTokenSource

# Convert Tailwind to JSON format
tokens_json = {
    "color": {
        "primary": {"value": "#3B82F6", "type": "color"}
    }
}

parser = JSONTokenSource()
result = await parser.extract(json.dumps(tokens_json))
```

### CSS Variables Not Extracted

**Problem**: CSS parsed but tokens not found

**Solution**:
```python
# Ensure using :root selector
css_content = """
:root {
    --color-primary: #3B82F6;  /* This works */
}

.class {
    --local-var: red;  /* This doesn't work (scoped) */
}
"""
```

### SCSS Import Errors

**Problem**: `@import` statements cause parsing errors

**Solution**:
```python
# DSS doesn't resolve @import
# Extract the compiled CSS instead, or inline variables
```

## Test Failures

### Async Tests Skipped

**Problem**: All `@pytest.mark.asyncio` tests skipped

**Solution**:
```bash
# Install pytest-asyncio
pip install pytest-asyncio

# Verify installation
pytest --version
# Should show: plugins: asyncio-...

# Run tests again
pytest tests/
```

### Tests Fail: "database is locked"

**Problem**: SQLite database locked during tests

**Solution**:
```bash
# Use separate test database
export TEST_DB_PATH=.dss/test.db

# Or delete lock file
rm -f .dss/dss.db-lock

# Run tests
pytest
```

### Import Errors in Tests

**Problem**: `ModuleNotFoundError` in test files

**Solution**:
```bash
# Run from project root
cd /path/to/dss

# Verify pytest.ini exists and has:
# pythonpath = .

# Run with python path
PYTHONPATH=. pytest tests/
```

## Performance Issues

### Slow File Scanning

**Problem**: Project scan takes >10 seconds

**Solution**:
```python
# Add more directories to skip
scanner = ProjectScanner(
    path=".",
    exclude=['node_modules', '.git', 'dist', 'build', '.venv']
)

# Use cache
scanner = ProjectScanner(path=".", use_cache=True)

# Scan specific subdirectories only
scanner = ProjectScanner(path="./src")
```

### High Memory Usage

**Problem**: Python process using >1GB RAM

**Solution**:
```python
# Process tokens in batches
for batch in batches(tokens, 1000):
    process_batch(batch)

# Clear collections after use
collection.tokens.clear()

# Use generators for large datasets
def token_generator():
    for token in large_dataset:
        yield process(token)
```

### Slow Figma API Calls

**Problem**: Figma extraction takes >30 seconds

**Solution**:
```bash
# Check network latency
ping api.figma.com

# Use local JSON export for development
figma export --format json

# Increase cache TTL
export FIGMA_CACHE_TTL=3600  # 1 hour
```

## Database Issues

### Database Corruption

**Problem**: `database disk image is malformed`

**Solution**:
```bash
# Backup database
cp .dss/dss.db .dss/dss.db.backup

# Try to repair
sqlite3 .dss/dss.db "PRAGMA integrity_check;"

# If corrupt, restore from backup or delete
rm .dss/dss.db
# Database will be recreated on next run
```

### Can't Write to Database

**Problem**: `attempt to write a readonly database`

**Solution**:
```bash
# Check permissions
ls -l .dss/dss.db

# Fix permissions
chmod 644 .dss/dss.db
chown $USER:$USER .dss/dss.db

# Check parent directory is writable
ls -ld .dss/
chmod 755 .dss/
```

## Getting Help

### Check Logs

```bash
# Server logs
tail -f .dss/logs/server.log

# MCP server logs
tail -f .dss/logs/mcp.log

# Application logs
python -m tools.api.server --log-level DEBUG
```

### Debug Mode

```bash
# Enable debug logging
export LOG_LEVEL=DEBUG

# Run with verbose output
python -m tools.api.server -vv
```

### Still Stuck?

1. **Search Issues**: https://github.com/your-org/dss/issues
2. **Open Issue**: Provide:
   - DSS version (`git describe --tags`)
   - Python version (`python3 --version`)
   - Operating system
   - Full error message
   - Steps to reproduce
3. **Check Documentation**:
   - README.md
   - QUICKSTART.md
   - ARCHITECTURE.md
   - CODE_QUALITY.md

## Common Error Messages

### "RuntimeError: Event loop is closed"

**Solution**:
```python
# Use asyncio.run() for top-level async calls
import asyncio

async def main():
    result = await some_async_function()

if __name__ == "__main__":
    asyncio.run(main())
```

### "JSONDecodeError: Expecting value"

**Solution**:
```python
# Check JSON is valid
import json

try:
    data = json.loads(content)
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
    print(f"Content: {content[:100]}")
```

### "ConnectionRefusedError: [Errno 111]"

**Solution**:
```bash
# Server not running - start it
python -m tools.api.server

# Or check correct host/port
curl http://127.0.0.1:3456/status
```

## Prevention Tips

1. **Always use virtual environment**
2. **Run tests before committing**
3. **Keep dependencies updated**
4. **Check logs regularly**
5. **Use .env for configuration**
6. **Back up database periodically**

---

Can't find your issue? Open a GitHub issue with details!
