# ruff: noqa: E402
import sys
from pathlib import Path

_pkg = Path(__file__).parent
if str(_pkg) not in sys.path:
    sys.path.insert(0, str(_pkg))

import asyncio
import os
import pathlib
from dotenv import load_dotenv
from nicegui import app, ui
from starlette.responses import Response

load_dotenv()

# Register all page routes by importing the modules
import pages.login  # noqa: F401  /  /login  /setup
import pages.dashboard  # noqa: F401  /dashboard
import pages.admin.organizations  # noqa: F401  /admin/organizations
import pages.admin.departments  # noqa: F401  /admin/departments
import pages.admin.users  # noqa: F401  /admin/users
import pages.admin.access_management  # noqa: F401  /admin/access-management
import pages.admin.mapper  # noqa: F401  /admin/mapper
import pages.admin.settings  # noqa: F401  /admin/settings
import pages.admin.dept_members  # noqa: F401  /dept/members
import pages.data.explorer  # noqa: F401  /data/explorer
import pages.data.plots  # noqa: F401  /data/plots
import pages.alarms  # noqa: F401  /alarms
import pages.tokens  # noqa: F401  /tokens

import db
import alarm_checker
import pages.api  # noqa: F401  /api/*

app.add_static_files("/images", str(pathlib.Path(__file__).parent / "images"))


@app.get("/apple-touch-icon.png")
@app.get("/apple-touch-icon-precomposed.png")
async def apple_touch_icon():
    return Response(status_code=204)


@app.on_startup
async def startup() -> None:
    await db.init_pool()
    asyncio.ensure_future(alarm_checker.alarm_checker_loop())


@app.on_shutdown
async def shutdown() -> None:
    await db.close_pool()


if __name__ in {"__main__", "__mp_main__"}:
    ui.run(
        host="0.0.0.0",
        port=8081,
        title="LEAF Portal",
        favicon=str(pathlib.Path(__file__).parent / "images" / "icon.svg"),
        dark=False,
        storage_secret=os.environ.get("STORAGE_SECRET", "change-me-in-production"),
        show=False,
    )
