"""
Central configuration for the FinanceGPT Bot.

All values can be overridden through environment variables so that secrets
(the bot token) never have to live in source control.
"""

import os

# Load variables from a local .env file if python-dotenv is available.
# This lets all settings live in one .env file without exporting them by hand.
try:
    from dotenv import load_dotenv

    _env_path = os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".env"
    )
    load_dotenv(_env_path)
except Exception:
    # python-dotenv not installed (or no .env file): fall back to real env vars.
    pass


def _env(name: str, default: str = "") -> str:
    value = os.environ.get(name)
    return value if value is not None else default


def _env_text(name: str, default: str) -> str:
    """
    Like `_env`, but for multi-line user-facing text. `.env` files are single
    line per value, so a literal "\\n" typed there becomes a real line break —
    lets these be edited without touching code.
    """
    return _env(name, default).replace("\\n", "\n")


# --- Messaging platform (Telegram) --------------------------------------------

# Telegram bot token (the part after "bot" in the API URL), e.g. "123456:ABC...".
BOT_TOKEN = _env("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_API_BASE = _env("TELEGRAM_API_BASE", "https://api.telegram.org")

# Public URL where this server is reachable; used to register the webhook.
WEBHOOK_URL = _env("WEBHOOK_URL", "https://your-public-host/telegram")

# The gating channel: /start checks whether the sender is a member of this
# channel before letting them use the bot. Numeric channel id (usually -100...).
GEEVEX_CHANNEL_ID = int(_env("GEEVEX_CHANNEL_ID", "0"))

# Public join link for the channel, shown on the "must join" prompt.
CHANNEL_JOIN_URL = _env("CHANNEL_JOIN_URL", "https://t.me/FinanceGPTlab")

# Signature appended to the end of every outgoing message.
# Set this in .env to whatever you want, e.g. "@MyBot" or "🌐 example.com"
BOT_SIGNATURE = _env("BOT_SIGNATURE", "@FinanceGPTlab_bot")

# Bot's own @username (without the @), used to build the "add to group" deep
# link: https://t.me/<BOT_USERNAME>?startgroup=true
BOT_USERNAME = _env("BOT_USERNAME", "FinanceGPTlab_bot")

# URL the "خرید ..." button under a price/amount reply links to, when the
# chat it's sent in has no group-specific referral link registered.
BUY_COIN_URL = _env("BUY_COIN_URL", "https://geevex.com")

# Admin rights (comma-separated, Telegram's own names) pre-selected on the
# "make the bot an admin" screen when someone uses the add-to-group deep
# link. Making the bot an admin also bypasses BotFather's Group Privacy
# restriction, so it can see every group message regardless of that setting.
# Leave empty to skip requesting admin rights (bot joins as a plain member).
ADD_TO_GROUP_ADMIN_RIGHTS = _env("ADD_TO_GROUP_ADMIN_RIGHTS", "delete_messages")


# --- User-facing text (all editable from .env; use "\n" for a line break) ------

MEMBERSHIP_REQUIRED_TEXT = _env_text(
    "MEMBERSHIP_REQUIRED_TEXT",
    "برای استفاده از ربات ابتدا باید در کانال عضو شوید.",
)
MEMBERSHIP_CONFIRMED_TEXT = _env_text("MEMBERSHIP_CONFIRMED_TEXT", "عضویت شما تایید شد")

# Main reply-keyboard button labels (row 1: one button, row 2: two buttons,
# row 3: one button).
MENU_PRICE_BUTTON_TEXT = _env_text("MENU_PRICE_BUTTON_TEXT", "قیمت لحظه ای ارز های دیجیتال")
MENU_EXPLORER_BUTTON_TEXT = _env_text("MENU_EXPLORER_BUTTON_TEXT", "بلاکچین اکسپلور")
MENU_PRICE_ALERT_BUTTON_TEXT = _env_text("MENU_PRICE_ALERT_BUTTON_TEXT", "هشدار قیمت")
MENU_EARN_BUTTON_TEXT = _env_text("MENU_EARN_BUTTON_TEXT", "کسب درامد")

ASK_COIN_TEXT = _env_text(
    "ASK_COIN_TEXT", "نام یا نماد رمزارز خود را ارسال کنید"
)

ADD_TO_GROUP_BUTTON_TEXT = _env_text("ADD_TO_GROUP_BUTTON_TEXT", "➕ افزودن ربات به گروه")

ADD_TO_GROUP_PROMPT_TEXT = _env_text(
    "ADD_TO_GROUP_PROMPT_TEXT",
    "روی دکمه‌ی زیر بزن و گروه موردنظرت رو انتخاب کن تا ربات به اون گروه اضافه بشه.\n"
    "\n"
    "⚠️ در همون مرحله، تلگرام درخواست می‌کنه ربات رو ادمین گروه کنی — این کار لازمه "
    "تا ربات بتونه همه‌ی پیام‌های گروه رو ببینه.",
)

NOT_GROUP_ADMIN_TEXT = _env_text("NOT_GROUP_ADMIN_TEXT", "شما ادمین این گروه نیستید.")

BOT_ADDED_TO_GROUP_MESSAGE_TEXT = _env_text(
    "BOT_ADDED_TO_GROUP_MESSAGE_TEXT",
    "ربات فعال شد ✅\nبرای فعال‌سازی کامل، ادمین گروه لینک رفرال خودش را ثبت می‌کند.",
)

ASK_REFERRAL_LINK_TEMPLATE = _env_text(
    "ASK_REFERRAL_LINK_TEMPLATE",
    "ربات با موفقیت به گروه «{group_title}» اضافه شد ✅\n"
    "برای این‌که دکمه‌ی «خرید» زیر قیمت‌ها به لینک رفرال خودتون اشاره کنه، لطفاً "
    "همین‌جا لینک رفرال گیوکس‌تون رو برام بفرستید (باید با http:// یا https:// شروع بشه).",
)

REFERRAL_LINK_INVALID_TEXT = _env_text(
    "REFERRAL_LINK_INVALID_TEXT",
    "این یک لینک معتبر نیست. لطفاً یک آدرس که با http:// یا https:// شروع می‌شود ارسال کنید.",
)

REFERRAL_LINK_SAVED_TEXT = _env_text("REFERRAL_LINK_SAVED_TEXT", "لینک رفرال شما با موفقیت ثبت شد ✅")

# --- Blockchain explorer: network picker + result text ---------------------------

EXPLORER_ASK_NETWORK_TEXT = _env_text(
    "EXPLORER_ASK_NETWORK_TEXT", "شبکه‌ی بلاکچینی تراکنش موردنظرتون رو انتخاب کنید:"
)

EXPLORER_NETWORK_BEP20_LABEL = _env_text("EXPLORER_NETWORK_BEP20_LABEL", "BEP20 (BNB Smart Chain)")
EXPLORER_NETWORK_TRC20_LABEL = _env_text("EXPLORER_NETWORK_TRC20_LABEL", "TRC20 (Tron)")
EXPLORER_NETWORK_ERC20_LABEL = _env_text("EXPLORER_NETWORK_ERC20_LABEL", "ERC20 (Ethereum)")
EXPLORER_NETWORK_BTC_LABEL = _env_text("EXPLORER_NETWORK_BTC_LABEL", "BTC (Bitcoin)")
EXPLORER_NETWORK_SOL_LABEL = _env_text("EXPLORER_NETWORK_SOL_LABEL", "SOL (Solana)")

EXPLORER_ASK_HASH_TEMPLATE = _env_text(
    "EXPLORER_ASK_HASH_TEMPLATE", "لطفاً هش تراکنش شبکه‌ی {network} رو ارسال کنید."
)

EXPLORER_NOT_FOUND_TEXT = _env_text("EXPLORER_NOT_FOUND_TEXT", "تراکنشی با این هش پیدا نشد.")

EXPLORER_ERROR_TEXT = _env_text(
    "EXPLORER_ERROR_TEXT", "در دریافت اطلاعات این تراکنش خطایی رخ داد. لطفاً دوباره تلاش کنید."
)

EXPLORER_RESULT_TEMPLATE = _env_text(
    "EXPLORER_RESULT_TEMPLATE",
    "🔗 *نتیجه استعلام تراکنش*\n"
    "\n"
    "📤 *آدرس مبدا:*\n`{source_address}`\n"
    "\n"
    "📥 *آدرس مقصد:*\n`{destination_address}`\n"
    "\n"
    "💰 *ارز:* {asset}\n"
    "🔢 *مقدار:* {amount}\n"
    "📅 *تاریخ:* {date}\n"
    "✅ *وضعیت:* {status}\n"
    "🌐 *شبکه:* {network}\n"
    "\n"
    "🔍 [مشاهده در بلاک‌اکسپلورر]({source})",
)

# --- Blockchain explorer: data sources (same providers as the reference n8n flow) --

# Moralis (BEP20 / BNB Smart Chain transactions) — header auth, key name "X-API-Key".
MORALIS_API_KEY = _env("MORALIS_API_KEY", "")
MORALIS_BEP20_TX_URL = _env(
    "MORALIS_BEP20_TX_URL", "https://deep-index.moralis.io/api/v2.2/transaction/{tx_hash}?chain=bsc"
)

# Etherscan v2 (ERC20 / Ethereum transactions) — query auth, key name "apikey".
ETHERSCAN_API_KEY = _env("ETHERSCAN_API_KEY", "")
ETHERSCAN_API_URL = _env("ETHERSCAN_API_URL", "https://api.etherscan.io/v2/api")

# mempool.space (BTC transactions) — public, no key needed.
MEMPOOL_SPACE_TX_URL = _env("MEMPOOL_SPACE_TX_URL", "https://mempool.space/api/tx/{tx_hash}")

# Solana public JSON-RPC (SOL transactions) — public, no key needed.
SOLANA_RPC_URL = _env("SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com")

# Tronscan (TRC20 / Tron transactions) — public, no key needed.
TRONSCAN_TX_URL = _env(
    "TRONSCAN_TX_URL", "https://apilist.tronscanapi.com/api/transaction-info?hash={tx_hash}"
)

EXPLORER_HTTP_TIMEOUT = float(_env("EXPLORER_HTTP_TIMEOUT", "20"))
# Matches the reference flow: ERC20/BTC/TRC20 retry up to 5 times, 5s apart;
# BEP20/SOL do not retry (a single failed attempt is reported as an error).
EXPLORER_HTTP_MAX_TRIES = int(_env("EXPLORER_HTTP_MAX_TRIES", "5"))
EXPLORER_HTTP_RETRY_WAIT_SECONDS = float(_env("EXPLORER_HTTP_RETRY_WAIT_SECONDS", "5"))


# --- Local persistence ---------------------------------------------------------

# Directory that holds the JSON-backed tables (per-group referral links, and
# the short-lived "waiting for a referral link" state).
DATA_DIR = _env(
    "DATA_DIR",
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data"),
)


# --- Price lookup (Nobitex / BitPin / Geevex) -----------------------------------
# This feature only ever *reads* market prices from public, keyless APIs.

NOBITEX_ORDERBOOK_URL = _env("NOBITEX_ORDERBOOK_URL", "https://apiv2.nobitex.ir/v3/orderbook/all")
BITPIN_TICKERS_URL = _env("BITPIN_TICKERS_URL", "https://api.bitpin.org/api/v1/mkt/tickers/")
GEEVEX_PRICE_API_URL = _env("GEEVEX_PRICE_API_URL", "https://api.ipharkat.ir/api/coins/")

# Per-request timeout for each of the three price sources.
PRICE_HTTP_TIMEOUT = float(_env("PRICE_HTTP_TIMEOUT", "6"))

# How long a fetched price snapshot is reused before hitting the API again.
# Every request for the same source shares one cached snapshot (the source
# endpoints return *all* coins at once), so this also caps how often groups
# with heavy traffic can trigger outbound API calls.
PRICE_CACHE_TTL_SECONDS = float(_env("PRICE_CACHE_TTL_SECONDS", "8"))


# --- Run-mode safety guard -------------------------------------------------------
# app.py (webhook, served by Passenger in production) and poller.py (long-polling)
# are mutually exclusive: poller.py calls deleteWebhook on startup, which breaks
# the production webhook if both ever end up running at the same time (e.g. a
# stray cron job or leftover background process on the production host).
# poller.py refuses to start unless this is explicitly enabled — it must stay
# "false" on any host where app.py/passenger_wsgi.py is the live deployment, and
# is only meant to be turned on for local/dev runs without a public HTTPS endpoint.
ALLOW_POLLING = _env("ALLOW_POLLING", "false").strip().lower() in ("1", "true", "yes", "on")


# --- Group chat price replies ----------------------------------------------------

# When enabled, the bot scans group/supergroup text messages for a recognizable
# coin name and replies (as a reply-to) with a compact price snapshot.
GROUP_PRICE_ENABLED = _env("GROUP_PRICE_ENABLED", "true").strip().lower() in ("1", "true", "yes", "on")


# --- HTTP server ---------------------------------------------------------------

HOST = _env("HOST", "0.0.0.0")
PORT = int(_env("PORT", "5000"))
WEBHOOK_PATH = _env("WEBHOOK_PATH", "/telegram")

# Outgoing-request retry policy (mirrors the original 5 tries / 5s spacing).
HTTP_MAX_TRIES = int(_env("HTTP_MAX_TRIES", "5"))
HTTP_RETRY_WAIT_SECONDS = float(_env("HTTP_RETRY_WAIT_SECONDS", "5"))
