# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

Cloudflare Worker-based AI server recommendation service. Uses Workers AI (Llama 3.1 8B), D1 database, and VPS benchmark data to recommend cost-effective servers based on natural language requirements.

**Production URL**: `https://server-recommend.kappa-d8e.workers.dev`

## Commands

```bash
# Development
npm run dev              # Start local development server (wrangler dev)
npm run deploy           # Deploy to Cloudflare Workers
npm run typecheck        # TypeScript type checking

# Database operations (D1)
npx wrangler d1 execute cloud-instances-db --file=schema.sql        # Apply schema
npx wrangler d1 execute cloud-instances-db --file=seed.sql          # Seed data
npx wrangler d1 execute cloud-instances-db --command="SELECT ..."   # Ad-hoc queries

# View logs
npx wrangler tail
```

## Architecture

```
src/index.ts (single file Worker)
├── handleHealth()           GET /api/health
├── handleGetServers()       GET /api/servers - List servers with filtering
└── handleRecommend()        POST /api/recommend - AI-powered recommendations
    ├── validateRecommendRequest()
    ├── queryCandidateServers()     → D1: instance_types + providers + pricing + regions
    ├── queryBenchmarkData()         → D1: benchmark_results + benchmark_types
    ├── queryVPSBenchmarks()         → D1: vps_benchmarks (Geekbench 6)
    └── getAIRecommendations()       → Workers AI (Llama 3.1 8B)
```

### Key Data Flow

1. User sends natural language request (`tech_stack`, `expected_users`, `use_case`, `region_preference`)
2. `queryCandidateServers()` finds matching servers with **flexible region matching** (supports country codes, names, city names)
3. `queryVPSBenchmarks()` retrieves Geekbench 6 scores, **prioritizing same provider match**
4. AI analyzes and returns 3 tiers: Budget, Balanced, Premium

### D1 Database Tables (cloud-instances-db)

- `providers` - Cloud providers (50+)
- `instance_types` - Server specifications
- `pricing` - Regional pricing
- `regions` - Geographic regions
- `vps_benchmarks` - Geekbench 6 benchmark data (269 records, manually seeded)
- `benchmark_results` / `benchmark_types` / `processors` - Phoronix benchmark data

## Key Implementation Details

### Flexible Region Matching (`queryCandidateServers`)

Region matching supports multiple input formats:
```sql
LOWER(r.region_code) = ? OR
LOWER(r.region_code) LIKE ? OR
LOWER(r.region_name) LIKE ? OR
LOWER(r.country_code) = ?
```

Valid inputs: `"korea"`, `"KR"`, `"seoul"`, `"ap-northeast-2"`

### Provider-Priority Benchmark Matching (`queryVPSBenchmarks`)

1. First tries exact provider match
2. Falls back to similar spec match from any provider
3. Used to attach real benchmark data to recommendations

### AI Prompt Strategy

- System prompt emphasizes cost-efficiency and minimum viable specs
- Tech stack → resource guidelines (e.g., "Nginx: 1 vCPU per 1000 users")
- Scoring: Cost efficiency (40%) + Capacity fit (30%) + Scalability (30%)
- Budget option should score highest if viable

## Bindings (wrangler.toml)

```toml
[ai]
binding = "AI"

[[d1_databases]]
binding = "DB"
database_name = "cloud-instances-db"
database_id = "bbcb472d-b25e-4e48-b6ea-112f9fffb4a8"

# KV Cache (optional, not configured)
# binding = "CACHE"
```

## Testing

```bash
# Health check
curl https://server-recommend.kappa-d8e.workers.dev/api/health

# Recommendation
curl -X POST https://server-recommend.kappa-d8e.workers.dev/api/recommend \
  -H "Content-Type: application/json" \
  -d '{
    "tech_stack": ["php", "mysql"],
    "expected_users": 1000,
    "use_case": "community forum",
    "region_preference": ["korea"]
  }'
```

## Known Limitations

- AI recommendations may be inaccurate for specialized workloads (game servers, Minecraft)
- KV cache is not currently configured (CACHE binding commented out in wrangler.toml)
- `src/types.ts` contains legacy type definitions (not actively used, actual types inline in index.ts)
