import hmac
from config import Config

from flask import Blueprint, request

from deploy_logic import run_deploy

deploy_bp = Blueprint("deploy", __name__)


def _get_deploy_webhook_secret():
    return Config.DEPLOY_WEBHOOK_SECRET


def _run_deploy_and_log():
    success, message = run_deploy()
    return success, message

def _get_deploy_key_from_request():
    key = request.args.get("key") or request.headers.get("X-Deploy-Key")
    if key:
        return (key or "").strip()

    if request.is_json:
        data = request.get_json(silent=True)
        key = data.get("key") if data else None
    else:
        key = request.form.get("key")

    if key is not None:
        return (key if isinstance(key, str) else str(key)).strip()

    return ""


@deploy_bp.route("/webhook/deploy", methods=["GET", "POST"])
def deploy_webhook_namecheap():
    secret = _get_deploy_webhook_secret()
    if not secret:
        return "Server misconfigured (no deploy secret)", 500

    provided = _get_deploy_key_from_request()
    if not provided or not hmac.compare_digest(secret, provided):
        return "Unauthorized", 401

    success, message = _run_deploy_and_log()
    if success:
        return message or "OK", 200

    return message or "Deploy failed", 500
