# Step 04: Fix Import Dependencies

## Prerequisites
- Step 03 completed (server modules implemented)
- All server modules can be created
- Python packaging structure is correct

## Objectives
1. Identify and resolve all remaining import dependencies
2. Ensure context_logic modules are available
3. Fix any circular import issues
4. Test complete import chain

## Implementation Details

### Step 1: Test All Import Chains
```bash
# Test complete import chain
python -c "
import sys
sys.path.append('.')
from _mcp.main import create_storm_mcp_server
server = create_storm_mcp_server()
print('✓ Complete import chain working')
"
```

### Step 2: Fix Missing Context Logic Functions
Some server modules may reference functions that don't exist yet. Create placeholder implementations:

```python
# In _mcp/context_logic/placeholders.py
def placeholder_function(*args, **kwargs):
    \"\"\"Placeholder function for future implementation.\"\"\"
    return {
        "status": "placeholder",
        "message": "This function will be implemented in future versions",
        "args": args,
        "kwargs": kwargs
    }
```

### Step 3: Update Server Modules with Fallbacks
Add fallback imports to server modules:

```python
# Example for coverage server
try:
    from _mcp.context_logic import coverage_analysis
except ImportError:
    from _mcp.context_logic.placeholders import placeholder_function as coverage_analysis
```

### Step 4: Fix Circular Import Issues
If circular imports exist, restructure them:

```python
# Instead of direct imports at module level
# from _mcp.context_logic import module_a

# Use lazy imports inside functions
def tool_function():
    from _mcp.context_logic import module_a
    return module_a.some_function()
```

### Step 5: Create Context Logic Module Index
Create `_mcp/context_logic/__init__.py`:

```python
"""
Context Logic Module Index
Central import location for all context logic modules
"""

# Safe imports with fallbacks
try:
    from . import coverage_analysis
except ImportError:
    coverage_analysis = None

try:
    from . import test_generation
except ImportError:
    test_generation = None

try:
    from . import workflow_optimization
except ImportError:
    workflow_optimization = None

# Add other modules as needed
```

## Testing/Validation

### Step 1: Test Individual Module Imports
```bash
# Test each context_logic module
for module in coverage_analysis test_generation workflow_optimization; do
    echo "Testing $module..."
    python -c "
import sys
sys.path.append('.')
try:
    from _mcp.context_logic import $module
    print(f'✓ {module} imported successfully')
except ImportError as e:
    print(f'✗ {module} import failed: {e}')
"
done
```

### Step 2: Test Server-to-Context Dependencies
```bash
# Test that servers can access context logic
python -c "
import sys
sys.path.append('.')
from _mcp.servers.coverage import create_coverage_server
server = create_coverage_server()
print('✓ Coverage server created with context logic')
"
```

### Step 3: Test Main Server Creation
```bash
# Test the complete server creation
python -c "
import sys
sys.path.append('.')
from _mcp.main import create_storm_mcp_server
server = create_storm_mcp_server()
print(f'✓ Main server created: {server.name}')
print(f'  Total tools: {len(server.tools)}')
"
```

## Success Criteria
- [ ] All imports work without errors
- [ ] Main server can be created successfully
- [ ] No circular import issues
- [ ] All context_logic dependencies resolved
- [ ] Placeholder functions where needed

## JSON Update Instructions

When starting this step:
```json
{
  "steps": {
    "04": {
      "status": "in_progress",
      "progress": 20,
      "issues": ["Testing import chains"],
      "next_action": "Fix missing context_logic dependencies"
    }
  }
}
```

When 50% complete (dependencies identified):
```json
{
  "steps": {
    "04": {
      "status": "in_progress",
      "progress": 50,
      "issues": ["Implementing missing functions"],
      "next_action": "Create placeholder functions and fallbacks"
    }
  }
}
```

When complete:
```json
{
  "steps": {
    "04": {
      "status": "completed",
      "progress": 100,
      "issues": [],
      "next_action": "Proceed to Step 05"
    }
  },
  "current_step": "05",
  "overall_progress": 40,
  "completed_features": [
    "All 7 server modules implemented",
    "Health check functions added",
    "Server creation working",
    "Import dependencies resolved"
  ]
}
```

## Troubleshooting

### Common Issues

1. **Missing context_logic modules**
   - Create placeholder implementations
   - Add to placeholders.py
   - Update server modules with fallbacks

2. **Circular import errors**
   - Use lazy imports inside functions
   - Restructure module dependencies
   - Consider moving shared code to utils

3. **Module not found errors**
   - Check __init__.py files exist
   - Verify module names are correct
   - Check Python path includes project root

### Debug Commands
```bash
# Check what's available in context_logic
python -c "
import sys
sys.path.append('.')
import _mcp.context_logic
print(dir(_mcp.context_logic))
"

# Test specific import
python -c "
import sys
sys.path.append('.')
try:
    from _mcp.context_logic.coverage_analysis import analyze_coverage_gaps
    print('✓ Function import works')
except ImportError as e:
    print(f'✗ Function import failed: {e}')
"
```

## Next Steps
After completing this step:
1. Update JSON status to "completed"
2. Proceed to Step 05: Create Health Check System
3. Use resolved imports to implement health checks

## Notes
- Create placeholder functions for missing implementations
- Document which functions need actual implementation later
- Ensure all imports have fallbacks
- Test thoroughly before proceeding