import re


class CookieConverter:
    """
    Converts Amazon session cookies between regional variants.

    Amazon uses region-specific suffixes in cookie names (e.g. -acbmx, -main, -acbca)
    and values (currency, locale). This converter rewrites those markers so a session
    obtained from one storefront can be used on another.

    Supported: MX ↔ US, MX ↔ CA, US ↔ CA
    """

    REGIONS = {
        'US': {'suffix': 'main',  'currency': 'USD', 'locale': 'en_US', 'domain': 'amazon.com'},
        'CA': {'suffix': 'acbca', 'currency': 'CAD', 'locale': 'en_CA', 'domain': 'amazon.ca'},
        'MX': {'suffix': 'acbmx', 'currency': 'MXN', 'locale': 'es_MX', 'domain': 'amazon.com.mx'},
        'UK': {'suffix': 'acbuk', 'currency': 'GBP', 'locale': 'en_GB', 'domain': 'amazon.co.uk'},
        'FR': {'suffix': 'acbfr', 'currency': 'EUR', 'locale': 'fr_FR', 'domain': 'amazon.fr'},
        'IT': {'suffix': 'acbit', 'currency': 'EUR', 'locale': 'it_IT', 'domain': 'amazon.it'},
        'ES': {'suffix': 'acbes', 'currency': 'EUR', 'locale': 'es_ES', 'domain': 'amazon.es'},
        'AU': {'suffix': 'acbau', 'currency': 'AUD', 'locale': 'en_AU', 'domain': 'amazon.com.au'},
    }

    # ── All known suffixes for detection ─────────────────────────────
    _ALL_SUFFIXES = {v['suffix'] for v in REGIONS.values()}

    @classmethod
    def detect_region(cls, cookie_text: str) -> str | None:
        """Detect the region of a cookie string based on suffix patterns."""
        for code, cfg in cls.REGIONS.items():
            if f"-{cfg['suffix']}" in cookie_text:
                return code
        return None

    @classmethod
    def convert(cls, cookie_text: str, target_region: str) -> str:
        """
        Convert cookie_text to the target region.

        If the cookie is already in the target region, returns it unchanged.
        Auto-detects source region from the cookie content.
        """
        target_region = target_region.upper()
        if target_region not in cls.REGIONS:
            return cookie_text

        source = cls.detect_region(cookie_text)
        if not source or source == target_region:
            return cookie_text

        src = cls.REGIONS[source]
        dst = cls.REGIONS[target_region]

        out = cookie_text

        # ── Replace region suffix in cookie names (e.g. at-acbmx → at-main) ─
        out = re.sub(
            rf'-{re.escape(src["suffix"])}\b',
            f'-{dst["suffix"]}',
            out,
        )

        # ── Replace standalone suffix occurrences ────────────────────
        out = re.sub(
            rf'\b{re.escape(src["suffix"])}\b',
            dst['suffix'],
            out,
        )

        # ── Replace currency (i18n-prefs=MXN → i18n-prefs=USD) ──────
        out = re.sub(
            rf'(i18n-prefs=){re.escape(src["currency"])}',
            rf'\1{dst["currency"]}',
            out,
        )

        # ── Replace locale (es_MX → en_US) ───────────────────────────
        out = re.sub(
            re.escape(src['locale']),
            dst['locale'],
            out,
        )

        return out

    @classmethod
    def convert_all(cls, cookie_text: str) -> dict[str, str]:
        """
        Convert a cookie string to all supported regions.

        Returns a dict with all supported regions converted.
        The source region entry will be the original cookie unchanged.
        """
        return {code: cls.convert(cookie_text, code) for code in cls.REGIONS}