"""JRA公式 HTML 取得（Shift_JIS）"""
from __future__ import annotations

import time
from typing import TYPE_CHECKING

import requests

if TYPE_CHECKING:
    pass

from config import REQUEST_HEADERS, REQUEST_INTERVAL, REQUEST_TIMEOUT

JRA_BASE = "https://www.jra.go.jp"
LAST_FETCH = 0.0


def throttle() -> None:
    global LAST_FETCH
    now = time.monotonic()
    gap = REQUEST_INTERVAL - (now - LAST_FETCH)
    if gap > 0:
        time.sleep(gap)
    LAST_FETCH = time.monotonic()


def get_session() -> requests.Session:
    s = requests.Session()
    s.headers.update(dict(REQUEST_HEADERS))
    s.headers["Accept"] = "text/html"
    s.headers["Referer"] = "https://www.jra.go.jp/keiba/"
    return s


def fetch_access_s(session: requests.Session, cname_path: str) -> tuple[str | None, str]:
    """
    cname_path: pw01sde1004202103040120210801/DF（先頭に pw01sde が付いた CNAME 全体）
    requests の params だと末尾16進が欠ける事例があるため、クエリは手組みにする。
    """
    throttle()
    from urllib.parse import quote

    url = f"{JRA_BASE}/JRADB/accessS.html?CNAME={quote(cname_path, safe='')}"
    r = session.get(url, timeout=REQUEST_TIMEOUT)
    if r.status_code != 200:
        return None, f"http_{r.status_code}"
    raw = r.content
    for enc in ("shift_jis", "cp932", "utf-8"):
        try:
            return raw.decode(enc), "ok"
        except UnicodeDecodeError:
            continue
    return None, "encoding"
