#!/usr/bin/env python3
"""Regression tests for the bilingual/no-JS production contract."""
from __future__ import annotations

import os
import re
import unittest
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen

from bs4 import BeautifulSoup

BASE_URL = os.environ.get("COSMOS_BASE_URL", "https://www.cosmosluminosity.com").rstrip("/")
ROOT = Path(__file__).resolve().parents[1]
ROUTES = (
    "",
    "magic-cloud/",
    "audioboosts/",
    "gateways/",
    "portal/",
    "cosmos-cacao/",
    "lumoside/",
    "privacy/",
    "contact/",
)
NEW_ROUTES = ("webinar/", "terms/", "refund-policy/")
ALL_ROUTES = (*ROUTES, *NEW_ROUTES)


def fetch(path: str) -> tuple[int, str]:
    request = Request(f"{BASE_URL}/{path}", headers={"User-Agent": "CosmosReleaseRegression/1.0"})
    try:
        with urlopen(request, timeout=20) as response:
            return response.status, response.read().decode("utf-8")
    except HTTPError as error:
        return error.code, error.read().decode("utf-8", errors="replace")


class BilingualReleaseTests(unittest.TestCase):
    def test_every_english_route_is_server_rendered_and_canonical(self) -> None:
        for route in ROUTES:
            with self.subTest(route=route or "/"):
                status, html = fetch(f"en/{route}")
                self.assertEqual(status, 200)
                soup = BeautifulSoup(html, "html.parser")
                self.assertEqual(soup.html.get("lang"), "en")
                self.assertEqual(soup.select_one('meta[property="og:locale"]')["content"], "en_US")
                canonical = soup.select_one('link[rel="canonical"]')
                self.assertIsNotNone(canonical)
                self.assertEqual(canonical["href"], f"{BASE_URL}/en/{route}")
                self.assertTrue(soup.select_one('link[rel="alternate"][hreflang="ru"]'))
                self.assertTrue(soup.select_one('link[rel="alternate"][hreflang="en"]'))
                self.assertFalse(re.search(r"[А-Яа-яЁё]", soup.select_one("h1").get_text(" ", strip=True)))

    def test_english_product_metadata_is_specific_without_javascript(self) -> None:
        status, html = fetch("en/magic-cloud/")
        self.assertEqual(status, 200)
        soup = BeautifulSoup(html, "html.parser")
        title = soup.title.get_text(" ", strip=True)
        description = soup.select_one('meta[name="description"]')["content"]
        self.assertIn("Magic Cloud", title)
        self.assertIn("symbolic", description.lower())
        self.assertNotEqual(description, "Cosmos Luminosity — practices for thinking, state and body that support living choice.")

    def test_source_defines_no_js_mobile_navigation_fallback(self) -> None:
        default = (ROOT / "default.hbs").read_text(encoding="utf-8")
        self.assertRegex(default, r"<noscript>[\s\S]*class=\"no-js-nav\"")
        self.assertRegex(default, r"<noscript>[\s\S]*\.menu-toggle\s*\{\s*display:none")
        self.assertRegex(default, r"<noscript>[\s\S]*href=\"/magic-cloud/\"")

    def test_routes_config_defines_all_english_routes(self) -> None:
        routes = (ROOT / "routes.yaml").read_text(encoding="utf-8")
        for route in ROUTES:
            key = f"/en/{route}:"
            with self.subTest(route=key):
                self.assertIn(key, routes)
        self.assertRegex(routes, r"(?m)^  /en/:\n    template: index-en$")
        self.assertNotRegex(routes, r"(?m)^collections:[\s\S]*^  /en/:")

    def test_generated_english_templates_have_one_metadata_contract(self) -> None:
        for template in ("index-en.hbs", *(f"page-{route.rstrip('/')}-en.hbs" for route in ROUTES[1:])):
            with self.subTest(template=template):
                source = (ROOT / template).read_text(encoding="utf-8")
                for block in ("page_title", "page_description", "canonical_url", "ru_url", "en_url"):
                    self.assertEqual(source.count(f'contentFor "{block}"'), 1, f"duplicate {block}")
                metadata_values = " ".join(re.findall(r'\{\{#contentFor "[^"]+"\}\}(.*?)\{\{/contentFor\}\}', source))
                self.assertNotRegex(metadata_values, r"[А-Яа-яЁё]")

    def test_generated_english_no_js_navigation_is_localized(self) -> None:
        default = (ROOT / "default-en.hbs").read_text(encoding="utf-8")
        noscript = default.split("<noscript>", 1)[1].split("</noscript>", 1)[0]
        self.assertIn('aria-label="Mobile navigation"', noscript)
        self.assertIn('href="/en/magic-cloud/"', noscript)
        self.assertRegex(noscript, r'href="\{\{#block "ru_url"\}\}[^<]+>RU</a>')
        self.assertRegex(noscript, r'href="\{\{#block "en_url"\}\}[^<]+>EN</a>')

    def test_primary_home_navigation_anchors_exist_in_both_languages(self) -> None:
        pairs = (("default.hbs", "index.hbs", "/"), ("default-en.hbs", "index-en.hbs", "/en/"))
        for layout_name, index_name, root_path in pairs:
            layout = (ROOT / layout_name).read_text(encoding="utf-8")
            index = (ROOT / index_name).read_text(encoding="utf-8")
            anchors = re.findall(rf'href="{re.escape(root_path)}#([^"]+)"', layout)
            self.assertTrue(anchors, layout_name)
            for anchor in anchors:
                with self.subTest(layout=layout_name, anchor=anchor):
                    self.assertRegex(index, rf'\bid="{re.escape(anchor)}"')


if __name__ == "__main__":
    unittest.main(verbosity=2)
