"""Heathrow Airport's own site (www.heathrow.com): the World Duty Free page under Shops A-Z.

Server-rendered (11 Sep 2026): one page lists every World Duty Free store at the airport, a
section per terminal (`data-terminal-details-identifier="id-<terminal>-..."`), and inside it one
`hrl-terminal-detail-wrapper` per store with its area (`hrl-area-info`: Departures, Gate B35,
Baggage Reclaim Hall) and its clock (`hrl-store-timing`: "Mo-Su 05:30-22:00"). Fourteen stores
across four terminals on the day it was read. robots.txt permits the path; no Crawl-delay.
A store whose clock is missing is skipped, never guessed.
"""

import re

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

_SECTION = re.compile(r'data-terminal-details-identifier="id-(\w+)-\d+"')
_H1 = re.compile(r"<h1[^>]*>(.*?)</h1>", re.S)
_AREA = re.compile(r'<span class="hrl-area-info[^"]*">(.*?)</span>', re.S)
_TIMING = re.compile(r'<span class="hrl-store-timing[^"]*">(.*?)</span>', re.S)


class HeathrowHours:
    slug = "heathrow-hours"
    operator = "Heathrow Airport"
    homepage = "https://www.heathrow.com"
    airports = ("LHR",)
    parser_version = "heathrow-hours-1"
    delay_seconds = 0.0

    def pages(self, iata: str) -> list[str]:
        return [f"{self.homepage}/at-the-airport/shops-a-z/world-duty-free"]

    def follow(self, body: str, url: str) -> list[str]:
        return []

    def parse(self, body: str, url: str) -> list[StoreHours]:
        heading = _H1.search(body)
        name = text_of(heading.group(1)) if heading else None
        stores: list[StoreHours] = []
        marks = list(_SECTION.finditer(body))
        for i, mark in enumerate(marks):
            end = marks[i + 1].start() if i + 1 < len(marks) else len(body)
            section = body[mark.end():end]
            terminal = f"T{mark.group(1).upper()}"
            for wrapper in section.split("hrl-terminal-detail-wrapper")[1:]:
                timing = _TIMING.search(wrapper)
                if not timing:
                    continue
                times, days, statement = parse_timing(timing.group(1))
                if not times and not statement:
                    continue
                area = _AREA.search(wrapper)
                stores.append(StoreHours(
                    terminal=terminal,
                    area=text_of(area.group(1)) if area else None,
                    times=times,
                    days=days,
                    statement=statement,
                    name=name,
                ))
        return stores
