"""Utility helpers used across the Smart Card Benefit Recommender app."""

from __future__ import annotations

from datetime import date, datetime
from typing import Any


def format_currency(amount: float | int | None, show_zero: bool = True) -> str:
    """Format a number as Indian Rupees using Indian digit grouping.

    Examples:
        5000 -> ₹5,000
        125000 -> ₹1,25,000

    The helper is intentionally simple so it can be explained in a viva as
    string formatting rather than a finance library dependency.
    """
    if amount is None:
        return "₹0" if show_zero else "-"

    try:
        numeric_amount = float(amount)
    except (TypeError, ValueError):
        return "₹0" if show_zero else "-"

    sign = "-" if numeric_amount < 0 else ""
    numeric_amount = abs(numeric_amount)

    if numeric_amount == int(numeric_amount):
        whole_part = str(int(numeric_amount))
        decimal_part = ""
    else:
        whole_part, decimal_part = f"{numeric_amount:.2f}".split(".")
        decimal_part = f".{decimal_part}"

    if len(whole_part) > 3:
        last_three = whole_part[-3:]
        leading_digits = whole_part[:-3]
        grouped_leading = []

        while len(leading_digits) > 2:
            grouped_leading.insert(0, leading_digits[-2:])
            leading_digits = leading_digits[:-2]

        if leading_digits:
            grouped_leading.insert(0, leading_digits)

        formatted_whole = ",".join(grouped_leading + [last_three])
    else:
        formatted_whole = whole_part

    return f"{sign}₹{formatted_whole}{decimal_part}"


def format_percentage(rate: float | int | None) -> str:
    """Display reward rates without noisy trailing zeros."""
    if rate is None:
        return "0%"

    value = float(rate)
    if value == int(value):
        return f"{int(value)}%"
    return f"{value:.2f}%"


def clean_text(value: Any) -> str:
    """Normalize text fields before saving them to SQLite."""
    return str(value or "").strip()


def today_iso() -> str:
    """Return today's date in ISO format for database defaults."""
    return date.today().isoformat()


def parse_iso_date(value: str | date | datetime | None) -> date | None:
    """Convert supported date values into a date object."""
    if value is None:
        return None
    if isinstance(value, datetime):
        return value.date()
    if isinstance(value, date):
        return value
    try:
        return datetime.strptime(str(value), "%Y-%m-%d").date()
    except ValueError:
        return None


def get_custom_css() -> str:
    """Central place for the Streamlit visual polish."""
    return """
    <style>
        :root {
            --primary: #2563eb;
            --secondary: #6d28d9;
            --ink: #0f172a;
            --muted: #64748b;
            --panel: #ffffff;
            --line: #e2e8f0;
            --soft: #f8fafc;
        }

        .main .block-container {
            padding-top: 1.8rem;
            padding-bottom: 3rem;
            max-width: 1180px;
        }

        h1, h2, h3 {
            color: var(--ink);
            letter-spacing: 0;
        }

        div[data-testid="stMetric"] {
            background: var(--panel);
            border: 1px solid var(--line);
            border-radius: 8px;
            padding: 1rem;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.04);
        }

        div[data-testid="stMetric"] label {
            color: var(--muted);
        }

        .app-header {
            background: linear-gradient(135deg, #eff6ff 0%, #f5f3ff 100%);
            border: 1px solid #dbeafe;
            border-radius: 8px;
            padding: 1.4rem 1.5rem;
            margin-bottom: 1rem;
        }

        .app-header h1 {
            margin: 0;
            font-size: 2rem;
            line-height: 1.15;
        }

        .app-header p {
            color: var(--muted);
            margin: 0.35rem 0 0;
            font-size: 1rem;
        }

        .soft-panel {
            background: var(--panel);
            border: 1px solid var(--line);
            border-radius: 8px;
            padding: 1rem;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.04);
            margin-bottom: 1rem;
        }

        .recommendation-box {
            background: linear-gradient(135deg, #1d4ed8 0%, #7c3aed 100%);
            color: white;
            border-radius: 8px;
            padding: 1.5rem;
            margin: 1rem 0;
            box-shadow: 0 14px 32px rgba(37, 99, 235, 0.22);
        }

        .recommendation-box h2,
        .recommendation-box h3,
        .recommendation-box p {
            color: white;
            margin-top: 0;
        }

        .card-title {
            color: var(--ink);
            font-size: 1.15rem;
            font-weight: 700;
            margin-bottom: 0.15rem;
        }

        .card-subtitle {
            color: var(--muted);
            font-size: 0.9rem;
            margin-bottom: 0.8rem;
        }

        .pill {
            display: inline-block;
            background: #eef2ff;
            color: #3730a3;
            border: 1px solid #c7d2fe;
            border-radius: 999px;
            padding: 0.2rem 0.6rem;
            font-size: 0.82rem;
            margin: 0.1rem 0.1rem 0.1rem 0;
        }

        .empty-state {
            background: var(--soft);
            border: 1px dashed #cbd5e1;
            border-radius: 8px;
            color: var(--muted);
            padding: 1.4rem;
            text-align: center;
        }

        .stButton > button {
            border-radius: 8px;
            border: 1px solid #bfdbfe;
            font-weight: 600;
        }

        .stButton > button[kind="primary"] {
            background: #2563eb;
            border-color: #2563eb;
        }
    </style>
    """
