"""Verification and anchor endpoints."""

from __future__ import annotations

import sqlite3

from fastapi import APIRouter, Depends, HTTPException

from ads_foundation.merkle import MerkleProof, Side, verify_proof

from ..auth import require_api_key
from ..db import get_db
from ..models import (
    AnchorRequest,
    AnchorResponse,
    VerifyRequest,
    VerifyResponse,
)

router = APIRouter()


@router.post("/verify", response_model=VerifyResponse)
def verify(
    body: VerifyRequest,
    api_key: dict = Depends(require_api_key),
    conn: sqlite3.Connection = Depends(get_db),
):
    path = [
        (Side[entry.side], bytes.fromhex(entry.sibling_hash))
        for entry in body.proof
    ]
    proof = MerkleProof(path=path, root_hash=bytes.fromhex(body.proof_root))
    record_hash_bytes = bytes.fromhex(body.record_hash)

    valid = verify_proof(record_hash_bytes, proof)

    anchored = False
    anchor_created_at = None
    if valid:
        row = conn.execute(
            "SELECT created_at FROM anchors WHERE api_key_id = ? AND root_hash = ?",
            (api_key["id"], body.proof_root),
        ).fetchone()
        if row:
            anchored = True
            anchor_created_at = row["created_at"]

    return VerifyResponse(
        valid=valid,
        anchored=anchored,
        anchor_created_at=anchor_created_at,
    )


@router.post("/anchors", response_model=AnchorResponse, status_code=201)
def create_anchor(
    body: AnchorRequest,
    api_key: dict = Depends(require_api_key),
    conn: sqlite3.Connection = Depends(get_db),
):
    try:
        conn.execute(
            """INSERT INTO anchors (api_key_id, root_hash, receipt_count)
               VALUES (?, ?, ?)""",
            (api_key["id"], body.root_hash, body.receipt_count),
        )
        conn.commit()
    except sqlite3.IntegrityError:
        raise HTTPException(
            status_code=409,
            detail="Anchor with this root hash already exists",
        )

    row = conn.execute(
        "SELECT created_at FROM anchors WHERE api_key_id = ? AND root_hash = ?",
        (api_key["id"], body.root_hash),
    ).fetchone()

    return AnchorResponse(
        root_hash=body.root_hash,
        receipt_count=body.receipt_count,
        created_at=row["created_at"],
    )
