import pathlib

import orjson
import yaml
from flask import Blueprint, make_response, render_template, send_from_directory
from yaml import CLoader as Loader

from src.pages.api.v1 import v1api_bp

api_bp = Blueprint("api", __name__, url_prefix="/api")

api_bp.register_blueprint(v1api_bp)


@api_bp.get("/swagger_schema")
def swagger_schema():
    response = make_response(
        render_template(
            "swagger_schema.html",
            props=dict(
                json_spec=orjson.dumps(
                    yaml.load(open(pathlib.Path(__file__).parent / "schema.yaml", "r"), Loader=Loader)
                ).decode()
            ),
        ),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=60"
    return response


@api_bp.get("/swagger_schema.yaml")
def swagger_schema_yaml():
    return send_from_directory(pathlib.Path(__file__).parent, "schema.yaml")


@api_bp.get("/schema")
def api_schema():
    response = make_response(
        render_template(
            "schema.html",
            props=dict(),
        ),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=60"
    return response
