# exchanges.py — supported stock exchanges
#
# SPDX-License-Identifier: GPL-3.0-or-later

from dataclasses import dataclass
from gettext import gettext as _


@dataclass(frozen=True)
class Exchange:
    id: str
    name: str
    short_name: str
    suffix: str          # Yahoo Finance ticker suffix
    currency: str
    timezone: str
    examples: str
    color: tuple         # RGB, used for allocation bar and legend
    listing_codes: frozenset  # Yahoo "exchangeName" codes accepted for this market


EXCHANGES = (
    Exchange(
        id="NYSE",
        name=_("New York Stock Exchange"),
        short_name="NYSE",
        suffix="",
        currency="USD",
        timezone="America/New_York",
        examples="KO, JPM, IBM, BRK-B",
        color=(0.208, 0.518, 0.894),   # Adwaita blue 3
        # NYQ = NYSE, PCX = NYSE Arca, ASE = NYSE American
        listing_codes=frozenset({"NYQ", "NYS", "NYSE", "PCX", "ASE"}),
    ),
    Exchange(
        id="STO",
        name=_("Nasdaq Stockholm"),
        short_name=_("Stockholm"),
        suffix=".ST",
        currency="SEK",
        timezone="Europe/Stockholm",
        examples="VOLV-B, ERIC-B, ATCO-A",
        color=(0.898, 0.647, 0.039),   # Adwaita yellow 5
        listing_codes=frozenset({"STO"}),
    ),
    Exchange(
        id="OSL",
        name=_("Oslo Børs"),
        short_name=_("Oslo"),
        suffix=".OL",
        currency="NOK",
        timezone="Europe/Oslo",
        examples="EQNR, DNB, NHY",
        color=(0.878, 0.106, 0.141),   # Adwaita red 3
        listing_codes=frozenset({"OSL"}),
    ),
)

_BY_ID = {e.id: e for e in EXCHANGES}

BASE_CURRENCIES = ("NOK", "SEK", "USD", "EUR")


def get_exchange(exchange_id):
    return _BY_ID[exchange_id]


def exchange_index(exchange_id):
    for i, e in enumerate(EXCHANGES):
        if e.id == exchange_id:
            return i
    return 0


def detect_exchange(text):
    """Return the exchange id implied by a typed Yahoo suffix (".ST", ".OL"), or None."""
    upper = text.strip().upper()
    for e in EXCHANGES:
        if e.suffix and upper.endswith(e.suffix):
            return e.id
    return None


def clean_ticker(text, exchange_id):
    """Normalise what the user typed into a bare ticker for the given exchange.

    "volv b" -> "VOLV-B", "eqnr.ol" -> "EQNR", " brk.b " -> "BRK-B".
    """
    e = get_exchange(exchange_id)
    s = text.strip().upper()
    if e.suffix and s.endswith(e.suffix):
        s = s[: -len(e.suffix)]
    s = "-".join(s.split())
    # Class shares: Yahoo uses a dash on every market (BRK-B, VOLV-B)
    if "." in s:
        s = s.replace(".", "-")
    return s


def to_yahoo_symbol(text, exchange_id):
    ticker = clean_ticker(text, exchange_id)
    if not ticker:
        return ""
    return ticker + get_exchange(exchange_id).suffix


def display_symbol(yahoo_symbol, exchange_id):
    suffix = get_exchange(exchange_id).suffix
    if suffix and yahoo_symbol.endswith(suffix):
        return yahoo_symbol[: -len(suffix)]
    return yahoo_symbol


def listing_problem(quote, exchange_id):
    """Return a user-facing message if the quote is not listed on the chosen exchange."""
    e = get_exchange(exchange_id)
    code = (quote.exchange_code or "").upper()
    if not code or code in e.listing_codes:
        return None
    where = quote.exchange_name or code
    return _("{symbol} is listed on {market}, not {exchange}").format(
        symbol=display_symbol(quote.symbol, exchange_id), market=where, exchange=e.name)
