#!/usr/bin/env python3 

import fastapi, fastapi.responses, fastapi.security
import pathlib
import json
import uuid
import datetime

CurrentDirectory = pathlib.Path(__file__).parent

with (CurrentDirectory / "Internal/Internal.json").resolve().open() as F:
    JSON = json.load(F)

API = fastapi.FastAPI()
Security = fastapi.security.HTTPBasic(realm=str(uuid.uuid4()))

@API.get("/auth")
async def GetPerAuthentication(File: str, Credentials: fastapi.security.HTTPBasicCredentials = fastapi.Depends(Security)):
    global JSON
    with (CurrentDirectory / "Internal/Internal.json").resolve().open() as F:
        JSON = json.load(F)

    if "/" in File or "\\" in File:
        raise fastapi.HTTPException(403, "Cannot access Directories!")

    try:
        UserAccessInteger, Password = JSON["Accounts"][Credentials.username]

        if not Password == Credentials.password:
            raise fastapi.HTTPException(401, "Wrong Password!")

        FileAccessInteger, Path = JSON["Files"][File]
    except KeyError as e:
        raise fastapi.HTTPException(404, f"File ({File}) or Username ({Credentials.username}) not found! ({e})")

    if UserAccessInteger >= FileAccessInteger:
        raise fastapi.HTTPException(401, "AccessInteger of User to *high* for File!")

    if not pathlib.Path(Path).exists():
        raise fastapi.HTTPException(404, f"File ({File}) not found!")

    return fastapi.responses.FileResponse(Path, filename=File)

@API.get("/token")
async def GetPerToken(Token: str):
    global JSON
    with (CurrentDirectory / "Internal/Internal.json").resolve().open() as F:
        JSON = json.load(F)

    try:
        File, Until = JSON["Tokens"][Token]
    except KeyError as e:
        raise fastapi.HTTPException(404, f"Token ({Token}) not found! ({e})")

    Until = datetime.datetime.fromisoformat(Until)

    if datetime.datetime.now(datetime.UTC) > Until:
        raise fastapi.HTTPException(401, f"Token ({Token}) expired ({Until.isoformat()})!")

    try:
        Path = JSON["Files"][File][1]
    except KeyError as e:
        raise fastapi.HTTPException(404, f"File ({File}) not found!")

    if not pathlib.Path(Path).exists():
        raise fastapi.HTTPException(404, f"File ({File}) not found!")

    return fastapi.responses.FileResponse(Path, filename=File)