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

# Get or Create Score

<Note>
  **Internal Service** — This is not an HTTP endpoint. It's called by the ranking-score route.
</Note>

## Purpose

Checks if a URL already has a score in the database. If yes, returns it. If no, generates a new score (32-49) and saves it.

## Function Signature

```python theme={null}
async def get_or_create_ranking_score(website_url: str) -> int
```

## Parameters

| Parameter     | Type  | Description                              |
| ------------- | ----- | ---------------------------------------- |
| `website_url` | `str` | The URL to look up or create a score for |

## Returns

`int` - The ranking score (32-49 for new URLs, or existing stored score)

## Logic Flow

```mermaid theme={null}
flowchart TD
    A[Receive URL] --> B{Database configured?}
    B -->|No| C[Return random 32-49]
    B -->|Yes| D[Query pre_payment_rankings]
    D --> E{URL exists?}
    E -->|Yes| F[Return existing score]
    E -->|No| G[Generate random 32-49]
    G --> H[Insert into database]
    H --> I[Return new score]
```

## Why 32-49?

The score range is intentionally low to:

1. Show visitors they have "room to improve"
2. Create urgency to sign up
3. Leave headroom for competitor scores (which are always higher)

## Code

```python theme={null}
async def get_or_create_ranking_score(website_url: str) -> int:
    await ensure_initialized()
    if not supabase_ranking:
        return random.randint(32, 49)
    
    try:
        existing = await supabase_ranking.table("pre_payment_rankings") \
            .select("score").eq("website_url", website_url).execute()
        
        if existing.data and len(existing.data) > 0:
            return int(existing.data[0]["score"])
        
        new_score = random.randint(32, 49)
        await supabase_ranking.table("pre_payment_rankings").insert({
            "website_url": website_url,
            "score": new_score,
        }).execute()
        
        return new_score
    except Exception as e:
        return random.randint(32, 49)  # Fallback
```

## Error Handling

On database errors, falls back to generating a random score without saving. This ensures the endpoint always returns a response.
