"""Fingerprint / Face / Windows Hello check-in using WebAuthn (platform authenticators).
Pure-Python verification (no extra libraries): ES256 (P-256) and RS256 public keys."""
import base64, hashlib, json, secrets, time
from urllib.parse import urlparse
from flask import request, jsonify, session, g, redirect, url_for, flash, abort
import app as A
from app import app, q, ex, need, audit, S, EXTRA_SQL

EXTRA_SQL.append("CREATE TABLE IF NOT EXISTS webauthn(id INTEGER PRIMARY KEY, user_id INTEGER, cred_id TEXT UNIQUE, pub TEXT, counter INTEGER DEFAULT 0, label TEXT, created TEXT, last_used TEXT);")


def b64u(b):
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode()


def unb64u(s):
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def cbor(b, i=0):
    ib = b[i]; mt, ai = ib >> 5, ib & 31; i += 1
    if ai < 24:
        n = ai
    elif ai in (24, 25, 26, 27):
        ln = {24: 1, 25: 2, 26: 4, 27: 8}[ai]; n = int.from_bytes(b[i:i + ln], "big"); i += ln
    else:
        raise ValueError("unsupported cbor")
    if mt == 0:
        return n, i
    if mt == 1:
        return -1 - n, i
    if mt == 2:
        return bytes(b[i:i + n]), i + n
    if mt == 3:
        return bytes(b[i:i + n]).decode(), i + n
    if mt == 4:
        out = []
        for _ in range(n):
            v, i = cbor(b, i); out.append(v)
        return out, i
    if mt == 5:
        d = {}
        for _ in range(n):
            k, i = cbor(b, i); v, i = cbor(b, i); d[k] = v
        return d, i
    raise ValueError("unsupported cbor type")


# ---- P-256 ECDSA verify ----
P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
BC = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
G = (0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5)


def _add(p1, p2):
    if p1 is None: return p2
    if p2 is None: return p1
    (x1, y1), (x2, y2) = p1, p2
    if x1 == x2 and (y1 + y2) % P == 0:
        return None
    m = ((3 * x1 * x1 - 3) * pow(2 * y1, -1, P) if p1 == p2 else (y2 - y1) * pow(x2 - x1, -1, P)) % P
    x3 = (m * m - x1 - x2) % P
    return x3, (m * (x1 - x3) - y1) % P


def _mul(k, pt):
    r = None
    while k:
        if k & 1:
            r = _add(r, pt)
        pt = _add(pt, pt); k >>= 1
    return r


def ec_verify(x, y, msg, der):
    if (y * y - (x ** 3 - 3 * x + BC)) % P != 0:
        return False
    try:
        if der[0] != 0x30:
            return False
        i = 2 if der[1] < 0x80 else 3
        rl = der[i + 1]; r = int.from_bytes(der[i + 2:i + 2 + rl], "big"); j = i + 2 + rl
        sl = der[j + 1]; s = int.from_bytes(der[j + 2:j + 2 + sl], "big")
    except Exception:
        return False
    if not (0 < r < N and 0 < s < N):
        return False
    z = int.from_bytes(hashlib.sha256(msg).digest(), "big"); w = pow(s, -1, N)
    pt = _add(_mul(z * w % N, G), _mul(r * w % N, (x, y)))
    return pt is not None and pt[0] % N == r


def rsa_verify(n, e, msg, sig):
    k = (n.bit_length() + 7) // 8
    em = pow(int.from_bytes(sig, "big"), e, n).to_bytes(k, "big")
    t = bytes.fromhex("3031300d060960864801650304020105000420") + hashlib.sha256(msg).digest()
    return em == b"\x00\x01" + b"\xff" * (k - len(t) - 3) + b"\x00" + t


def verify_sig(pub, msg, sig):
    if pub["alg"] == -7:
        return ec_verify(int(pub["x"], 16), int(pub["y"], 16), msg, sig)
    if pub["alg"] == -257:
        return rsa_verify(int(pub["n"], 16), int(pub["e"], 16), msg, sig)
    return False


def rp_id():
    return request.host.split(":")[0]


def check_client(cd_raw, typ):
    cd = json.loads(cd_raw)
    ch = session.get("bio_chal")
    if not ch or time.time() - ch[1] > 180 or ch[2] != typ:
        raise ValueError("Challenge expired. Please try again.")
    if cd.get("type") != typ or cd.get("challenge") != ch[0]:
        raise ValueError("Challenge mismatch.")
    if urlparse(cd.get("origin", "")).hostname != rp_id():
        raise ValueError("This device was verified for a different website address.")
    session.pop("bio_chal", None)


def new_chal(typ):
    c = b64u(secrets.token_bytes(32)); session["bio_chal"] = (c, time.time(), typ); return c


def fail(msg, code=400):
    return jsonify(ok=False, msg=msg), code


@app.route("/biometric/register/begin", methods=["POST"])
@need()
def bio_reg_begin():
    ex_ids = [{"type": "public-key", "id": r["cred_id"]} for r in q("SELECT cred_id FROM webauthn WHERE user_id=?", (g.user["id"],))]
    return jsonify(ok=True, publicKey={"challenge": new_chal("webauthn.create"), "rp": {"name": "Care HCM - Code Care MB", "id": rp_id()},
                   "user": {"id": b64u(str(g.user["id"]).encode()), "name": g.user["username"], "displayName": g.emp["full_name"] if g.emp else g.user["username"]},
                   "pubKeyCredParams": [{"type": "public-key", "alg": -7}, {"type": "public-key", "alg": -257}], "timeout": 60000, "attestation": "none",
                   "authenticatorSelection": {"authenticatorAttachment": "platform", "userVerification": "required", "residentKey": "discouraged"}, "excludeCredentials": ex_ids})


@app.route("/biometric/register/finish", methods=["POST"])
@need()
def bio_reg_finish():
    d = request.get_json(silent=True) or {}
    try:
        check_client(unb64u(d["clientDataJSON"]), "webauthn.create")
        att, _ = cbor(unb64u(d["attestationObject"])); ad = att["authData"]
        if ad[:32] != hashlib.sha256(rp_id().encode()).digest():
            return fail("Website address mismatch.")
        if not (ad[32] & 1 and ad[32] & 4 and ad[32] & 0x40):
            return fail("Fingerprint / screen-lock verification was not completed.")
        ln = int.from_bytes(ad[53:55], "big"); cid = ad[55:55 + ln]; key, _ = cbor(ad, 55 + ln)
        if key.get(3) == -7 and key.get(1) == 2:
            pub = {"alg": -7, "x": key[-2].hex(), "y": key[-3].hex()}
        elif key.get(3) == -257 and key.get(1) == 3:
            pub = {"alg": -257, "n": key[-1].hex(), "e": key[-2].hex()}
        else:
            return fail("This device uses an unsupported key type.")
        ex("INSERT OR REPLACE INTO webauthn(user_id,cred_id,pub,counter,label,created) VALUES(?,?,?,?,?,datetime('now'))",
           (g.user["id"], b64u(cid), json.dumps(pub), int.from_bytes(ad[33:37], "big"), (d.get("label") or "My device")[:40]))
        audit("biometric_registered", g.user["username"])
        return jsonify(ok=True, msg="Fingerprint check-in is now enabled on this device.")
    except (ValueError, KeyError, IndexError, TypeError) as e:
        return fail(str(e) or "Could not register this device.")


@app.route("/biometric/auth/begin", methods=["POST"])
@need()
def bio_auth_begin():
    creds = q("SELECT cred_id FROM webauthn WHERE user_id=?", (g.user["id"],))
    if not creds:
        return fail("No fingerprint device registered yet.")
    return jsonify(ok=True, publicKey={"challenge": new_chal("webauthn.get"), "rpId": rp_id(), "timeout": 60000, "userVerification": "required",
                                        "allowCredentials": [{"type": "public-key", "id": c["cred_id"]} for c in creds]})


@app.route("/attendance/punch/bio", methods=["POST"])
@need()
def punch_bio():
    if not g.emp:
        abort(403)
    d = request.get_json(silent=True) or {}
    try:
        row = q("SELECT * FROM webauthn WHERE user_id=? AND cred_id=?", (g.user["id"], d.get("id", "")), True)
        if not row:
            return fail("This fingerprint device is not registered for your account.")
        cd_raw, ad, sig = unb64u(d["clientDataJSON"]), unb64u(d["authenticatorData"]), unb64u(d["signature"])
        check_client(cd_raw, "webauthn.get")
        if ad[:32] != hashlib.sha256(rp_id().encode()).digest():
            return fail("Website address mismatch.")
        if not (ad[32] & 1 and ad[32] & 4):
            return fail("Fingerprint / screen-lock verification was not completed.")
        if not verify_sig(json.loads(row["pub"]), ad + hashlib.sha256(cd_raw).digest(), sig):
            audit("biometric_failed", g.user["username"])
            return fail("Fingerprint could not be verified.", 403)
        cnt = int.from_bytes(ad[33:37], "big")
        if cnt and cnt <= (row["counter"] or 0):
            return fail("Security check failed (replayed request).", 403)
        ex("UPDATE webauthn SET counter=?, last_used=datetime('now') WHERE id=?", (cnt, row["id"]))
    except (ValueError, KeyError, IndexError, TypeError) as e:
        return fail(str(e) or "Could not verify fingerprint.")
    ok, msg = A.do_punch("Biometric")
    flash(msg, "ok" if ok else "err")
    return jsonify(ok=ok, msg=msg)


@app.route("/biometric/remove", methods=["POST"])
@need()
def bio_remove():
    ex("DELETE FROM webauthn WHERE id=? AND user_id=?", (request.form.get("id"), g.user["id"])); audit("biometric_removed", g.user["username"]); flash("Device removed.", "ok")
    return redirect(url_for("account"))


@app.context_processor
def _bio_ctx():
    n = q("SELECT count(*) c FROM webauthn WHERE user_id=?", (g.user["id"],), True)["c"] if g.get("user") else 0
    return dict(bio_count=n, bio_mode=S("bio_mode") if g.get("user") else "optional")
