from decimal import Decimal
from urllib.parse import quote

from pydantic import model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    app_name: str = "Yeneb CODS API"
    environment: str = "development"

    # CORS (see app.main and the cors_allowed_origins property below).
    # Empty by default — deliberately secure over convenient: the
    # mobile apps are native HTTP clients and never hit CORS at all, so
    # this only matters once a browser-based client (an admin/partner
    # web console) exists, and it should list that console's real
    # origin(s) explicitly rather than "*". Comma-separated (the
    # natural .env form) rather than a list field, since pydantic-
    # settings would otherwise try to JSON-parse a list-typed env var.
    cors_allowed_origins_raw: str = ""

    db_user: str = "postgres"
    db_password: str = "postgres"
    db_host: str = "localhost"
    db_port: int = 5432
    db_name: str = "yeneb"
    # psycopg sslmode (disable/allow/prefer/require/verify-ca/verify-
    # full). "prefer" — the psycopg/libpq default — uses TLS whenever
    # the server offers it but falls back to plaintext otherwise, so
    # local dev (no TLS configured on a local Postgres) keeps working
    # unchanged. environment=="production" requires at least "require"
    # (see _reject_placeholder_secrets_in_production below) — a
    # deployment talking to a real Postgres over an untrusted network
    # should never silently downgrade to plaintext.
    db_sslmode: str = "prefer"

    redis_host: str = "localhost"
    redis_port: int = 6379
    redis_db: int = 0

    cloudinary_cloud_name: str = ""
    cloudinary_api_key: str = ""
    cloudinary_api_secret: str = ""

    # Uploads (see app.api.v1.endpoints.uploads) — enforced before the
    # bytes ever reach Cloudinary, not just relying on Cloudinary's own
    # account-level limits.
    max_upload_size_bytes: int = 5 * 1024 * 1024

    # Empty by default (local dev/tests) — app.services.sms only makes a
    # real API call when this is set, so the test suite (which triggers
    # OTP sends on nearly every request) never hits the network.
    sms_ethiopia_api_key: str = ""

    # Same reasoning as sms_ethiopia_api_key above, for app.services.email
    # — only smtp_password gates a real send; the other three have
    # defaults matching our own mail hosting (port 465 = implicit
    # SSL/TLS, not STARTTLS) so only the secret needs setting in
    # production.
    smtp_host: str = "mail.yeneb.com"
    smtp_port: int = 465
    smtp_username: str = "noreply@yeneb.com"
    smtp_password: str = ""
    smtp_sender_name: str = "YENEB CODS"

    # Header logo for HTML emails (see app/templates/email/) — hosted
    # on Cloudinary since that's already this project's asset host
    # (see app.services.upload). Not a secret, just a URL; overridable
    # in case the logo ever moves.
    email_logo_url: str = (
        "https://res.cloudinary.com/dkvh0gurm/image/upload/"
        "v1785763909/yeneb/brand/logo.jpg"
    )

    # Google Sign-In (see app.services.google_oauth). This is the OAuth
    # client ID ("audience"), not a secret — verifying an ID token only
    # needs it to check the token was actually issued for this app, not
    # a credential we authenticate with. Empty by default, same
    # log-only-until-configured pattern as the other providers: without
    # it, app.services.google_oauth.verify_google_id_token refuses to
    # even try, so the test suite never needs network access or a real
    # client ID — tests monkeypatch the verify function directly instead
    # (see tests/test_google_auth.py).
    google_oauth_client_id: str = ""

    # Chapa (payment gateway). chapa_webhook_secret is a separate value
    # you set in the Chapa dashboard specifically for signing webhook
    # payloads — not the same as chapa_secret_key (used to authenticate
    # our own API calls to Chapa). Same empty-by-default pattern as the
    # other providers above: app.services.payments.chapa only calls the real API
    # when chapa_secret_key is set.
    chapa_secret_key: str = ""
    chapa_webhook_secret: str = ""
    chapa_callback_url: str = ""
    chapa_return_url: str = ""

    # Push notifications (FCM HTTP v1 API — see app.services.push). Both
    # Flutter apps already integrate firebase_messaging client-side, so
    # FCM isn't a choice being made here, just the credential this
    # backend needs to call it. fcm_service_account_json is the full
    # service-account key JSON (as one string) downloaded from the
    # Firebase console — used to mint short-lived OAuth2 access tokens
    # for the HTTP v1 API, unlike the legacy system's simpler (and now
    # Google-deprecated) static server-key header. Same empty-by-default
    # pattern as the other providers above: app.services.push only
    # calls the real API when both are set.
    fcm_project_id: str = ""
    fcm_service_account_json: str = ""

    # Public download link for the customer app (Play Store/App Store)
    # — used only in the "Order for a Friend" SMS to an unregistered
    # recipient (see app.services.order_notifications), to invite them
    # to install the app rather than just describing an order they
    # can't otherwise see. Empty by default: the Play Store release is
    # still pending as of this writing, and sending a broken/fake link
    # would be worse than sending no link at all — that sentence is
    # simply omitted from the SMS until this is set to a real one.
    app_download_url: str = ""

    # Rate limiting (Redis) — max requests per window, per IP and per
    # phone independently, on the abuse-prone auth endpoints (OTP
    # requests, OTP verification, login). Deliberately higher than
    # otp_max_attempts/max_pin_attempts below: those are specific,
    # informative business-logic limits (wrong-code, wrong-PIN) that
    # should fire first with their own message; this is a broader
    # outer backstop against high-volume/automated abuse.
    rate_limit_max_attempts: int = 10
    rate_limit_window_seconds: int = 300

    # A separate, much more generous per-IP cap applied to *every*
    # endpoint (see app.services.rate_limit.rate_limit_global) — a
    # last-resort backstop against one client hammering the API in
    # general, not a replacement for the tighter action-specific
    # limits above.
    global_rate_limit_max_requests: int = 300
    global_rate_limit_window_seconds: int = 60

    # Tighter, per-user limits on top of the global backstop above, for
    # the two non-auth endpoints where a single abusive account has a
    # direct cost: repeated checkout calls tie up couriers and hit
    # Chapa per attempt, and each upload costs money via Cloudinary
    # regardless of whether the image is ever used anywhere.
    checkout_rate_limit_max_attempts: int = 10
    checkout_rate_limit_window_seconds: int = 300
    upload_rate_limit_max_attempts: int = 20
    upload_rate_limit_window_seconds: int = 300

    # Rejected before the body is even read if Content-Length declares
    # more than this (see app.core.middleware.
    # RequestBodySizeLimitMiddleware) — comfortably above
    # max_upload_size_bytes to leave room for multipart overhead,
    # since the upload endpoint is the one legitimate large-body case.
    max_request_body_bytes: int = 6 * 1024 * 1024

    # Error tracking (see app.main) — empty by default, same opt-in-
    # when-configured pattern as the other providers above: Sentry is
    # only initialized once a real DSN is set, so local dev/tests never
    # try to report anything anywhere. traces_sample_rate is 0 by
    # default (errors only, no performance tracing) — deliberately
    # conservative since this API handles PINs and payment data and
    # tracing spans can end up carrying request details.
    sentry_dsn: str = ""
    sentry_traces_sample_rate: float = 0.0

    # Caching (Redis) — how long a cached merchant/branch/menu read is
    # served before hitting Postgres again. Short on purpose: correctness
    # (an approval showing up promptly) matters more than shaving a few
    # more requests, and a short TTL bounds staleness without needing
    # precise invalidation for every mutation.
    cache_ttl_seconds: int = 30

    # Auth
    secret_key: str = "change-me-in-production"
    access_token_expire_minutes: int = 30
    refresh_token_expire_days: int = 30

    # OTP / PIN
    otp_length: int = 6
    otp_expire_minutes: int = 5
    otp_max_attempts: int = 5
    verification_token_expire_minutes: int = 10
    pin_length: int = 6
    max_pin_attempts: int = 5
    lockout_minutes: int = 15

    # Order pricing (see app.services.pricing). Delivery fee is
    # distance-based: a flat base plus a per-km rate, computed from the
    # branch-to-delivery-address distance — unlike the legacy system,
    # which used one flat deliveryprice per restaurant regardless of
    # distance. service_fee_rate is a genuinely new line the legacy
    # system never had (it had no service/platform fee concept at
    # all). vat_rate matches the legacy formula (15% of subtotal +
    # delivery_fee) — the one legacy figure confirmed from its code
    # rather than chosen fresh.
    delivery_fee_base: Decimal = Decimal("20.00")
    delivery_fee_per_km: Decimal = Decimal("10.00")
    service_fee_rate: Decimal = Decimal("0.05")
    vat_rate: Decimal = Decimal("0.15")

    # A general estimate shown on the order confirmation email (see
    # app.templates.email.order_confirmation) — not computed from
    # anything (no per-branch prep-time/distance-based ETA exists in
    # this codebase yet), just a reasonable stated range, same as most
    # delivery apps show before a courier is actually assigned.
    delivery_eta_min_minutes: int = 30
    delivery_eta_max_minutes: int = 45
    pickup_eta_min_minutes: int = 15
    pickup_eta_max_minutes: int = 20

    model_config = SettingsConfigDict(env_file=".env", extra="ignore")

    @model_validator(mode="after")
    def _enforce_production_hardening(self) -> "Settings":
        """secret_key and db_password default to shared, memorable
        placeholder values on purpose — convenient for local dev/tests,
        where every clone of this repo should behave identically out of
        the box. That same convenience is a real risk in production: a
        missing or misconfigured .env should fail loudly at startup
        with environment=="production", not silently boot with a JWT
        signing key, DB password, or unencrypted DB connection every
        clone of this repo already has/allows by default."""
        if self.environment != "production":
            return self
        if self.secret_key == "change-me-in-production":  # nosec B105 -- rejecting the placeholder, not using it as a credential
            raise ValueError(
                "secret_key is still the placeholder default — set a real "
                "SECRET_KEY before running with environment=production."
            )
        if self.db_password == "postgres":  # nosec B105 -- same as above, not a credential
            raise ValueError(
                "db_password is still the placeholder default — set a real "
                "DB_PASSWORD before running with environment=production."
            )
        # TLS protects data crossing a network segment an attacker could
        # sit on — that's meaningless for db_host on loopback, where the
        # "connection" never leaves the machine, and plenty of real
        # deployments (app and Postgres colocated on one host, e.g. a
        # shared-hosting box) don't have TLS configured on Postgres's
        # local listener at all. Only require it once the DB is actually
        # reachable over a real network.
        db_is_local = self.db_host in {"localhost", "127.0.0.1", "::1"}
        if not db_is_local and self.db_sslmode not in {
            "require",
            "verify-ca",
            "verify-full",
        }:
            raise ValueError(
                f"db_sslmode={self.db_sslmode!r} doesn't enforce TLS — set "
                "DB_SSLMODE to require/verify-ca/verify-full before running "
                "with environment=production and a non-local DB_HOST."
            )
        return self

    @property
    def database_url(self) -> str:
        # db_user/db_password are plain values in .env (not
        # pre-encoded) but get embedded in a URL here — quote() so a
        # password containing reserved URL characters (?, =, $, @, ...,
        # all fair game for a generated Postgres password) doesn't
        # corrupt the DSN psycopg parses this into.
        user = quote(self.db_user, safe="")
        password = quote(self.db_password, safe="")
        return (
            f"postgresql+psycopg://{user}:{password}"
            f"@{self.db_host}:{self.db_port}/{self.db_name}"
            f"?sslmode={self.db_sslmode}"
        )

    @property
    def redis_url(self) -> str:
        return f"redis://{self.redis_host}:{self.redis_port}/{self.redis_db}"

    @property
    def cors_allowed_origins(self) -> list[str]:
        if not self.cors_allowed_origins_raw.strip():
            return []
        return [
            origin.strip()
            for origin in self.cors_allowed_origins_raw.split(",")
            if origin.strip()
        ]


settings = Settings()
