> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fkapi.sunr4y.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Troubleshooting

> Common issues and solutions for FKApi development and deployment

## Quick Diagnosis

<Steps>
  <Step title="Check Services">
    Verify PostgreSQL and Redis are running
  </Step>

  <Step title="Review Logs">
    Check `fkapi/api.log` and `fkapi/logs/performance.log`
  </Step>

  <Step title="Test Connections">
    Verify database and cache connections work
  </Step>

  <Step title="Check Environment">
    Ensure `.env` file has all required variables
  </Step>
</Steps>

## Setup Issues

### Database Connection Errors

<AccordionGroup>
  <Accordion title="Error: could not connect to server">
    **Problem**: `django.db.utils.OperationalError: could not connect to server`

    **Solutions**:

    1. **Verify PostgreSQL is running**:

    ```bash theme={null}
    # On Linux/Mac
    sudo systemctl status postgresql

    # On Windows
    # Check Services panel

    # Test with pg_isready
    pg_isready
    ```

    2. **Check database credentials in `.env`**:

    ```bash theme={null}
    DATABASE_URL=postgresql://user:password@localhost:5432/fkapi
    ```

    3. **Create database if missing**:

    ```bash theme={null}
    createdb fkapi
    ```

    4. **Test connection**:

    ```bash theme={null}
    psql -U user -d fkapi -h localhost
    ```
  </Accordion>

  <Accordion title="Database does not exist">
    **Problem**: Database not created during setup

    **Solution**:

    ```bash theme={null}
    # Create database
    createdb fkapi

    # Or using psql
    psql -U postgres
    CREATE DATABASE fkapi;
    \q

    # Run migrations
    cd fkapi
    python manage.py migrate
    ```
  </Accordion>
</AccordionGroup>

### Redis Connection Errors

<AccordionGroup>
  <Accordion title="Error: connecting to Redis">
    **Problem**: `ConnectionError: Error connecting to Redis`

    **Solutions**:

    1. **Verify Redis is running**:

    ```bash theme={null}
    # On Linux/Mac
    redis-cli ping
    # Should return: PONG

    # On Windows
    # Check Services panel or use WSL
    ```

    2. **Check Redis URL in `.env`**:

    ```bash theme={null}
    REDIS_URL=redis://localhost:6379/1
    ```

    3. **Start Redis**:

    ```bash theme={null}
    # On Linux/Mac
    redis-server

    # Using Docker
    docker run -d -p 6379:6379 redis
    ```

    4. **Test connection**:

    ```bash theme={null}
    redis-cli
    127.0.0.1:6379> PING
    PONG
    ```
  </Accordion>
</AccordionGroup>

### Module Import Errors

<AccordionGroup>
  <Accordion title="ModuleNotFoundError">
    **Problem**: `ModuleNotFoundError: No module named 'core'`

    **Solutions**:

    1. **Ensure correct directory**:

    ```bash theme={null}
    cd fkapi
    pwd  # Should show .../fkapi
    ```

    2. **Activate virtual environment**:

    ```bash theme={null}
    # Linux/Mac
    source venv/bin/activate

    # Windows
    venv\Scripts\activate
    ```

    3. **Install dependencies**:

    ```bash theme={null}
    pip install -r requirements.txt
    pip install -r requirements-dev.txt
    ```

    4. **Verify installation**:

    ```bash theme={null}
    pip list | grep django
    ```
  </Accordion>
</AccordionGroup>

## Runtime Issues

### Rate Limit Exceeded

<AccordionGroup>
  <Accordion title="403 Forbidden with rate limit message">
    **Problem**: API returns 403 with rate limit error

    **Solutions**:

    1. **Wait for rate limit to reset** (default: 1 hour)

    2. **Increase rate limit in `.env`**:

    ```bash theme={null}
    API_RATE_LIMIT_RATE=200/hour
    ```

    3. **Whitelist IP for testing** (in `.env`):

    ```bash theme={null}
    RATE_LIMIT_WHITELIST=127.0.0.1,192.168.1.100
    ```

    4. **Check current rate limit status**:

    ```bash theme={null}
    redis-cli
    KEYS "ratelimit:*"
    TTL "ratelimit:127.0.0.1"
    ```

    5. **Clear rate limit** (development only):

    ```bash theme={null}
    redis-cli
    DEL "ratelimit:127.0.0.1"
    ```
  </Accordion>
</AccordionGroup>

### Slow API Responses

<AccordionGroup>
  <Accordion title="API responses are slow">
    **Solutions**:

    1. **Check Redis cache is working**:

    ```bash theme={null}
    redis-cli ping
    redis-cli KEYS "fkapi:*"
    ```

    2. **Check response time headers**:

    ```bash theme={null}
    curl -I http://localhost:8000/api/kits/arsenal-2024-home
    # Look for: X-Response-Time, X-Query-Count
    ```

    3. **Enable query logging** (temporarily in `settings.py`):

    ```python theme={null}
    LOGGING = {
        'loggers': {
            'django.db.backends': {
                'level': 'DEBUG',
            },
        },
    }
    ```

    4. **Review slow query logs**:

    ```bash theme={null}
    tail -f fkapi/logs/performance.log
    ```

    5. **Warm cache**:

    ```bash theme={null}
    python manage.py warm_cache
    ```
  </Accordion>
</AccordionGroup>

### Cache Not Working

<AccordionGroup>
  <Accordion title="Cache doesn't seem to be working">
    **Solutions**:

    1. **Verify Redis connection** (see Redis section above)

    2. **Check cache configuration** in `settings.py`:

    ```python theme={null}
    CACHES = {
        "default": {
            "BACKEND": "django.core.cache.backends.redis.RedisCache",
            "LOCATION": os.getenv("REDIS_URL"),
        }
    }
    ```

    3. **Clear cache manually**:

    ```bash theme={null}
    redis-cli FLUSHDB
    ```

    4. **Check cache keys**:

    ```bash theme={null}
    redis-cli KEYS "fkapi:*"
    ```

    5. **Test cache from Django shell**:

    ```bash theme={null}
    python manage.py shell
    >>> from django.core.cache import cache
    >>> cache.set('test', 'value', 60)
    >>> cache.get('test')
    'value'
    ```
  </Accordion>
</AccordionGroup>

### Database Migration Errors

<AccordionGroup>
  <Accordion title="InconsistentMigrationHistory">
    **Problem**: `django.db.migrations.exceptions.InconsistentMigrationHistory`

    **Solutions**:

    1. **Check migration history**:

    ```bash theme={null}
    python manage.py showmigrations
    ```

    2. **Fake migration** (use with caution):

    ```bash theme={null}
    python manage.py migrate --fake core 0001
    ```

    3. **Reset migrations** (development only):

    ```bash theme={null}
    # Delete migration files (keep __init__.py)
    # Recreate migrations
    python manage.py makemigrations
    python manage.py migrate
    ```
  </Accordion>

  <Accordion title="Migrations not applying">
    **Solutions**:

    1. **Create migrations**:

    ```bash theme={null}
    python manage.py makemigrations
    ```

    2. **Apply migrations**:

    ```bash theme={null}
    python manage.py migrate
    ```

    3. **Check for conflicts**:

    ```bash theme={null}
    python manage.py makemigrations --check
    ```
  </Accordion>
</AccordionGroup>

## Testing Issues

### Tests Failing

<AccordionGroup>
  <Accordion title="Tests fail with import errors">
    **Solutions**:

    1. **Check pytest.ini configuration**:

    ```ini theme={null}
    [pytest]
    DJANGO_SETTINGS_MODULE = test_settings
    pythonpath = fkapi
    ```

    2. **Run tests from project root**:

    ```bash theme={null}
    pytest fkapi/core/tests/
    ```

    3. **Clear test database**:

    ```bash theme={null}
    rm fkapi/test_db.sqlite3
    ```

    4. **Verify test settings**:

    ```bash theme={null}
    cat fkapi/test_settings.py
    ```
  </Accordion>
</AccordionGroup>

### Coverage Not Working

<AccordionGroup>
  <Accordion title="Coverage report shows 0% or missing files">
    **Solutions**:

    1. **Install coverage tools**:

    ```bash theme={null}
    pip install pytest-cov coverage
    ```

    2. **Run with coverage**:

    ```bash theme={null}
    pytest --cov=fkapi/core --cov-report=html
    ```

    3. **Check configuration** in `pyproject.toml`:

    ```toml theme={null}
    [tool.coverage.run]
    source = ["fkapi/core"]
    ```
  </Accordion>
</AccordionGroup>

## Scraping Issues

### Scraping Fails with Connection Errors

<AccordionGroup>
  <Accordion title="ConnectionError or timeout">
    **Problem**: `requests.exceptions.ConnectionError` or timeout

    **Solutions**:

    1. **Check internet connection**

    2. **Verify target website is accessible**:

    ```bash theme={null}
    curl -I https://www.footballkitarchive.com
    ```

    3. **Check proxy settings** in `core/http.py`

    4. **Increase timeout** in `.env`:

    ```bash theme={null}
    HTTP_TIMEOUT=30
    ```
  </Accordion>
</AccordionGroup>

### HTML Parsing Errors

<AccordionGroup>
  <Accordion title="AttributeError or KeyError during parsing">
    **Solutions**:

    1. **Check if website structure changed**

    2. **Log raw HTML for debugging**:

    ```python theme={null}
    logger.debug(f"HTML content: {html[:1000]}")
    ```

    3. **Review HTML fixtures in tests**

    4. **Add defensive checks in parsers**:

    ```python theme={null}
    name = soup.find('h1')
    if name:
        kit_name = name.text.strip()
    ```
  </Accordion>
</AccordionGroup>

### Duplicate Data Issues

<AccordionGroup>
  <Accordion title="Duplicate clubs or kits created">
    **Solutions**:

    1. **Check slug uniqueness constraints**

    2. **Use get\_or\_create()** instead of create():

    ```python theme={null}
    club, created = Club.objects.get_or_create(
        slug=slug,
        defaults={'name': name}
    )
    ```

    3. **Find duplicates**:

    ```bash theme={null}
    python manage.py shell
    >>> from django.db.models import Count
    >>> from core.models import Club
    >>> Club.objects.values('slug').annotate(count=Count('id')).filter(count__gt=1)
    ```
  </Accordion>
</AccordionGroup>

## API Issues

### 500 Internal Server Error

<AccordionGroup>
  <Accordion title="API returns 500 error">
    **Solutions**:

    1. **Check Django logs**:

    ```bash theme={null}
    tail -f fkapi/api.log
    ```

    2. **Enable DEBUG mode** (temporarily in `.env`):

    ```bash theme={null}
    DJANGO_DEBUG=True
    ```

    3. **Check database connection**

    4. **Verify environment variables**:

    ```bash theme={null}
    cat .env | grep -v "#"
    ```

    5. **Test endpoint directly**:

    ```bash theme={null}
    curl -v http://localhost:8000/api/health
    ```
  </Accordion>
</AccordionGroup>

### API Documentation Not Loading

<AccordionGroup>
  <Accordion title="/api/docs returns 404 or error">
    **Solutions**:

    1. **Verify Django Ninja is installed**:

    ```bash theme={null}
    pip list | grep django-ninja
    ```

    2. **Check URL configuration** in `fkapi/urls.py`:

    ```python theme={null}
    path('api/', api.urls),
    ```

    3. **Access correct URL**:

    ```
    http://localhost:8000/api/docs
    ```
  </Accordion>
</AccordionGroup>

## Performance Issues

### High Database Query Count

<AccordionGroup>
  <Accordion title="Too many queries per request">
    **Solutions**:

    1. **Use select\_related() for foreign keys**:

    ```python theme={null}
    Kit.objects.select_related('team', 'season')
    ```

    2. **Use prefetch\_related() for many-to-many**:

    ```python theme={null}
    Club.objects.prefetch_related('competitions')
    ```

    3. **Check query count** in response headers:

    ```bash theme={null}
    curl -I http://localhost:8000/api/kits/
    # Look for: X-Query-Count
    ```

    4. **Enable query logging** (see Slow API Responses)
  </Accordion>
</AccordionGroup>

### Memory Issues

<AccordionGroup>
  <Accordion title="High memory usage">
    **Solutions**:

    1. **Use pagination for large datasets**

    2. **Process data in chunks**:

    ```python theme={null}
    for kit in Kit.objects.all().iterator(chunk_size=1000):
        process(kit)
    ```

    3. **Clear cache periodically**:

    ```bash theme={null}
    redis-cli FLUSHDB
    ```

    4. **Monitor with django-debug-toolbar** (development)
  </Accordion>
</AccordionGroup>

## Getting More Help

<CardGroup cols={2}>
  <Card title="Check Logs" icon="file-lines">
    Review `fkapi/api.log` and `fkapi/logs/performance.log`
  </Card>

  <Card title="Enable Debug" icon="bug">
    Set `DJANGO_DEBUG=True` for detailed error messages
  </Card>

  <Card title="Documentation" icon="book">
    Review other docs in `/docs` directory
  </Card>

  <Card title="GitHub Issues" icon="github">
    Search existing issues or create new one
  </Card>
</CardGroup>

## Common Error Messages

### `django.core.exceptions.ImproperlyConfigured`

Usually means missing or incorrect settings. Check:

* Environment variables in `.env`
* Database configuration
* Redis configuration

### `django.db.utils.IntegrityError`

Database constraint violation. Check:

* Unique constraints
* Foreign key relationships
* Required fields

### `ninja.errors.ValidationError`

API request validation failed. Check:

* Required parameters
* Parameter types
* Request body format

### `core.exceptions.ScrapingError`

Scraping operation failed. Check:

* Network connectivity
* Target website availability
* HTML structure changes

***

**Still having issues?** Open an issue on GitHub with:

* Error message and full stack trace
* Steps to reproduce
* Environment details (OS, Python version, etc.)
* Relevant logs
