import uuid

from pydantic import BaseModel, ConfigDict, EmailStr, field_validator, model_validator

from app.core.config import settings
from app.utils.phone import InvalidPhoneNumber, normalize_ethiopian_phone


def _validate_phone(v: str) -> str:
    try:
        return normalize_ethiopian_phone(v)
    except InvalidPhoneNumber as exc:
        raise ValueError(str(exc)) from exc


def _validate_name(v: str) -> str:
    v = v.strip()
    if not v:
        raise ValueError("Name is required.")
    return v


def _clean_email(v: str) -> str:
    """Normalize before EmailStr validates format: trimmed and
    lowercased, so e.g. "Foo@Example.com " and "foo@example.com" are
    treated as the same address for the uniqueness check. Used where
    email is mandatory (invited accounts, login identifier), so
    blank/whitespace-only is rejected the same as an invalid
    address."""
    if not isinstance(v, str) or not v.strip():
        raise ValueError("Email is required.")
    return v.strip().lower()


def _clean_optional_email(v: str | None) -> str | None:
    """Same normalization as _clean_email, but passes None through —
    for the customer self-signup/add-identifier flows where email is
    optional (see CustomerSignupRequest)."""
    if v is None:
        return None
    if not isinstance(v, str) or not v.strip():
        return None
    return v.strip().lower()


def _validate_pin(v: str) -> str:
    if not v.isdigit() or len(v) != settings.pin_length:
        raise ValueError(f"PIN must be exactly {settings.pin_length} digits.")
    return v


# Every all-same-digit PIN ("000000".."999999") plus the handful of
# sequences people reach for next — ascending/descending runs and a
# couple of well-known "random-looking" ones that show up at the top
# of every leaked-PIN frequency list. Not exhaustive (no blocklist
# is), just cheap insurance against the PINs a brute-force guesser
# would try first, on top of the actual defenses (lockout + rate
# limiting) that do the real work.
_WEAK_PINS = {str(d) * 6 for d in range(10)} | {
    "123456",
    "654321",
    "012345",
    "543210",
    "123123",
    "121212",
    "010101",
}


def _validate_new_pin(v: str) -> str:
    """Same format check as _validate_pin, plus a blocklist — only for
    a PIN actually being *set* (signup, forgot-pin reset, change-pin).
    Deliberately not applied to LoginRequest/ChangePinRequest.
    current_pin: someone proving they know an existing weak PIN
    (already allowed before this check existed) should still be able
    to log in or authorize a change — the blocklist only stops *new*
    weak PINs from being chosen going forward."""
    v = _validate_pin(v)
    if v in _WEAK_PINS:
        raise ValueError(
            "This PIN is too easy to guess — choose a less predictable one."
        )
    return v


def _validate_otp_code(v: str) -> str:
    if not v.isdigit() or len(v) != settings.otp_length:
        raise ValueError(
            f"Verification code must be exactly {settings.otp_length} digits."
        )
    return v


class PhoneAndNameRequest(BaseModel):
    """Phone + name + email — used when an admin invites a
    courier/supplier/admin (see app.api.v1.endpoints.admin), where both
    are always mandatory. Customer self-signup uses
    CustomerSignupRequest instead, which only ever requires one of
    phone/email."""

    phone: str
    name: str
    email: EmailStr

    @field_validator("phone")
    @classmethod
    def _phone(cls, v: str) -> str:
        return _validate_phone(v)

    @field_validator("name")
    @classmethod
    def _name(cls, v: str) -> str:
        return _validate_name(v)

    @field_validator("email", mode="before")
    @classmethod
    def _email(cls, v: str) -> str:
        return _clean_email(v)


class CustomerSignupRequest(BaseModel):
    """Customer self-signup — single-identifier-first: exactly one of
    phone or email, never both. Whichever one is given gets a single
    OTP code and becomes the account's one verified identifier; the
    other stays unset and can be added later, skippably, via
    /auth/phone/* or /auth/email/*. Invited accounts
    (courier/supplier/admin) are unaffected — still always phone+email
    via PhoneAndNameRequest, see app.api.v1.endpoints.admin."""

    model_config = ConfigDict(
        json_schema_extra={
            "examples": [{"name": "Abebe Kebede", "phone": "0912345678"}]
        }
    )

    name: str
    phone: str | None = None
    email: EmailStr | None = None

    @field_validator("name")
    @classmethod
    def _name(cls, v: str) -> str:
        return _validate_name(v)

    @field_validator("phone")
    @classmethod
    def _phone(cls, v: str | None) -> str | None:
        return _validate_phone(v) if v else None

    @field_validator("email", mode="before")
    @classmethod
    def _email(cls, v: str | None) -> str | None:
        return _clean_optional_email(v)

    @model_validator(mode="after")
    def _exactly_one_identifier(self) -> "CustomerSignupRequest":
        if bool(self.phone) == bool(self.email):
            raise ValueError("Provide exactly one of phone or email, not both.")
        return self


class OtpVerifyRequest(BaseModel):
    """identifier (phone or email) + OTP code — shared by signup,
    forgot-pin, and account activation, all of which now key their OTP
    by whichever identifier the flow is actually verifying."""

    model_config = ConfigDict(
        json_schema_extra={
            "examples": [{"identifier": "0912345678", "otp_code": "123456"}]
        }
    )

    identifier: str
    otp_code: str

    @field_validator("identifier")
    @classmethod
    def _identifier(cls, v: str) -> str:
        v = v.strip()
        if not v:
            raise ValueError("Phone number or email is required.")
        if "@" in v:
            return _clean_email(v)
        return _validate_phone(v)

    @field_validator("otp_code")
    @classmethod
    def _otp_code(cls, v: str) -> str:
        return _validate_otp_code(v)


class PhoneOtpVerifyRequest(BaseModel):
    """Phone + OTP code — used by /auth/phone/verify-otp specifically,
    where the identifier is always a phone number."""

    phone: str
    otp_code: str

    @field_validator("phone")
    @classmethod
    def _phone(cls, v: str) -> str:
        return _validate_phone(v)

    @field_validator("otp_code")
    @classmethod
    def _otp_code(cls, v: str) -> str:
        return _validate_otp_code(v)


class EmailOtpVerifyRequest(BaseModel):
    """Email + OTP code — used by /auth/email/verify-otp, the
    email-keyed counterpart to PhoneOtpVerifyRequest."""

    email: EmailStr
    otp_code: str

    @field_validator("email", mode="before")
    @classmethod
    def _email(cls, v: str) -> str:
        return _clean_email(v)

    @field_validator("otp_code")
    @classmethod
    def _otp_code(cls, v: str) -> str:
        return _validate_otp_code(v)


class PinSetRequest(BaseModel):
    """Verification token + PIN: the final step of signup, forgot-pin
    reset, and account activation."""

    model_config = ConfigDict(
        json_schema_extra={
            "examples": [
                {"verification_token": "a1b2c3d4...", "pin": "417293"}  # nosec B105 -- OpenAPI example value, not a credential
            ]
        }
    )

    verification_token: str
    pin: str

    @field_validator("pin")
    @classmethod
    def _pin(cls, v: str) -> str:
        return _validate_new_pin(v)


class LoginRequest(BaseModel):
    """identifier is a phone number or an email address — detected by
    format (see app.api.v1.endpoints.auth.login), since signup can now
    leave either one as the verified identifier depending on which
    channel the customer confirmed. Only a *verified* phone/email can
    ever be matched at login — see the User model docstring."""

    model_config = ConfigDict(
        json_schema_extra={"examples": [{"identifier": "0912345678", "pin": "417293"}]}
    )

    identifier: str
    pin: str

    @field_validator("identifier")
    @classmethod
    def _identifier(cls, v: str) -> str:
        v = v.strip()
        if not v:
            raise ValueError("Phone number or email is required.")
        if "@" in v:
            return _clean_email(v)
        return _validate_phone(v)

    @field_validator("pin")
    @classmethod
    def _pin(cls, v: str) -> str:
        return _validate_pin(v)


class ForgotPinStartRequest(BaseModel):
    """identifier is a phone number or an email address — symmetric to
    LoginRequest, since an email-only-signup customer has no phone to
    reset a PIN by SMS with."""

    identifier: str

    @field_validator("identifier")
    @classmethod
    def _identifier(cls, v: str) -> str:
        v = v.strip()
        if not v:
            raise ValueError("Phone number or email is required.")
        if "@" in v:
            return _clean_email(v)
        return _validate_phone(v)


class GoogleSignInRequest(BaseModel):
    """The ID token from the Flutter app's on-device Google Sign-In —
    our backend never sees a Google password or client secret, only
    verifies this token's signature. See
    app.services.google_oauth.verify_google_id_token. Only signs in an
    account already linked to this Google identity, or creates a new
    one — it never auto-links to an existing phone/email account it
    doesn't already own; see GoogleConnectRequest for that."""

    id_token: str


class GoogleConnectRequest(BaseModel):
    """Links a Google identity to the *currently logged-in* account —
    used by POST /auth/google/connect when GoogleSignInRequest finds an
    email collision it refuses to auto-link. Requires re-entering the
    PIN even though the caller is already authenticated: proof that
    this specific sensitive action (permanently attaching a new login
    method) is really being done by the account holder, not just
    whoever is holding an unlocked session."""

    id_token: str
    pin: str

    @field_validator("pin")
    @classmethod
    def _pin(cls, v: str) -> str:
        return _validate_pin(v)


class ChangePinRequest(BaseModel):
    """Changes the PIN on the currently logged-in account — requires
    the current PIN as proof this sensitive action is really the
    account holder, same reasoning as GoogleConnectRequest above."""

    current_pin: str
    new_pin: str

    @field_validator("current_pin")
    @classmethod
    def _current_pin(cls, v: str) -> str:
        return _validate_pin(v)

    @field_validator("new_pin")
    @classmethod
    def _new_pin(cls, v: str) -> str:
        return _validate_new_pin(v)


class AddPhoneStartRequest(BaseModel):
    """First step of adding/replacing a verified phone number on an
    already-authenticated account — see app.api.v1.endpoints.auth's
    /auth/phone/* endpoints. Distinct from CustomerSignupRequest's
    phone step: this one requires an existing session, not a fresh
    account."""

    phone: str

    @field_validator("phone")
    @classmethod
    def _phone(cls, v: str) -> str:
        return _validate_phone(v)


class AddEmailStartRequest(BaseModel):
    """Symmetric to AddPhoneStartRequest, for verifying/replacing the
    email on an already-authenticated account — see
    app.api.v1.endpoints.auth's /auth/email/* endpoints."""

    email: EmailStr

    @field_validator("email", mode="before")
    @classmethod
    def _email(cls, v: str) -> str:
        return _clean_email(v)


class VerificationTokenOnlyRequest(BaseModel):
    """Just the verification_token from /auth/phone/verify-otp or
    /auth/email/verify-otp — no PIN involved, unlike PinSetRequest,
    since adding a phone/email to an already-logged-in account doesn't
    touch the PIN at all."""

    verification_token: str


class MarketingConsentRequest(BaseModel):
    """PATCH /auth/me/marketing-consent — a standalone, explicit opt-in
    step, separate from signup itself, since by the time the app
    prompts for it the customer is already logged in (see the User
    model docstring on marketing_emails_opt_in)."""

    opt_in: bool


class RefreshRequest(BaseModel):
    refresh_token: str


class LogoutRequest(BaseModel):
    refresh_token: str


class UserOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    phone: str | None
    name: str
    email: str | None
    role: str
    is_phone_verified: bool
    is_email_verified: bool
    marketing_emails_opt_in: bool
    is_active: bool


class UserStatusUpdateRequest(BaseModel):
    """Admin-only account activation switch — see
    app.api.v1.endpoints.admin.update_user_status. is_active is
    already what app.api.v1.deps.get_current_user and
    app.services.tokens both check on every request, so setting this
    to false immediately blocks both the access and refresh token —
    no separate session-revocation step needed."""

    is_active: bool


class TokenResponse(BaseModel):
    access_token: str
    refresh_token: str
    token_type: str = "bearer"
    user: UserOut


class MessageResponse(BaseModel):
    message: str
    # Only populated when ENVIRONMENT=development, since no real SMS
    # gateway is wired up yet — lets you test signup/reset without
    # having to tail server logs for the code. Never set outside dev.
    debug_otp: str | None = None


class VerificationTokenResponse(BaseModel):
    verification_token: str
    expires_in_minutes: int


class InviteResponse(BaseModel):
    message: str
    debug_otp: str | None = None
    user: UserOut
