import requests
import pandas as pd
import logging
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

logger = logging.getLogger(__name__)

def _create_session() -> requests.Session:
    session = requests.Session()
    retries = Retry(total=3, backoff_factor=0.5)
    adapter = HTTPAdapter(max_retries=retries)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

def fetch_jse_tickers(api_key: str) -> list[str]:
    logger.info("Fetching JSE tickers")
    session = _create_session()
    params = {"access_key": api_key, "limit": 350}

    response = session.get(
        "http://api.marketstack.com/v1/exchanges/XJSE/tickers",
        params=params,
        timeout=10,
    )
    response.raise_for_status()

    data = response.json()
    df = pd.json_normalize(data["data"]["tickers"])

    split = df["symbol"].str.split(".", expand=True)
    split.columns = ["base", "exchange"]
    split.replace("XJSE", "JO", inplace=True)

    tickers = split["base"] + "." + split["exchange"]
    return tickers.dropna().unique().tolist()
