# English comments only
from __future__ import annotations

import os
import socket
from contextlib import asynccontextmanager
from fastapi import FastAPI

from .core.redis import get_redis
from .metrics import snapshot as metrics_snapshot
from .api.fall import router as fall_router
from .core.config import load_config, print_config
from .api.emergency import router as emergency_router

# Optional: subscriber may or may not exist in this service
try:
    from . import subscriber as sub  # type: ignore
except Exception:  # pragma: no cover
    sub = None  # type: ignore

_sub_running: bool = False


@asynccontextmanager
async def lifespan(app: FastAPI):
    # English comments only
    global _sub_running
    r = get_redis()
    cfg = load_config()
    print_config(cfg)

    # Best-effort MQTT DNS check
    try:
        socket.gethostbyname(os.getenv("MQTT_HOST", "mosquitto"))
        print("[hs] mqtt dns ok")
    except Exception as e:
        print(f"[hs] mqtt dns failed: {e}")

    # Start subscriber with cfg and redis if present and enabled
    if sub is not None and cfg.START_SUBSCRIBER:
        try:
            sub.start(cfg, r)
            _sub_running = True
        except Exception as e:
            print(f"[hs] subscriber start failed: {e}")

    yield

    # Shutdown
    if sub is not None:
        try:
            sub.stop()
        except Exception:
            pass
    _sub_running = False


app = FastAPI(lifespan=lifespan)

# Mount API routers
app.include_router(fall_router)
app.include_router(emergency_router)

@app.get("/whoami")
def whoami():
    import app as _pkg
    return {"service": "hs", "import_path": getattr(_pkg, "__file__", "")}

@app.get("/ping")
def ping():
    # English comments only
    return {"msg": "pong"}


@app.get("/health/live")
def health_live():
    # English comments only
    return {"status": "live"}


@app.get("/health/ready")
def health_ready():
    # English comments only
    ok_redis = False
    ok_dns = False
    try:
        get_redis().ping()
        ok_redis = True
    except Exception:
        ok_redis = False
    try:
        host = os.getenv("MQTT_HOST", "mosquitto")  # prefer env var, fallback to default
        socket.gethostbyname(host)
        ok_dns = True
    except Exception:
        ok_dns = False

    # Telegram env (optional in HS)

    has_token = bool(os.getenv("TELEGRAM_TOKEN"))
    has_chat = bool(os.getenv("TELEGRAM_CHAT_ID"))

    metrics = metrics_snapshot()
    return {
        "redis": ok_redis,
        "mqtt_dns": ok_dns,
        "subscriber": bool(_sub_running),
        "notify_env": {"has_token": has_token, "has_chat": has_chat},
        "metrics": metrics,
    }
