from my_modules.app.setup import LIMITER
from my_modules.functions import is_valid_uuid

from urllib.parse import urlencode

from quart import Blueprint, send_from_directory, current_app, Response, redirect, abort, request

basic_bp = Blueprint('basic', __name__)

@basic_bp.route('/favicon.ico', methods=['GET'])
@basic_bp.route('/favicon-32x32.png', methods=['GET'])
@basic_bp.route('/favicon.png', methods=['GET'])
@basic_bp.route('/res/favicon.ico', methods=['GET'])
@basic_bp.route('/favicon', methods=['GET'])
@LIMITER.exempt
async def favicon():
  file_data = await current_app.convex.get_current_favicon()
  return redirect(file_data['file_id'])

@basic_bp.route('/robots.txt', methods=['GET'])
@LIMITER.limit('3 per day')
async def robots():
  return await send_from_directory(current_app.static_folder, f'robots.txt')

@basic_bp.route("/storage/<path:file_id>")
async def convex_storage_proxy(file_id:str):
  if not is_valid_uuid(file_id):
    return abort(404, "Not a valid uuid")

  query_keys = set(request.args.keys())
  if query_keys - {"component"}:
    return abort(400, "Only the component query parameter is allowed")

  component_values = request.args.getlist("component")
  if len(component_values) > 1:
    return abort(400, "Only one component query parameter is allowed")

  storage_file_id = file_id
  if component_values:
    storage_file_id = f"{file_id}?{urlencode({'component': component_values[0]})}"

  stream, headers = await current_app.convex.open_storage_stream(storage_file_id, add_api_path=True)
  if 'Content-Type' not in headers:
    headers['Content-Type'] = 'application/octet-stream'

  return Response(stream, headers=headers)
