#!/usr/bin/env python3
"""Acceptance contract for the first paid Cosmos Luminosity offer."""
from __future__ import annotations

import json
import re
import unittest
from pathlib import Path

from bs4 import BeautifulSoup

ROOT = Path(__file__).resolve().parents[1]
LEGAL_ROUTES = ("terms", "refund-policy")
ALL_NEW_ROUTES = ("webinar", *LEGAL_ROUTES)
SELLER = "Being In Future LLC"
SUPPORT = "info@cosmosluminosity.com"


class CommerceReleaseTests(unittest.TestCase):
    def source(self, name: str) -> str:
        return (ROOT / name).read_text(encoding="utf-8")

    def test_routes_define_ru_and_en_offer_and_legal_pages(self) -> None:
        routes = self.source("routes.yaml")
        for route in ALL_NEW_ROUTES:
            with self.subTest(route=route):
                self.assertIn(f"  /{route}/:\n    template: page-{route}", routes)
                self.assertIn(f"  /en/{route}/:\n    template: page-{route}-en", routes)

    def test_webinar_offer_is_specific_and_not_fake_checkout(self) -> None:
        source = self.source("page-webinar.hbs")
        text = BeautifulSoup(source, "html.parser").get_text(" ", strip=True)
        for value in ("$77 USD", "90", "30", SELLER, SUPPORT):
            with self.subTest(value=value):
                self.assertIn(value, text)
        self.assertRegex(source, r'href="mailto:info@cosmosluminosity\.com[^\"]*"')
        self.assertNotRegex(source, r'href="(?:#|javascript:|https?://(?:checkout|buy)\.example)')
        self.assertIn("application/ld+json", source)
        self.assertIn('"price":"77"', source)
        self.assertIn('"priceCurrency":"USD"', source)

    def test_legal_pages_name_seller_support_and_effective_date(self) -> None:
        for route in LEGAL_ROUTES:
            source = self.source(f"page-{route}.hbs")
            with self.subTest(route=route):
                self.assertIn(SELLER, source)
                self.assertIn(SUPPORT, source)
                self.assertIn("25 октября 2026", source)
                self.assertIn("Wyoming", source)

    def test_refund_matrix_covers_core_cases(self) -> None:
        source = self.source("page-refund-policy.hbs")
        for phrase in (
            "до начала вебинара",
            "не получал доступ",
            "отменён организатором",
            "обязательные права потребителя",
        ):
            self.assertIn(phrase, source)

    def test_footer_links_all_commerce_policies(self) -> None:
        layout = self.source("default.hbs")
        for href in ("/webinar/", "/terms/", "/refund-policy/"):
            self.assertIn(f'href="{href}"', layout)

    def test_generator_owns_english_variants(self) -> None:
        generator = self.source("tools/generate_english_templates.py")
        for route in ALL_NEW_ROUTES:
            self.assertIn(f'"path": "{route}/"', generator)
            self.assertIn(f'"target": "page-{route}-en.hbs"', generator)

    def test_no_sensitive_or_unverified_business_fields(self) -> None:
        combined = "\n".join(self.source(f"page-{r}.hbs") for r in ALL_NEW_ROUTES)
        self.assertNotRegex(combined, re.compile(r"\bEIN\b|registration number|registered agent", re.I))
        self.assertNotRegex(combined, re.compile(r"medical outcome|guaranteed result|лечит|гарантирован", re.I))

    def test_webinar_product_schema_is_valid_json_ld(self) -> None:
        for template in ("page-webinar.hbs", "page-webinar-en.hbs"):
            source = self.source(template)
            match = re.search(r'<script type="application/ld\+json">(.*?)</script>', source, re.S)
            self.assertIsNotNone(match, template)
            payload = json.loads(match.group(1))
            self.assertEqual(payload["@context"], "https://schema.org")
            self.assertEqual(payload["@type"], "Product")
            self.assertEqual(payload["offers"]["price"], "77")
            self.assertEqual(payload["offers"]["priceCurrency"], "USD")

    def test_generated_english_commerce_copy_has_no_cyrillic(self) -> None:
        for route in ALL_NEW_ROUTES:
            template = f"page-{route}-en.hbs"
            visible_text = BeautifulSoup(self.source(template), "html.parser").get_text(" ", strip=True)
            with self.subTest(template=template):
                self.assertNotRegex(visible_text, r"[А-Яа-яЁё]")

    def test_magic_cloud_external_transition_is_explicit_in_both_languages(self) -> None:
        for template in ("page-magic-cloud.hbs", "page-magic-cloud-en.hbs"):
            source = self.source(template)
            with self.subTest(template=template):
                self.assertIn("Cosmic Oracle &amp; Ancient Wisdom", source)
                self.assertIn("руны, Mayan и другие символические системы; символы выбирает сервис", source)
                self.assertIn("runes, Mayan and other symbolic systems; the service selects the symbols", source)
                self.assertNotIn("систему выбираете вы", source)
                self.assertNotIn("you choose the system", source)
                self.assertIn("отдельный сайт Magic Cloud", source)
                self.assertIn("separate Magic Cloud website", source)
                self.assertIn("текст вашего вопроса", source)
                self.assertIn("the text of your question", source)
                self.assertIn("не указывайте конфиденциальные", source)
                self.assertIn("do not enter confidential", source)
                self.assertIn("не опубликованы отдельные ссылки", source)
                self.assertIn("does not publish separate links", source)
                self.assertIn('href="https://getmagic.cloud/about"', source)
                disclosure = source.index("Cosmic Oracle &amp; Ancient Wisdom")
                about_link = source.index('href="https://getmagic.cloud/about"')
                external_link = source.index('href="https://getmagic.cloud/"')
                self.assertLess(disclosure, about_link)
                self.assertLess(about_link, external_link)
                self.assertIn('target="_blank" rel="noopener noreferrer"', source)


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