from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates

import uvicorn

from endurance_can import EnduranceDataManager
from logger import start_per_valve_logger

app = FastAPI()

# Static and templates
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

# Global CAN manager
data_mgr = EnduranceDataManager()
data_mgr.connect_to_can()

start_per_valve_logger(data_mgr)

@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/api/valve-data")
async def get_valve_data():
    return JSONResponse(content=data_mgr.get_valve_data())

@app.get("/api/flow-data")
async def get_flow_data():
    return JSONResponse(content=data_mgr.get_flow_data())

@app.get("/api/pressure-data")
async def get_pressure_data():
    return JSONResponse(content=data_mgr.get_pressure_data())

@app.get("/api/pump-rpm")
async def get_pump_rpm():
    return JSONResponse(content={"rpm": data_mgr.get_pump_rpm()})

@app.post("/api/start-test")
async def start_test():
    data_mgr.send_test_command(1)
    return {"status": "started"}

@app.post("/api/stop-test")
async def stop_test():
    data_mgr.send_test_command(0)
    return {"status": "stopped"}

@app.get("/data")
def get_data():
    return {
        "valves": data_mgr.get_valve_data(),
        "flow": data_mgr.get_flow_data(),
        "pressure": data_mgr.get_pressure_data(),
        "pump": data_mgr.get_pump_rpm()
    }

@app.get("/graphs", response_class=HTMLResponse)
async def show_graphs(request: Request):
    return templates.TemplateResponse("graphs.html", {"request": request})


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8080, reload=True)
