from pathlib import Path

from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

from api.discipline import router as discipline_router
from api.license import router as license_router
from api.platforms import router as platforms_router
from api.rules import router as rules_router
from api.signals import router as signals_router
from api.webhooks import router as webhooks_router
from config import settings
from core.engine import discipline_engine
from runtime.paths import runtime_info, static_dir
from services.license_service import ensure_demo_license, license_status
from services.ninja_addon_sync import sync_ninja_addon_config
from services.user_settings import load_persisted_rules_into_runtime

sync_ninja_addon_config()
load_persisted_rules_into_runtime()
ensure_demo_license()

app = FastAPI(
    title="Paychek Safeguard",
    description=(
        "Discipline safeguard for NinjaTrader. "
        "Core: session rules, max trades, max loss. "
        "Active connector: NinjaTrader (addon)."
    ),
    version="0.5.1",
)

app.include_router(webhooks_router)
app.include_router(platforms_router)
app.include_router(discipline_router)
app.include_router(rules_router)
app.include_router(signals_router)
app.include_router(license_router)

_STATIC = static_dir()
app.mount("/static", StaticFiles(directory=_STATIC), name="static")


@app.get("/")
def dashboard() -> FileResponse:
    """Interface visuelle simple — ouvrir http://127.0.0.1:8080/"""
    return FileResponse(
        _STATIC / "index.html",
        headers={
            "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
            "Pragma": "no-cache",
            "Expires": "0",
            "X-Paychek-UI-Build": "20260724-1605",
        },
    )


@app.get("/health")
def health() -> dict[str, str | bool | dict[str, str]]:
    snapshot = discipline_engine.snapshot()
    lic = license_status()
    return {
        "status": "ok",
        "version": app.version,
        "execution_mode": settings.execution_mode,
        "trading_enabled": snapshot["trading_enabled"],
        "within_session": snapshot["within_session"],
        "max_lot_enabled": snapshot.get("max_lot_enabled"),
        "trade_interval_enabled": snapshot.get("trade_interval_enabled"),
        "license_activated": lic.get("activated"),
        "runtime": runtime_info(),
    }


if __name__ == "__main__":
    import os
    import threading
    import time
    import uvicorn
    import webbrowser

    def _open_browser() -> None:
        time.sleep(1.0)
        webbrowser.open(f"http://127.0.0.1:{settings.port}/")

    # DEV.bat (PAYCHEK_DEV_UI) ouvre deja le navigateur ; desktop packagé non plus.
    if not os.environ.get("PAYCHEK_DESKTOP") and not os.environ.get("PAYCHEK_DEV_UI"):
        threading.Thread(target=_open_browser, daemon=True).start()

    # Dev: reload picks up license_service / API edits (avoids stale
    # in-memory code returning obsolete activate errors). Packaged exe: off.
    use_reload = not bool(os.environ.get("PAYCHEK_DESKTOP"))
    print(f"Paychek Safeguard -> http://127.0.0.1:{settings.port}/")
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=use_reload,
    )
