from flask import jsonify, make_response, request

from src.config import Configuration
from src.lib.files import get_file_relationships, try_set_password
from src.pages.api.v1 import v1api_bp
from src.utils.utils import get_query_parameters_dict


@v1api_bp.get("/search_hash/<file_hash>")
def lookup_file(file_hash):
    if not (len(file_hash) == 64 and all(c in "0123456789abcdefABCDEF" for c in file_hash)):
        response = make_response(jsonify({"error": "Invalid SHA256 hash"}), 400)
        return response
    if not (file := get_file_relationships(file_hash)):
        response = make_response("{}", 404)
        response.headers["Cache-Control"] = "s-maxage=600"
        return response

    response = make_response(jsonify(file), 200)
    response.headers["Cache-Control"] = "s-maxage=600"
    return response


@v1api_bp.get("/set_password")
def set_password():
    if not Configuration().archive_server["enabled"]:
        return "false"
    q = get_query_parameters_dict(request)
    file_hash = q.get("file_hash")
    passwords = [password for password in request.args.getlist("password") if password]
    if not file_hash or not passwords or not try_set_password(file_hash, passwords):
        return "false"
    return "true"
