from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import os
from dotenv import load_dotenv
from monitor_logic import get_ssh_data, check_web_service
import asyncio

load_dotenv()

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Serve static files from the current directory
app.mount("/static", StaticFiles(directory="."), name="static")

# Configuration from environment variables
PC_HOST = "asf-server.duckdns.org"
PC_PORT = 49152
PC_USER = "asf"
PC_PASS = os.getenv("PC_PASS", "ASF")

PI_HOST = "rpi-asf-tb.duckdns.org"
PI_PORT = 2222
PI_USER = "asf_tb"
PI_PASS = os.getenv("PI_PASS", "ASF_TB")

WEB_SERVICES = [
    {"name": "Gitea", "url": "https://gitea.nabd-co.com/"},
    {"name": "OpenProject", "url": "https://openproject.nabd-co.com/"},
    {"name": "Draw.io", "url": "https://drawio.nabd-co.com/"},
    {"name": "TestArena", "url": "https://testarena.nabd-co.com/"},
    {"name": "TBM", "url": "https://tbm.asf.nabd-co.com/"},
    {"name": "Board", "url": "https://board.nabd-co.com/"},
]

@app.get("/")
async def read_index():
    return FileResponse("monitor.html")

@app.get("/api/status")
async def get_status():
    # Run SSH checks in parallel
    pc_task = asyncio.to_thread(get_ssh_data, PC_HOST, PC_PORT, PC_USER, PC_PASS)
    pi_task = asyncio.to_thread(get_ssh_data, PI_HOST, PI_PORT, PI_USER, PI_PASS)
    
    # Run web checks in parallel
    web_tasks = [asyncio.to_thread(check_web_service, s["url"]) for s in WEB_SERVICES]
    
    pc_res, pi_res, *web_res = await asyncio.gather(pc_task, pi_task, *web_tasks)
    
    services = []
    for i, res in enumerate(web_res):
        services.append({
            "name": WEB_SERVICES[i]["name"],
            "url": WEB_SERVICES[i]["url"],
            **res
        })
        
    return {
        "pc": pc_res,
        "pi": pi_res,
        "services": services
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
