# 🐄 Ranchlands Online

A production-grade, persistent browser-based ranching MMO built with React + Node.js + PostgreSQL.

## Architecture

```
ranchlands/
├── client/          # React + Vite + Tailwind frontend
├── server/          # Node.js + Express + PostgreSQL backend
├── shared/          # TypeScript types shared between client/server
└── docker-compose.yml
```

## Quick Start

### Prerequisites
- Node.js 20+
- Docker + Docker Compose (for PostgreSQL and Redis)
- npm 9+

### 1. Clone and install

```bash
git clone <your-repo>
cd ranchlands
npm install
```

### 2. Start databases

```bash
docker-compose up -d
```

### 3. Configure server environment

```bash
cp server/.env.example server/.env
# Edit server/.env if needed (defaults work out of the box with docker-compose)
```

### 4. Run database migrations and seed

```bash
npm run db:migrate
npm run db:seed
```

### 5. Start development servers

```bash
npm run dev
```

- **Client**: http://localhost:5173
- **Server**: http://localhost:3001
- **Health check**: http://localhost:3001/health

## Game Features (MVP)

| Feature | Status |
|---------|--------|
| Auth (register/login/JWT refresh) | ✅ |
| Ranch management | ✅ |
| Herd management with full CRUD | ✅ |
| Genetics engine (genotype/phenotype) | ✅ |
| Breeding with Monte Carlo preview | ✅ |
| Inbreeding coefficient calculation | ✅ |
| Market (fixed price + auctions) | ✅ |
| Anti-snipe auction extension | ✅ |
| Weekly shows with judging | ✅ |
| Seasonal leagues | ✅ |
| Dashboard with alerts | ✅ |
| Economy (fees, taxes, upkeep) | ✅ |
| Audit logging | ✅ |
| Real-time via Socket.IO | ✅ |

## API Reference

Base URL: `http://localhost:3001/api/v1`

All protected endpoints require: `Authorization: Bearer <token>`

### Auth
| Method | Path | Description |
|--------|------|-------------|
| POST | /auth/register | Create account + ranch + starter animals |
| POST | /auth/login | Email/password login |
| POST | /auth/refresh | Refresh access token |
| POST | /auth/logout | Invalidate refresh token |

### Ranch
| Method | Path | Description |
|--------|------|-------------|
| GET | /ranch/me | Own ranch details |
| GET | /ranch/me/dashboard | Dashboard data + alerts |
| PATCH | /ranch/me | Update ranch name/description |
| POST | /ranch/me/buildings | Build a building |

### Herd
| Method | Path | Description |
|--------|------|-------------|
| GET | /herd | List animals (filterable) |
| GET | /herd/:id | Animal detail + lineage + show history |
| POST | /herd/:id/feed | Feed animal (5 Gold) |
| POST | /herd/:id/treat | Treat sick animal (50 Gold) |
| POST | /herd/:id/retire | Retire elder animal |

### Breeding
| Method | Path | Description |
|--------|------|-------------|
| POST | /breed/preview | Monte Carlo offspring preview |
| POST | /breed | Initiate breeding |
| GET | /breed/active | Active pregnancies/recoveries |

### Market
| Method | Path | Description |
|--------|------|-------------|
| GET | /market/listings | Browse listings |
| POST | /market/listings | Create listing |
| DELETE | /market/listings/:id | Cancel listing |
| POST | /market/listings/:id/buy | Buy fixed listing |
| POST | /market/listings/:id/bid | Place auction bid |
| GET | /market/my-listings | Own active listings |

### Events
| Method | Path | Description |
|--------|------|-------------|
| GET | /events/shows | List shows |
| GET | /events/shows/:id | Show details + results |
| POST | /events/shows/:id/enter | Enter animal in show |
| POST | /events/shows/:id/judge | Trigger judging (admin) |
| POST | /events/shows/:id/claim-reward | Claim placement reward |
| GET | /events/season | Current season info |

## Genetics System

Each animal has two data layers:

**Genotype** (hidden, server-side only): 8 float values (0.0–1.0) stored in `animal_genotypes` table. Never exposed via API. Determines what offspring will inherit.

**Phenotype** (visible): Derived from genotype at birth with developmental noise. Fixed for life. Represents observable traits.

**Breeding algorithm:**
1. For each trait: `offspring_gene = lerp(sire_gene, dam_gene, weight) + noise`
2. Weight drawn uniformly from [0.3, 0.7] per trait (Mendelian model)
3. 2% mutation chance per trait (±15% max)
4. Inbreeding modifier applied based on Wright coefficient

**Rarity determination** (from genotype mean):
- Common: mean < 0.55
- Uncommon: mean 0.55–0.70
- Rare: mean 0.70–0.82
- Legendary: mean ≥ 0.82 AND min ≥ 0.55

## Economy Design

**Gold sinks:** market listing fees (5%), sale taxes (3%), upkeep, feeding (5G), medicine (50G), breeding (30G), building costs, show entry fees

**Gold sources:** show rewards (25–1500G), starter grant (500G), animal retirement (25G)

**Market restrictions:** New accounts cannot list for 7 days (anti-exploitation)

## Database

PostgreSQL 16 with the following main tables:
`users`, `ranches`, `buildings`, `animals`, `animal_phenotypes`, `animal_genotypes`, `lineage`, `market_listings`, `transactions`, `shows`, `show_entries`, `seasons`, `clubs`, `club_members`, `messages`, `audit_log`, `reports`

## Deployment

### Production environment variables (server)

```env
NODE_ENV=production
PORT=3001
DATABASE_URL=postgresql://user:pass@host:5432/ranchlands
JWT_SECRET=<64-char-random-string>
REFRESH_TOKEN_SECRET=<64-char-random-string>
REDIS_URL=redis://host:6379
CLIENT_URL=https://yourdomain.com
```

### Recommended stack
- **App server**: Railway, Render, or EC2
- **Database**: AWS RDS PostgreSQL or Railway PostgreSQL
- **Redis**: Upstash or Railway Redis
- **Frontend**: Vercel (point to `/client`)
- **CDN**: CloudFront for static assets

## Roadmap

See [DESIGN.docx](./ranchlands_mmo_design.docx) for the full 12-section design document covering:
- Phase 2–6 feature roadmap
- Full API design
- Security & anti-cheat plan
- Economy stability plan
- UI wireframes

---

Built with ❤️ and 🐄
