"""Toronto Pearson's own site (www.torontopearson.com): the duty free store pages.

The site's English sitemap (named in its robots.txt, which permits it) lists every store page;
the duty free ones are the `duty-free-*` pages under `/en/while-you-are-here/toronto-airport-shops/`
(an `archived-` page is a closed store and is skipped). Each store page is server-rendered
(11 Sep 2026) with a `location-info` list: where it is ("Terminal 1 - After security
(International) - Near Gate E76") and, under the clock icon, its hours as a rule rather than a
clock: "Open 3 hours before flights. Closed with gaps of more than 3 hours between flights."
One run reads the sitemap and each duty free store page, under the shared page cap.
"""

import re

from app.services.hours.base import StoreHours, parse_timing, terminal_label, text_of

_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
_STORE_PATH = re.compile(r"/en/while-you-are-here/toronto-airport-shops/duty-free-[a-z0-9-]+$")
_H1 = re.compile(r"<h1[^>]*>(.*?)</h1>", re.S)
_WHERE = re.compile(r'<span class="location-info__location-item">(.*?)</span>', re.S)
# The whole item: its content once began with an empty <div>, and a capture that stopped at
# the first closing div read eight of eleven store pages as having no hours (run of 11 Sep).
_TIME_ITEM = re.compile(r'<li\b[^>]*location-info__item--time[^>]*>(.*?)</li>', re.S)
_SPLIT = re.compile(r"\s*(?:—|–|-)\s*")


class TorontoPearsonHours:
    slug = "toronto-pearson-hours"
    operator = "Toronto Pearson (GTAA)"
    homepage = "https://www.torontopearson.com"
    airports = ("YYZ",)
    parser_version = "toronto-hours-1"
    # A second read of the store pages five minutes after the first met a Radware captcha
    # (11 Sep): eleven pages a run, so the pace is a slow human's, not a crawler's.
    delay_seconds = 10.0

    def pages(self, iata: str) -> list[str]:
        return [f"{self.homepage}/sitemap_yyz_en.xml"]

    def follow(self, body: str, url: str) -> list[str]:
        if not url.endswith(".xml"):
            return []
        return sorted({
            loc for loc in _LOC.findall(body)
            if _STORE_PATH.search(loc) and "/archived-" not in loc
        })

    def parse(self, body: str, url: str) -> list[StoreHours]:
        if url.endswith(".xml"):
            return []
        time_item = _TIME_ITEM.search(body)
        if not time_item:
            return []
        times, days, statement = parse_timing(time_item.group(1))
        if not times and not statement:
            return []
        name = next((text_of(h) for h in _H1.findall(body) if text_of(h).lower() != "search"), None)
        terminal = area = None
        where = _WHERE.search(body)
        if where:
            parts = [p for p in _SPLIT.split(text_of(where.group(1))) if p]
            if parts:
                terminal = terminal_label(parts[0])
                area = ", ".join(parts[1:]) or None
        return [StoreHours(terminal=terminal, area=area, times=times, days=days, statement=statement, name=name)]
