from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin

from .config import Config
from .db import Database
from .errors import bad_req, not_found

app = Flask(__name__)


JRD_JSON = "application/jrd+json; charset=utf-8"

WEBFINGER_ROUTE = "/.well-known/webfinger"

@app.route(WEBFINGER_ROUTE, methods=["GET"])
@cross_origin()
def hello_world():
    config = Config()
    db = Database()

    resource = request.args.get("resource")
    if resource is None:
        bad_req("webfinger must have 'resource' arg")
    if "acct:" not in resource:
        return bad_req("webfinger resource query must have 'acct'")
    if "@" not in resource:
        return bad_req("webfinger resource query must have '@'")

    parts = resource.split("acct:")
    parts = parts[1].split("@")
    username = parts[0]
    hostname = parts[1]
    if hostname != config.options["hostname"]:
        bad_req(f"Only serves hostname {config.options['hostname']}")
    user = db.get_user(username)
    if user is None:
        return not_found(f"resource {username} not found")

    resp = jsonify(
        {
            "subject": f"acct:{username}@{hostname}",
            "aliases": [f"http://{hostname}/@{username}"],
            "links": [
                {
                    "rel": "self",
                    "type": "application/activity+json",
                    "href": f"http://{hostname}/users/{username}",
                },
            ],
        }
    )
    resp.headers["Content-Type"] = JRD_JSON
    return resp