"""
System API endpoints for health checks and system information.

Provides:
- /health - Basic health check
- /api/v1/system/local-ip - Local network IP for QR-code mobile upload
"""

import os
import socket
from fastapi import APIRouter

router = APIRouter(tags=["System"])


@router.get("/health")
async def health_check():
    """
    Basic health check endpoint.

    Returns healthy status and service name.
    """
    return {
        "status": "healthy",
        "service": "breakpilot-backend"
    }


@router.get("/api/v1/system/local-ip")
async def get_local_ip():
    """
    Return the local network IP address.

    Used for QR-code generation for mobile PDF upload.
    Mobile devices can't reach localhost, so we need the actual network IP.

    Priority:
    1. LOCAL_NETWORK_IP environment variable (explicit configuration)
    2. Auto-detection via socket connection
    3. Fallback to default 192.168.178.157
    """
    # Check environment variable first
    env_ip = os.getenv("LOCAL_NETWORK_IP")
    if env_ip:
        return {"ip": env_ip}

    # Try to auto-detect
    try:
        # Create a socket to an external address to determine local IP
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(0.1)
        # Connect to a public DNS server (doesn't actually send anything)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()

        # Validate it's a private IP
        if (local_ip.startswith("192.168.") or
            local_ip.startswith("10.") or
            (local_ip.startswith("172.") and 16 <= int(local_ip.split('.')[1]) <= 31)):
            return {"ip": local_ip}
    except Exception:
        pass

    # Fallback to default
    return {"ip": "192.168.178.157"}
