import os
from fastapi import *
from psycopg2.errors import UndefinedTable
from sqlmodel import Session, select, text
from sqlalchemy.exc import ProgrammingError
from .models.timelog import TimeLog
from .models.calendar import Calendar
from .utils import (
    engine,
    create_db,
    tags_metadata,
    execute_sample_sql,
)
from .api import (
    user,
    timelog,
    forecast,
    epic,
    epic_area,
    client,
    rate,
    team,
    role,
    sponsor,
    capacity,
    demand,
)
import csv

app = FastAPI(title="timeflow app API", openapi_tags=tags_metadata)

app.include_router(timelog.router)
app.include_router(forecast.router)
app.include_router(user.router)
app.include_router(epic.router)
app.include_router(epic_area.router)
app.include_router(client.router)
app.include_router(rate.router)
app.include_router(team.router)
app.include_router(role.router)
app.include_router(sponsor.router)
app.include_router(capacity.router)
app.include_router(demand.router)


@app.on_event("startup")
def on_startup():
    with Session(engine) as session:
        if os.getenv("TIMEFLOW_DEV") == "true":
            try:
                statement = select(TimeLog)
                results = session.exec(statement)
            except ProgrammingError:
                create_db()
                execute_sample_sql()
        elif os.getenv("TIMEFLOW_DEV") == "false":
            try:
                statement = select(TimeLog)
                results = session.exec(statement)
            except ProgrammingError:
                create_db()



@app.on_event("startup")
def implement_calendar_table():
    with 