from datetime import timedelta
from typing import Literal

from sqlalchemy.orm import Session

from app.core import security
from app.core.config import settings
from app.models.otp import OTPPurpose, OTPVerification
from app.services.email import send_templated_email
from app.services.sms import send_sms
from app.utils.time import utcnow


class OTPError(Exception):
    """A verification code couldn't be accepted as submitted."""


# One (subject, heading, intro) tuple per purpose — see
# app.templates.email.otp for how these render. Deliberately not just
# one generic "here's your code" email: the reader should be able to
# tell from the subject line alone whether this is the code they
# expect (someone requesting a PIN reset they didn't ask for is
# exactly the case worth being unambiguous for).
_OTP_EMAIL_COPY: dict[OTPPurpose, tuple[str, str, str]] = {
    OTPPurpose.SIGNUP: (
        "Verify your email — YENEB CODS",
        "Verify your email",
        "Enter this code to finish creating your YENEB account.",
    ),
    OTPPurpose.RESET_PIN: (
        "Reset your PIN — YENEB CODS",
        "Reset your PIN",
        "Enter this code to reset your YENEB account PIN.",
    ),
    OTPPurpose.ACTIVATE_ACCOUNT: (
        "Activate your account — YENEB CODS",
        "Activate your account",
        "Enter this code to activate your YENEB account.",
    ),
    OTPPurpose.ADD_EMAIL: (
        "Verify your email — YENEB CODS",
        "Verify your email",
        "Enter this code to add this email to your YENEB account.",
    ),
    OTPPurpose.ADD_PHONE: (
        "Verify your phone — YENEB CODS",
        "Verify your phone",
        "Enter this code to add this phone number to your YENEB account.",
    ),
}


def create_and_send_otp(
    db: Session,
    identifier: str,
    purpose: OTPPurpose,
    channel: Literal["sms", "email"] = "sms",
    pending_name: str | None = None,
) -> str:
    """Invalidate any earlier unconsumed code for this exact
    (identifier, purpose, channel), issue a new one, and send it.
    Returns the plaintext code — callers only use this to echo it back
    in dev mode (see app.api.v1.endpoints.auth), never to log or store
    it anywhere."""
    db.query(OTPVerification).filter(
        OTPVerification.identifier == identifier,
        OTPVerification.purpose == purpose.value,
        OTPVerification.channel == channel,
        OTPVerification.consumed_at.is_(None),
    ).delete()

    code = security.generate_otp_code(settings.otp_length)
    db.add(
        OTPVerification(
            identifier=identifier,
            purpose=purpose.value,
            channel=channel,
            pending_name=pending_name,
            code_hash=security.hash_otp(code),
            max_attempts=settings.otp_max_attempts,
            expires_at=utcnow() + timedelta(minutes=settings.otp_expire_minutes),
        )
    )
    db.commit()

    if channel == "email":
        subject, heading, intro_text = _OTP_EMAIL_COPY[purpose]
        send_templated_email(
            identifier,
            subject,
            "otp",
            {
                "heading": heading,
                "intro_text": intro_text,
                "code": code,
                "expiry_minutes": settings.otp_expire_minutes,
                "name": pending_name,
            },
        )
    else:
        message = (
            f"Your Yeneb verification code is {code}. It expires in "
            f"{settings.otp_expire_minutes} minutes."
        )
        send_sms(identifier, message)

    return code


def verify_otp(
    db: Session, identifier: str, purpose: OTPPurpose, code: str
) -> tuple[OTPVerification, str]:
    """Verify a submitted code against the still-unconsumed code for
    (identifier, purpose). Raises OTPError with a user-facing message
    on any failure. On success, marks the record consumed and issues a
    short-lived verification token — proof of that identifier's
    identity — so the caller doesn't have to submit the OTP code again
    to finish signing up / resetting a PIN. Returns
    (record, verification_token); record.channel tells the caller
    whether identifier is a phone or an email."""
    candidates = (
        db.query(OTPVerification)
        .filter(
            OTPVerification.identifier == identifier,
            OTPVerification.purpose == purpose.value,
            OTPVerification.consumed_at.is_(None),
        )
        .order_by(OTPVerification.created_at.desc())
        .all()
    )

    if not candidates:
        raise OTPError("Request a new verification code first.")

    live = [c for c in candidates if c.expires_at >= utcnow()]
    if not live:
        raise OTPError("This verification code has expired. Request a new one.")
    if all(c.attempts >= c.max_attempts for c in live):
        raise OTPError("Too many incorrect attempts. Request a new code.")

    matched = next(
        (
            c
            for c in live
            if c.attempts < c.max_attempts
            and security.verify_otp_hash(code, c.code_hash)
        ),
        None,
    )
    if matched is None:
        for c in live:
            if c.attempts < c.max_attempts:
                c.attempts += 1
        db.commit()
        raise OTPError("Incorrect verification code.")

    token = security.generate_verification_token()
    matched.consumed_at = utcnow()
    matched.verification_token_hash = security.hash_verification_token(token)
    matched.verification_token_expires_at = utcnow() + timedelta(
        minutes=settings.verification_token_expire_minutes
    )
    db.commit()
    return matched, token


def consume_verification_token(
    db: Session, purpose: OTPPurpose, token: str
) -> OTPVerification:
    """Redeem a verification token from verify_otp(). Single-use: clears
    the token hash on success so it can't be replayed."""
    token_hash = security.hash_verification_token(token)
    record = (
        db.query(OTPVerification)
        .filter(
            OTPVerification.purpose == purpose.value,
            OTPVerification.verification_token_hash == token_hash,
        )
        .first()
    )

    if record is None:
        raise OTPError("Verify your phone number again.")
    if record.verification_token_expires_at < utcnow():
        raise OTPError("This verification has expired. Verify your phone number again.")

    record.verification_token_hash = None
    db.commit()
    return record
