================================================================================
                   SREBOT PLAYER API DOCUMENTATION
                          Version 1.2.0
================================================================================

TABLE OF CONTENTS
--------------------------------------------------------------------------------
1. Overview
2. Base URL & Connection
3. Response Format
4. Error Codes
5. Player Endpoints
6. Leaderboard Endpoints
7. Squadron Endpoints
8. Live Match Endpoints
9. Search Endpoints
10. Debug Endpoints
11. Utility Endpoints
12. Rate Limiting & Best Practices

================================================================================
1. OVERVIEW
================================================================================

The SREBOT Player API provides access to War Thunder squadron battle statistics
including player data, vehicle performance, squadron rankings, live match
results, and real-time squadron points from the War Thunder API. All data is 
stored in SQLite databases and served via a RESTful API.

Database: SQLite (read-only)
Primary DB: sq_battles.db (player_games_hist, match_summary tables)
Lookup DB: squadrons.db (squadrons_data table) - optional
Port: 6000 (default)
Protocol: HTTP
Response Format: JSON
External Integration: War Thunder API (via Python Points_API module)

================================================================================
2. BASE URL & CONNECTION
================================================================================

Local Development:
    http://localhost:6000

Production:
    Configure via environment variable PORT (default: 6000)

Health Check:
    GET http://localhost:6000/health

API Information:
    GET http://localhost:6000/api/info

================================================================================
3. RESPONSE FORMAT
================================================================================

All successful responses return JSON with appropriate data structures.
All timestamps are in Unix epoch format (seconds) unless otherwise noted.

Standard Success Response:
{
    "data": { ... },
    "additional_fields": "..."
}

Standard Error Response:
{
    "error": "Error message",
    "errorCode": "ERROR_CODE" (optional)
}

================================================================================
4. ERROR CODES
================================================================================

HTTP Status Codes:
    200 - OK
    400 - Bad Request (invalid parameters)
    404 - Not Found (resource doesn't exist)
    500 - Internal Server Error (database or server error)
    503 - Service Unavailable (database connection error)

Custom Error Codes:
    DB_NICK_QUERY_FAILED - Failed to retrieve player nickname
    DB_GAMES_QUERY_FAILED - Failed to retrieve player games
    DB_SEARCH_QUERY_FAILED - Failed to execute search
    DB_PLAYER_LEADERBOARD_FAILED - Failed to generate player leaderboard
    DB_VEHICLE_LEADERBOARD_FAILED - Failed to generate vehicle leaderboard
    DB_SQUADRON_LEADERBOARD_FAILED - Failed to generate squadron leaderboard
    DB_SQUADRON_SUMMARY_FAILED - Failed to get squadron summary
    DB_SQUADRON_PLAYERS_FAILED - Failed to get squadron players
    DB_TOTAL_PLAYERS_FAILED - Failed to count total players
    DB_TOTAL_SQUADRONS_FAILED - Failed to count total squadrons
    DB_SCHEMA_CHECK_FAILED - Failed to check database schema
    DB_OVERALL_STATS_FAILED - Failed to get overall statistics
    DB_TOP_VEHICLES_FAILED - Failed to get top vehicles

================================================================================
5. PLAYER ENDPOINTS
================================================================================

5.1 GET /api/player/:uid
--------------------------------------------------------------------------------
Retrieve player data and aggregated vehicle statistics by UID.

Parameters:
    :uid (path) - Player unique identifier (required)
    start_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter from this date.
    end_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter until end of this date.

Response:
{
    "uid": "12345",
    "nick": "PlayerName",
    "squadron_name": "SQUAD",
    "total_vehicles": 5,
    "vehicles": [
        {
            "vehicle_internal": "germ_pzkpfw_VI_ausf_h1_tiger",
            "vehicle": "Tiger H1",
            "stats": {
                "ground_kills": 150,
                "air_kills": 25,
                "assists": 40,
                "captures": 10,
                "deaths": 50,
                "wins": 60,
                "losses": 40,
                "total_battles": 100,
                "win_rate": "60.0"
            }
        }
    ]
}

Examples:
    GET /api/player/123456789
    GET /api/player/123456789?start_date=2025-11-01&end_date=2025-11-30
    GET /api/player/123456789?start_date=2025-11-01

Notes:
    - Date filtering aggregates stats only from games within the specified date range
    - start_date filters from 00:00:00 of the specified date
    - end_date filters until 23:59:59 of the specified date
    - Both parameters are optional and can be used independently

Errors:
    400 - UID parameter is required
    404 - Player not found
    500 - DB_NICK_QUERY_FAILED, database error

--------------------------------------------------------------------------------

5.2 GET /api/player/:uid/games
--------------------------------------------------------------------------------
Retrieve individual game records for a specific player.

Parameters:
    :uid (path) - Player unique identifier (required)

Response:
{
    "uid": "12345",
    "nick": "PlayerName",
    "squadron_name": "SQUAD",
    "total_games_returned": 150,
    "games": [
        {
            "session_id": "20250101_120000",
            "vehicle_internal": "germ_pzkpfw_VI_ausf_h1_tiger",
            "vehicle": "Tiger H1",
            "squadron_name": "SQUAD",
            "timestamp": 1704110400,
            "stats": {
                "ground_kills": 3,
                "air_kills": 1,
                "assists": 2,
                "captures": 1,
                "deaths": 1
            },
            "result": "WIN"
        }
    ]
}

Example:
    GET /api/player/123456789/games

Errors:
    400 - UID parameter is required
    404 - Player not found
    500 - DB_GAMES_QUERY_FAILED

================================================================================
6. LEADERBOARD ENDPOINTS
================================================================================

6.1 GET /api/leaderboard/players
--------------------------------------------------------------------------------
Retrieve global player leaderboards with aggregated statistics.

Parameters:
    start_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter from this date.
    end_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter until end of this date.

Response:
{
    "timeframe": "all-time",
    "total_players": 1500,
    "players": [
        {
            "uid": "12345",
            "nick": "TopPlayer",
            "squadron_name": "ELITE",
            "total_kills": 5000,
            "ground_kills": 4000,
            "air_kills": 1000,
            "total_battles": 800,
            "wins": 500,
            "win_rate": 62.5,
            "kdr": 10.0,
            "deaths": 500,
            "assists": 1200,
            "captures": 300,
            "total_score": 25000
        }
    ]
}

Notes:
    - Returns ALL players in database sorted by total_score
    - Score calculation: ground_kills + air_kills + (assists * 0.5) + (captures * 2)
    - Only includes players with at least 1 kill
    - KDR = total_kills / deaths (or total_kills if deaths = 0)
    - Date filtering aggregates stats only from games within the specified date range

Examples:
    GET /api/leaderboard/players
    GET /api/leaderboard/players?start_date=2025-11-01&end_date=2025-11-30
    GET /api/leaderboard/players?start_date=2025-11-01

Errors:
    500 - DB_PLAYER_LEADERBOARD_FAILED

--------------------------------------------------------------------------------

6.2 GET /api/leaderboard/vehicles
--------------------------------------------------------------------------------
Retrieve vehicle-specific leaderboards showing top players for each vehicle.

Parameters:
    vehicle (query) - Optional. Filter by specific vehicle name (case-insensitive)
    start_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter from this date.
    end_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter until end of this date.

Response (without filter):
{
    "vehicles": [
        {
            "vehicle": "Tiger H1",
            "player_uid": "12345",
            "player_nick": "TankAce",
            "player_squadron_name": "TANKS",
            "total_kills": 450,
            "ground_kills": 400,
            "air_kills": 50,
            "battles": 120,
            "wins": 75,
            "win_rate": 62.5,
            "kdr": 9.0,
            "deaths": 50,
            "assists": 100,
            "captures": 30
        }
    ]
}

Response (with filter):
    Same structure, but only includes entries for specified vehicle

Examples:
    GET /api/leaderboard/vehicles
    GET /api/leaderboard/vehicles?vehicle=Tiger H1
    GET /api/leaderboard/vehicles?start_date=2025-11-01&end_date=2025-11-30
    GET /api/leaderboard/vehicles?vehicle=Tiger H1&start_date=2025-11-01

Errors:
    500 - DB_VEHICLE_LEADERBOARD_FAILED

Notes:
    - Returns ALL vehicle-player combinations
    - Sorted by total_kills DESC, then battles DESC
    - Only includes combinations with at least 1 kill
    - Date filtering aggregates stats only from games within the specified date range

--------------------------------------------------------------------------------

6.3 GET /api/leaderboard/squadrons
--------------------------------------------------------------------------------
Retrieve squadron leaderboards with aggregated stats across all members.

Parameters:
    start_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter from this date.
    end_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter until end of this date.

Response:
{
    "timeframe": "all-time",
    "total_squadrons": 50,
    "squadrons": [
        {
            "tag_name": "[ELITE]",
            "long_name": "Elite Squadron",
            "player_count": 25,
            "total_kills": 50000,
            "ground_kills": 40000,
            "air_kills": 10000,
            "total_battles": 8000,
            "wins": 5000,
            "win_rate": 62.5,
            "kdr": 10.0,
            "deaths": 5000,
            "assists": 12000,
            "captures": 3000,
            "points": {
                "total_points": 125000,
                "has_points_data": true
            }
        }
    ]
}

Notes:
    - Requires squadron_name column in database
    - Excludes squadrons named 'UNKNOWN'
    - Sorted by points if available, otherwise by total_kills DESC
    - Only includes squadrons with at least 1 kill
    - Uses squadrons.db to consolidate squadron name variants (tag_name, long_name, short_name)
    - Fetches squadron points data from War Thunder API via Python script
    - Points data fetching has 10-second timeout per squadron
    - Squadrons without points data (has_points_data: false) are sorted after those with points
    - Date filtering aggregates stats only from games within the specified date range

Examples:
    GET /api/leaderboard/squadrons
    GET /api/leaderboard/squadrons?start_date=2025-11-01&end_date=2025-11-30
    GET /api/leaderboard/squadrons?start_date=2025-11-01

Special Response (if squadron_name column missing):
{
    "timeframe": "all-time",
    "total_squadrons": 0,
    "squadrons": [],
    "migration_needed": true,
    "message": "Squadron data not available - squadron_name column missing from database"
}

Errors:
    500 - DB_SQUADRON_LEADERBOARD_FAILED, DB_SCHEMA_CHECK_FAILED

--------------------------------------------------------------------------------

6.4 GET /api/leaderboard/stats
--------------------------------------------------------------------------------
Retrieve overall leaderboard statistics and top vehicles.

Parameters:
    None

Response:
{
    "total_players": 1500,
    "total_vehicles_used": 250,
    "total_battles": 50000,
    "last_updated": "2025-01-15T12:00:00.000Z",
    "top_vehicles": [
        {
            "vehicle": "Tiger H1",
            "usage_count": 5000
        },
        {
            "vehicle": "T-34-85",
            "usage_count": 4500
        }
    ]
}

Notes:
    - Returns top 12 most-used vehicles
    - last_updated is ISO 8601 format
    - usage_count = total number of battles in that vehicle

Example:
    GET /api/leaderboard/stats

Errors:
    500 - DB_OVERALL_STATS_FAILED, DB_TOP_VEHICLES_FAILED

================================================================================
7. SQUADRON ENDPOINTS
================================================================================

7.1 GET /api/squadrons/:squadronname
--------------------------------------------------------------------------------
Retrieve all players in a specific squadron and their individual statistics.

Parameters:
    :squadronname (path) - Squadron name (required, accepts tag_name, long_name, or short_name)
    start_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter from this date.
    end_date (query) - Optional. ISO date string (YYYY-MM-DD). Filter until end of this date.

Response:
{
    "tag_name": "[ELITE]",
    "long_name": "Elite Squadron",
    "squadron_summary": {
        "player_count": 25,
        "total_kills": 50000,
        "ground_kills": 40000,
        "air_kills": 10000,
        "total_battles": 8000,
        "wins": 5000,
        "win_rate": 62.5,
        "kdr": 10.0,
        "deaths": 5000,
        "assists": 12000,
        "captures": 3000,
        "points": {
            "total_points": 125000,
            "has_points_data": true
        }
    },
    "players": [
        {
            "uid": "12345",
            "nick": "PlayerOne",
            "total_kills": 2000,
            "ground_kills": 1600,
            "air_kills": 400,
            "total_battles": 320,
            "wins": 200,
            "win_rate": 62.5,
            "kdr": 10.0,
            "deaths": 200,
            "assists": 480,
            "captures": 120
        }
    ]
}

Notes:
    - Requires squadron_name column in database
    - Players sorted by total_kills DESC
    - Includes all players with 0 or more kills
    - Uses squadrons.db to resolve squadron name variants to canonical long_name and tag_name
    - Consolidates stats from all squadron name variants (e.g., "ELITE", "[ELITE]", "Elite Squadron")
    - Fetches squadron points data from War Thunder API via Python script
    - Points data fetching has 10-second timeout
    - Date filtering aggregates stats only from games within the specified date range

Examples:
    GET /api/squadrons/ELITE
    GET /api/squadrons/[ELITE]
    GET /api/squadrons/Elite%20Squadron
    GET /api/squadrons/ELITE?start_date=2025-11-01&end_date=2025-11-30
    GET /api/squadrons/ELITE?start_date=2025-11-01

Special Response (squadron not found):
{
    "tag_name": "UNKNOWN",
    "long_name": "UNKNOWN",
    "squadron_summary": { 
        /* all zeros with points: { total_points: 0, has_points_data: false } */ 
    },
    "players": [],
    "message": "Squadron 'UNKNOWN' not found or has no players"
}

Special Response (if squadron_name column missing):
{
    "tag_name": "ELITE",
    "long_name": "ELITE",
    "squadron_summary": { 
        /* all zeros with points: { total_points: 0, has_points_data: false } */ 
    },
    "players": [],
    "migration_needed": true,
    "message": "Squadron data not available - squadron_name column missing from database"
}

Errors:
    400 - Squadron name parameter is required
    500 - DB_SQUADRON_SUMMARY_FAILED, DB_SQUADRON_PLAYERS_FAILED

================================================================================
8. LIVE MATCH ENDPOINTS
================================================================================

8.1 GET /api/live
--------------------------------------------------------------------------------
Retrieve live feed of recent match results.

Parameters:
    limit (query, optional) - Number of matches to return (default: 15, max: 200)

Response:
{
    "total_matches": 15,
    "limit": 15,
    "matches": [
        {
            "session_id": "20250115_143000",
            "map_name": "Normandy",
            "endtime_unix": 1705329000,
            "endtime_iso": "2025-01-15T14:30:00.000Z",
            "winning_squadron": "ELITE",
            "losing_squadron": "NOOBS",
            "winning_team": {
                "squadron": "ELITE",
                "players": [
                    {
                        "uid": "12345",
                        "nick": "PlayerOne",
                        "squadron_name": "ELITE",
                        "vehicle": "Tiger H1",
                        "vehicle_new": "Tiger H1",
                        "ground_kills": 5,
                        "air_kills": 1,
                        "assists": 3,
                        "captures": 2,
                        "deaths": 1
                    }
                ]
            },
            "losing_team": {
                "squadron": "NOOBS",
                "players": [ /* same structure */ ]
            }
        }
    ]
}

Notes:
    - Requires match_summary table in database
    - Matches sorted by endtime_unix DESC (newest first)
    - winning_team_json and losing_team_json are parsed into objects
    - If JSON parsing fails, team data will be null

Examples:
    GET /api/live
    GET /api/live?limit=50
    GET /api/live?limit=200

Errors:
    400 - Limit cannot exceed 200
    500 - Database error

Logging:
    - Request details (IP, user agent, query params)
    - Query execution time
    - JSON parse errors
    - Response size and timing

================================================================================
9. SEARCH ENDPOINTS
================================================================================

9.1 GET /api/search/:nickname
--------------------------------------------------------------------------------
Search for players by nickname (case-insensitive partial match).

Parameters:
    :nickname (path) - Player nickname to search for (required, min 1 char)

Response:
{
    "search_term": "player",
    "total_found": 5,
    "limited_to": 50,
    "results": [
        {
            "uid": "12345",
            "nick": "PlayerOne",
            "squadron_name": "ELITE"
        },
        {
            "uid": "67890",
            "nick": "TopPlayer",
            "squadron_name": "PROS"
        }
    ]
}

Notes:
    - Case-insensitive search
    - Partial match (e.g., "play" matches "PlayerOne", "TopPlayer")
    - Returns latest nickname for each UID
    - Limited to 50 results
    - Sorted alphabetically by nickname

Examples:
    GET /api/search/player
    GET /api/search/ace
    GET /api/search/top

Errors:
    400 - Nickname parameter is required
    500 - DB_SEARCH_QUERY_FAILED

================================================================================
10. DEBUG ENDPOINTS
================================================================================

10.1 GET /api/debug/stats
--------------------------------------------------------------------------------
Get database schema and statistics for player_games_hist table.

Response:
{
    "table_schema": [
        {
            "name": "UID",
            "type": "TEXT",
            "notnull": 1,
            "default_value": null
        }
    ],
    "database_stats": {
        "total_records": 50000,
        "unique_players": 1500,
        "unique_sessions": 8000,
        "oldest_session": "20240101_120000",
        "newest_session": "20250115_143000"
    },
    "sample_records": [ /* 3 recent records */ ],
    "timestamp": "2025-01-15T14:30:00.000Z"
}

--------------------------------------------------------------------------------

10.2 GET /api/debug/schema
--------------------------------------------------------------------------------
Get detailed database schema and sample records.

Response:
{
    "table_name": "player_games_hist",
    "schema": [ /* detailed column info */ ],
    "column_names": ["UID", "nick", "session_id", ...],
    "sample_records": [ /* 3 sample records */ ],
    "total_columns": 15,
    "timestamp": "2025-01-15T14:30:00.000Z"
}

--------------------------------------------------------------------------------

10.3 GET /api/debug/migration-status
--------------------------------------------------------------------------------
Check if squadron_name column exists and if migration is needed.

Response:
{
    "table_name": "player_games_hist",
    "has_squadron_column": true,
    "missing_columns": [],
    "all_columns": ["UID", "nick", "squadron_name", ...],
    "migration_needed": false,
    "migration_sql": null,
    "timestamp": "2025-01-15T14:30:00.000Z"
}

If migration needed:
{
    "migration_needed": true,
    "migration_sql": "ALTER TABLE player_games_hist ADD COLUMN squadron_name TEXT NOT NULL DEFAULT 'UNKNOWN'"
}

--------------------------------------------------------------------------------

10.4 GET /api/debug/player-sample
--------------------------------------------------------------------------------
Get sample player data (10 records).

Response:
{
    "sample_data": [
        {
            "UID": "12345",
            "nick": "PlayerOne",
            "session_id": "20250115_143000",
            "vehicle": "Tiger H1",
            "ground_kills": 3,
            "air_kills": 1,
            "assists": 2,
            "captures": 1,
            "deaths": 1,
            "victor_bool": "WIN"
        }
    ]
}

--------------------------------------------------------------------------------

10.5 GET /api/debug/player-count/:uid
--------------------------------------------------------------------------------
Get detailed analysis of a player's records.

Parameters:
    :uid (path) - Player UID (required)

Response:
{
    "player_analysis": {
        "UID": "12345",
        "total_records": 500,
        "unique_sessions": 500,
        "unique_vehicles": 15,
        "vehicles_used": "Tiger H1,T-34-85,Panther D,..."
    }
}

--------------------------------------------------------------------------------

10.6 GET /api/debug/squadron-names
--------------------------------------------------------------------------------
Analyze squadron name patterns and find potential duplicates.

Parameters:
    None

Response:
{
    "total_unique_names": 50,
    "squadron_names": [
        {
            "squadron_name": "ELITE",
            "record_count": 1500
        },
        {
            "squadron_name": "[ELITE]",
            "record_count": 800
        }
    ],
    "patterns": {
        "bracketed": [ /* squadrons with [brackets] */ ],
        "non_bracketed": [ /* squadrons without brackets */ ],
        "mixed": [ /* squadrons with partial brackets */ ]
    },
    "potential_duplicates": [
        {
            "name1": "ELITE",
            "name2": "[ELITE]",
            "normalized": "ELITE",
            "records1": 1500,
            "records2": 800
        }
    ]
}

Notes:
    - Limited to 50 squadron names
    - Excludes 'UNKNOWN' squadrons
    - Identifies potential duplicates by normalizing (removing brackets)
    - Useful for identifying squadron name variants that should be consolidated

--------------------------------------------------------------------------------

10.7 GET /api/debug/squadrons-db-schema
--------------------------------------------------------------------------------
Get squadrons.db database schema and sample records.

Parameters:
    None

Response:
{
    "database_path": "/path/to/squadrons.db",
    "tables": {
        "squadrons_data": {
            "schema": [
                {
                    "cid": 0,
                    "name": "clan_id",
                    "type": "TEXT",
                    "notnull": 0,
                    "dflt_value": null,
                    "pk": 0
                },
                {
                    "cid": 1,
                    "name": "long_name",
                    "type": "TEXT",
                    "notnull": 0,
                    "dflt_value": null,
                    "pk": 0
                },
                {
                    "cid": 2,
                    "name": "short_name",
                    "type": "TEXT",
                    "notnull": 0,
                    "dflt_value": null,
                    "pk": 0
                },
                {
                    "cid": 3,
                    "name": "tag_name",
                    "type": "TEXT",
                    "notnull": 0,
                    "dflt_value": null,
                    "pk": 0
                }
            ],
            "sample_records": [ /* 3 sample squadron records */ ],
            "record_count": 3
        }
    },
    "timestamp": "2025-01-15T14:30:00.000Z"
}

Special Response (if squadrons.db not found):
{
    "error": "Squadrons database not found",
    "path": "/path/to/squadrons.db"
}

Notes:
    - Returns schema for all tables in squadrons.db
    - Includes sample records (up to 3) for each table
    - Used to verify squadron lookup database structure

================================================================================
11. UTILITY ENDPOINTS
================================================================================

11.1 GET /health
--------------------------------------------------------------------------------
Health check endpoint.

Response:
{
    "status": "OK",
    "timestamp": "2025-01-15T14:30:00.000Z",
    "database": "Connected"
}

--------------------------------------------------------------------------------

11.2 GET /api/info
--------------------------------------------------------------------------------
API information and available endpoints.

Response:
{
    "name": "SREBOT Player API",
    "version": "1.2.0",
    "endpoints": {
        "GET /api/player/:uid": "Get player data and aggregated vehicle statistics by UID",
        "GET /api/player/:uid/games": "Get individual game records for a player (recent games)",
        "GET /api/search/:nickname": "Search for players by nickname",
        "GET /api/live": "Get live feed of recent match results (supports ?limit parameter, max 200)",
        "GET /api/leaderboard/players": "Get global player leaderboards with aggregated stats",
        "GET /api/leaderboard/squadrons": "Get squadron leaderboards with aggregated stats across all squadron members",
        "GET /api/leaderboard/vehicles": "Get vehicle-specific leaderboards (supports ?vehicle parameter)",
        "GET /api/leaderboard/stats": "Get overall leaderboard statistics and top vehicles",
        "GET /api/squadrons/:squadronname": "Get all players in a specific squadron and their individual stats",
        "GET /api/debug/stats": "Get database schema and statistics (debug)",
        "GET /api/debug/schema": "Get detailed database schema and sample records (debug)",
        "GET /api/debug/squadron-names": "Analyze squadron name patterns and find potential duplicates (debug)",
        "GET /api/debug/migration-status": "Check if squadron migration is needed (debug)",
        "GET /api/debug/squadrons-db-schema": "Get squadrons.db database schema and sample records (debug)",
        "GET /health": "Health check endpoint",
        "GET /api/info": "API information"
    },
    "database": {
        "path": "/path/to/sq_battles.db",
        "table": "player_games_hist",
        "expected_columns": [
            "UID", "nick", "session_id", "vehicle", "vehicle_internal",
            "ground_kills", "air_kills", "assists", "captures", "deaths", "victor_bool"
        ]
    }
}

================================================================================
12. RATE LIMITING & BEST PRACTICES
================================================================================

Rate Limiting:
    - No explicit rate limiting implemented
    - Database refreshes every 60 seconds
    - Use /api/live with reasonable limit values (15-50 recommended)

Best Practices:
    1. Cache responses on client side when possible
    2. Use specific endpoints rather than requesting all data
    3. Implement exponential backoff on errors
    4. Use /health endpoint before making data requests
    5. Filter vehicle leaderboards when possible
    6. Limit /api/live requests to necessary number of matches

Performance Considerations:
    - All queries use read-only database connection
    - Indexes recommended on: UID, session_id, vehicle, squadron_name
    - Large result sets (all players, all vehicles) may take longer
    - /api/live with high limits (>100) may be slower
    - Squadron endpoints fetch real-time points data via Python API calls
    - /api/leaderboard/squadrons may take longer with many squadrons (10s timeout per squadron)
    - /api/squadrons/:squadronname includes 10s timeout for points fetching
    - Points API calls run in parallel for leaderboards but may still take significant time

Error Handling:
    - Always check HTTP status code
    - Parse error JSON for detailed error information
    - Implement retry logic for 500-series errors
    - Log errorCode for debugging

Database Maintenance:
    - API performs periodic health checks every 60 seconds
    - Read-only mode prevents data corruption
    - Ensure main bot is running to populate data
    - Check /api/debug/migration-status for schema updates

================================================================================
APPENDIX A: CALCULATION FORMULAS
================================================================================

Win Rate:
    win_rate = (wins / total_battles) * 100

Kill/Death Ratio (KDR):
    kdr = total_kills / deaths
    (if deaths = 0, kdr = total_kills)

Total Kills:
    total_kills = ground_kills + air_kills

Total Score (Player/Squadron):
    total_score = ground_kills + air_kills + (assists * 0.5) + (captures * 2)

Average Statistics:
    avg_stat = sum(stat) / count(records)

================================================================================
APPENDIX B: DATABASE SCHEMA
================================================================================

Database: sq_battles.db
-----------------------

Table: player_games_hist
Columns:
    - UID (TEXT) - Player unique identifier
    - nick (TEXT) - Player nickname
    - squadron_name (TEXT) - Squadron name (may be UNKNOWN or NULL)
    - session_id (TEXT) - Match session identifier
    - vehicle (TEXT) - Display name of vehicle
    - vehicle_internal (TEXT) - Internal vehicle identifier
    - ground_kills (INTEGER) - Ground targets destroyed
    - air_kills (INTEGER) - Air targets destroyed
    - assists (INTEGER) - Kill assists
    - captures (INTEGER) - Capture points secured
    - deaths (INTEGER) - Number of deaths
    - victor_bool (TEXT) - Match result (WIN/LOSS)
    - endtime_unix (INTEGER) - Match end time (Unix timestamp)

Table: match_summary
Columns:
    - session_id (TEXT) - Match session identifier
    - map_name (TEXT) - Map name
    - endtime_unix (INTEGER) - Match end time
    - winning_sq (TEXT) - Winning squadron name
    - losing_sq (TEXT) - Losing squadron name
    - winning_team_json (TEXT) - JSON of winning team data
    - losing_team_json (TEXT) - JSON of losing team data

Database: squadrons.db (optional)
----------------------------------

Table: squadrons_data
Columns:
    - clan_id (TEXT) - Unique squadron identifier
    - long_name (TEXT) - Full squadron name (canonical name)
    - short_name (TEXT) - Short squadron name variant
    - tag_name (TEXT) - Squadron tag with brackets (e.g., "[ELITE]")

Notes:
    - squadrons.db is used to resolve squadron name variants
    - If squadrons.db is missing, API falls back to using raw squadron_name
    - Multiple squadron name variants map to the same long_name for consolidation
    - API uses this to combine stats from different name formats (e.g., "ELITE", "[ELITE]", "Elite Squadron")

================================================================================
APPENDIX C: EXTERNAL DEPENDENCIES
================================================================================

Python Integration:
-------------------
The API integrates with a Python module (Points_API.py) to fetch real-time
squadron points data from the War Thunder API.

Requirements:
    - Python 3.7+ installed and accessible via 'python' command
    - Points_API.py module in the same directory as the API server
    - Points_API module must export: obtain_clan_new_points(squadron_name) async function

Function Signature:
    obtain_clan_new_points(squadron_name: str) -> Tuple[Dict, int]
    
    Returns:
        - member_points: Dictionary of member points data
        - total_points: Total squadron points (integer)

Error Handling:
    - Python process timeout: 10 seconds per squadron
    - If Python script fails, points will default to 0
    - If Points_API is missing, points.has_points_data will be false
    - Errors are logged but do not prevent response

Implementation Details:
    - Uses Node.js child_process.spawn() to execute Python
    - Python output is parsed to extract total_points
    - Process is killed if timeout exceeds 10 seconds
    - Multiple squadron point requests run in parallel for leaderboards

Notes:
    - Points data is fetched in real-time (not cached)
    - Squadron leaderboard response time increases with squadron count
    - For best performance, ensure Python and dependencies are optimized

================================================================================
APPENDIX D: VERSION HISTORY
================================================================================

Version 1.2.0 (Current):
    - Added squadron points integration from War Thunder API
    - Squadron endpoints now return tag_name and long_name fields
    - Added points object to squadron responses (total_points, has_points_data)
    - Implemented squadron name consolidation using squadrons.db lookup
    - Squadron leaderboards now sorted by points (if available)
    - Added /api/debug/squadron-names endpoint for squadron name analysis
    - Added /api/debug/squadrons-db-schema endpoint to inspect squadrons.db
    - Enhanced squadron endpoints to handle multiple name variants
    - Python script integration for real-time points fetching
    - 10-second timeout per squadron for points API calls

Version 1.1.0:
    - Added squadron endpoints (/api/leaderboard/squadrons, /api/squadrons/:squadronname)
    - Added squadron_name field to player responses
    - Added migration status endpoint
    - Enhanced logging with structured log format
    - Added debug endpoints for schema inspection

Version 1.0.0:
    - Initial release
    - Player statistics endpoints
    - Vehicle leaderboards
    - Live match feed
    - Search functionality
    - Debug endpoints

================================================================================
                            END OF DOCUMENTATION
================================================================================

For support or questions, check the API info endpoint or contact the development team.

Last Updated: September 30, 2025
