Metadata-Version: 2.4
Name: lol-history-api
Version: 0.4.0
Summary: League of Legends history bridge and Python client SDK
Author: LoL History API contributors
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: aiohttp<4,>=3.9
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"

# LoL History API

A local Windows bridge for League of Legends match history, player rank, and deterministic match analysis.

The service reads credentials from the logged-in League client and exposes a small HTTP API for local tools or a bot. Authentication tokens are never returned by the API.
## 中文文档

完整的部署、Nginx 公网转发、Python SDK、接口参考、安全配置和故障排查，请阅读：

- [`docs/usage.zh-CN.md`](docs/usage.zh-CN.md)

## Project Structure

```text
lol_history_api/
  api.py          aiohttp routes, validation, HTTP error mapping
  service.py      player and match-history use cases
  ai.py           DeepSeek client, privacy redaction, and report prompts
  ai.py           DeepSeek client, privacy redaction, and report prompts
  clients.py      LCU and Tencent RSO/SGP network clients
  credentials.py League client process/log credential discovery
  regions.py      region whitelist and SGP URL routing
  normalizers.py  pure response and rank normalization helpers
  matches.py      stable match response construction
  analytics.py    ROFL-style deterministic metrics and scoring
python -m lol_history_api module entry point
tests/            unit tests with no live League client required
```

Dependencies flow inward from HTTP to services to clients/pure transformations. Network code is isolated from scoring and response normalization, so each layer can be tested independently.

## Start

```powershell
python -m pip install -r requirements.txt
python -X utf8 -m lol_history_api
```

The League client must be running and logged in.

## Endpoints

### Health

```text
GET /health
```

### Regions

```text
GET /lol/regions
```

### Player and Current Rank

```text
GET /lol/player?game_name=Player&tag_line=1234
GET /lol/player?region=HN10&game_name=Player&tag_line=1234
```

The normalized `player.ranked` object contains:

```json
{
  "available": true,
  "solo": {
    "queue_type": "RANKED_SOLO_5x5",
    "tier": "DIAMOND",
    "division": "II",
    "league_points": 70,
    "wins": 120,
    "losses": 98,
    "games": 218
  },
  "flex": null,
  "queues": [],
  "raw": {}
}
```

The LCU client may expose rank for an arbitrary PUUID through `ranked-stats/{puuid}`. If that is unavailable, the bridge only falls back to `current-ranked-stats` when the requested PUUID belongs to the currently logged-in account. In other cases `available` is `false` instead of failing the whole request.

### Match History

```text
GET /lol/history?game_name=Player&tag_line=1234&count=10
GET /lol/history?region=HN10&game_name=Player&tag_line=1234&count=10
```

`count` is limited to 1-20.

### Player Scouting

```text
GET /lol/scout?region=HN10&game_name=Player&tag_line=1234&count=20
```

The scouting report aggregates recent matches into:

- Champion pool and win rates.
- Primary and secondary positions.
- Aggression, stability, teamplay, farming, vision, objective, economy, and survival scores.
- Recent average KDA, CS, gold, damage, vision, and deterministic style labels.
- Sample size and confidence instead of unsupported absolute conclusions.

### Jungle Pathing Profile

```text
GET /lol/scout/jungle?region=HN10&game_name=Player&tag_line=1234&count=20
```

Version 0.2.2 analyzes only matches where the target has the Jungle position or Smite. It loads cached Timeline data with a maximum of four concurrent upstream requests and returns:

- The inferred first camp and whether the start was an invade.
- Minute-by-minute positions and a first-five-minute route.
- Top, middle, and bottom activity preferences during the first 14 minutes.
- First Gank time and lane, plus level 3 and level 4 early-Gank detection.
- Dragon, Voidgrub, Herald, and Baron participation.
- Multi-game start-camp, Gank-lane, route-zone, objective, and confidence aggregates.

Start camps and route preferences are coordinate-based inferences rather than exact server-provided labels.

### Post-game Event Analysis

```text
GET /lol/matches/123456789/analysis?region=HN10&game_name=Player&tag_line=1234
```

Version 0.2.2 automatically loads and caches Timeline from the local LCU `game-timelines` endpoint when no region is supplied, or Tencent SGP `DETAILS` when an explicit region is supplied. A custom `HistoryService(timeline_provider=...)` can still override the automatic sources. The API classifies target-player deaths such as `solo_death`, `gank_death`, `tower_dive_death`, and `teamfight_death`. If Timeline is unavailable, the response returns `review.available=false` and never invents missing events.

The normalized Timeline is also available directly:

```text
GET /lol/matches/123456789/timeline?region=HN10&game_name=Player&tag_line=1234
```

Each match keeps the original compatible summary fields and adds:

- `player`: complete target participant payload.
- `participants`: all participant payloads returned upstream.
- `participant_identities`: LCU participant-to-player mapping.
- `participant_analyses`: normalized ROFL-style analysis for every participant.
- `teams`: team and objective payloads.
- `analysis`: deterministic ROFL-style target-player analysis.
- `raw`: complete upstream match payload.

The `analysis` object includes:

- Position, team, level, items, summoner spells, and perks.
- KDA, champion damage, damage taken, healing, shielding, crowd control, and time dead.
- Gold, lane minions, jungle minions, and total CS.
- Vision score, wards placed, wards cleared, and control wards.
- Turrets, dragons, barons, elders, heralds, Atakhan, stolen objectives, and objective damage.
- Kill participation, damage share, gold share, and per-minute rates.
- Combat, economy, farm, objective, vision, teamplay, survival, and total score.

## ROFL Comparison

The API can produce analysis close to the final-statistics portion of `rofl_analysis`, but it cannot invent fields that the selected LCU/SGP response does not contain.

Match history provides final participant and team statistics, while LCU Timeline and SGP DETAILS add minute frames, positions, purchases, wards, skill levels, objectives, and combat events. A `.rofl` replay may still contain additional replay metadata, while none of these sources provide voice communication or complete decision-level interpretation.

## AI Analysis (0.3.0)

Version 0.3.0 adds optional DeepSeek reports on top of the existing deterministic analytics:

```text
GET /lol/scout/ai?region=HN10&game_name=Player&tag_line=1234&count=20
GET /lol/scout/jungle/ai?region=HN10&game_name=Player&tag_line=1234&count=20
GET /lol/matches/123456789/analysis/ai?region=HN10&game_name=Player&tag_line=1234
```

Configure the Windows bridge process before starting the API:

```powershell
$env:DEEPSEEK_API_KEY = "your-deepseek-api-key"
$env:DEEPSEEK_MODEL = "deepseek-v4-flash"
$env:DEEPSEEK_MODEL_VERSION = "DeepSeek-V4-Flash-0731"
python -X utf8 -m lol_history_api
```

Optional settings are `DEEPSEEK_BASE_URL`, `DEEPSEEK_TIMEOUT`, and `DEEPSEEK_MAX_TOKENS`. AI results are cached for ten minutes by default. Player names, Riot IDs, PUUIDs, account IDs, and summoner IDs are removed from the payload sent to the AI provider. Each response includes both `report` and the original deterministic `analytics`, so callers can verify the evidence. AI output is advisory and must not be treated as exact hidden-game-state data.

## AI Test Readiness (0.4.0)

Version 0.4.0 prepares the AI integration for controlled real-world testing:

```text
GET /ai/status
GET /ai/status?probe=true
GET /lol/coach/ai?region=HN10&game_name=Player&tag_line=1234&count=20
```

- `/ai/status` checks local configuration without making a remote request.
- `/ai/status?probe=true` calls the authenticated model-list endpoint without generating a coaching report.
- `/lol/coach/ai` combines the deterministic player and jungle profiles into one evidence-backed coaching report and seven-day training plan.
- AI requests use bounded concurrency, exponential retry for transient HTTP failures, and non-thinking JSON mode by default.
- Every generated response includes `quality.score`, `quality.level`, missing fields, and invalid fields for later evaluation.

Additional environment settings are `DEEPSEEK_MAX_RETRIES`, `DEEPSEEK_RETRY_BASE_DELAY`, `DEEPSEEK_MAX_CONCURRENCY`, and `DEEPSEEK_THINKING`.

## Authentication

Localhost mode may run without a bridge token. Any non-localhost bind requires `LOL_LCU_BRIDGE_TOKEN`.

```powershell
.\start_api.ps1 -BindAddress 0.0.0.0 -Port 18181 -Token "long-random-token"
```

Clients then send:

```text
X-LCU-Bridge-Token: long-random-token
```

Do not expose the bridge directly to the public internet.

## Tests

```powershell
$env:PYTHONDONTWRITEBYTECODE='1'
python -B -m unittest discover -s tests -v
```



## Python Client SDK

The package includes a small synchronous client for calling a deployed public API:

```python
from lol_history_api import LoLHistoryClient

client = LoLHistoryClient(
    base_url="http://111.228.5.172:18080",
    api_key="your-public-api-key",
)

health = client.health()
ai_status = client.ai_status(probe=False)
result = client.history(
    game_name="Player",
    tag_line="1234",
    region="榛戣壊鐜懓",
    count=10,
)

scouting = client.scout(
    game_name="Player",
    tag_line="1234",
    region="HN10",
    count=20,
)

jungle = client.jungle_profile(
    game_name="Player",
    tag_line="1234",
    region="HN10",
    count=20,
)

ai_scouting = client.ai_scout(
    game_name="Player",
    tag_line="1234",
    region="HN10",
    count=20,
)

ai_jungle = client.ai_jungle_profile(
    game_name="Player",
    tag_line="1234",
    region="HN10",
    count=20,
)

coach = client.ai_coach_report(
    game_name="Player",
    tag_line="1234",
    region="HN10",
    count=20,
)

review = client.analyze_match(
    game_id=123456789,
    game_name="Player",
    tag_line="1234",
    region="HN10",
)

ai_review = client.ai_analyze_match(
    game_id=123456789,
    game_name="Player",
    tag_line="1234",
    region="HN10",
)

timeline = client.match_timeline(
    game_id=123456789,
    game_name="Player",
    tag_line="1234",
    region="HN10",
)
```

The SDK only needs the public API key. It never needs the private `LOL_LCU_BRIDGE_TOKEN` used by the Windows bridge.

### Install the Python package

Install from a local checkout:

```powershell
python -m pip install .
```

Install directly from a Git repository:

```powershell
python -m pip install git+https://your-git-host/your-user/lol-history-api.git
```

Then call the deployed public API:

```python
from lol_history_api import LoLHistoryClient

client = LoLHistoryClient(
    base_url="http://111.228.5.172:18080",
    api_key="your-public-api-key",
)

result = client.history("Player", "1234", count=10)
print(result["matches"])
```

The public client uses `X-API-Key`. It does not need the private `LOL_LCU_BRIDGE_TOKEN` used by the Windows bridge.
