# SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

import os
from flask import Flask, render_template, request
from mcaptcha_api import MCaptcha

app = Flask(__name__)

sitekey = os.environ["SITEKEY"]
secret = os.environ["SECRET"]
instance_url = os.environ["INSTANCE_URL"]

if len(sitekey) == 0:
    print("please enter sitekey")
    exit(-1)


if len(secret) == 0:
    print("please enter secret")
    exit(-1)


if len(instance_url) == 0:
    print("please enter instance url")
    exit(-1)


@app.route("/")
def index():
    return render_template(
        "index.html.j2", widget_link=f"{instance_url}/widget?sitekey={sitekey}"
    )


mcaptcha = MCaptcha(instance_url=instance_url, sitekey=sitekey, secret=secret)


@app.route("/login", methods=["POST"])
def login_page():
    username = request.form["username"]
    token = request.form["mcaptcha__token"]
    if mcaptcha.verify(token=token):
        return "<p> Success. Click <a href="/">here</a> to retry</p>"
    else:
        return '<p> Failed. Click <a href="/">here</a> to retry</p>'