import unittest
import re

import server


PROJECT = {
    "id": 0,
    "domain_url": "https://contoh-gan89.test",
    "hostname": "contoh-gan89.test",
    "seo_title": "GAN89 | Panduan Contoh yang Lengkap",
    "meta_description": "GAN89 menghadirkan panduan baru yang disusun khusus untuk domain contoh.",
    "keywords": "GAN89, GAN89 Login, GAN89 Daftar, Contoh",
    "hero_heading": "GAN89 | Panduan Contoh yang Lengkap",
    "hero_subheading": "Informasi GAN89 yang bersih, relevan, dan berbeda untuk setiap domain.",
    "article_body": "Arah Utama GAN89\nKonten baru disusun berdasarkan identitas GAN89 dan kebutuhan pengunjung domain.\n\nPilihan yang Tepat\nSetiap bagian memakai canonical, anchor, gambar, serta copy milik proyek.",
    "cta_label": "Login GAN89",
    "cta_url": "https://contoh-gan89.test",
    "amp_url": "https://amp.contoh-gan89.test/",
    "alternate_links": "id|https://contoh-gan89.test/",
    "generate_faq": 1,
    "generate_reviews": 1,
    "audit_before_save": 1,
}


class TemplateSanitizerTests(unittest.TestCase):
    def assert_template_clean(self, key, metadata):
        path = server.Path(metadata["path"])
        source = (path / "index.html").read_text(encoding="utf-8", errors="ignore")
        legacy_brands = server.template_legacy_brands(source, server.project_brand(PROJECT))
        media_paths = server.project_default_media_urls(PROJECT)
        result = server.inject_project_content(source, PROJECT, key, media_paths, legacy_brands)
        issues = server.audit_landing_content(result, PROJECT, False, legacy_brands, media_paths)
        self.assertEqual([], issues, f"{key}: {issues}")
        self.assertNotIn("adminseo-article", result.lower(), key)
        visible_text = server.visible_document_text(result)
        for legacy_brand in legacy_brands:
            self.assertIsNone(re.search(re.escape(legacy_brand), visible_text, flags=re.I), f"{key}: {legacy_brand}")

        footer_position = server.find_footer_start(result)
        if footer_position is not None:
            for section_name in ("adminseo-faq", "adminseo-reviews"):
                section_match = re.search(rf'class=["\'][^"\']*\b{section_name}\b', result, flags=re.I)
                if section_match:
                    self.assertLess(section_match.start(), footer_position, f"{key}: {section_name} after footer")

    def test_all_template89_templates_are_clean(self):
        for key, path in server.discover_template89().items():
            with self.subTest(template=key):
                self.assert_template_clean(key, path)

    def test_all_ampall_templates_are_clean(self):
        for key, path in server.discover_ampall().items():
            with self.subTest(template=key):
                self.assert_template_clean(key, path)

    def test_existing_faq_and_reviews_are_reused_in_place(self):
        source = """
        <html><head><title>OLDCO</title></head><body>
          <main><h1>OLDCO Landing Page</h1><p>Old content.</p>
            <section class="faq-section"><h2>OLDCO FAQ</h2>
              <details><summary>Old question?</summary><p>Old answer.</p></details>
            </section>
            <section data-testid="member-reviews"><h2>OLDCO Reviews</h2>
              <blockquote>Old review.</blockquote><p>Old reviewer.</p>
            </section>
          </main>
          <div class="default_footer" role="contentinfo"><p>OLDCO copyright</p></div>
        </body></html>
        """
        result = server.inject_project_content(
            source,
            PROJECT,
            "existing-sections",
            server.project_default_media_urls(PROJECT),
            ["OLDCO"],
        )

        self.assertNotIn("OLDCO", server.visible_document_text(result))
        self.assertNotIn("adminseo-faq\"", result)
        self.assertNotIn("adminseo-reviews\"", result)
        self.assertIn("FAQ GAN89", result)
        self.assertIn("Review Pengguna GAN89", result)
        self.assertNotIn("adminseo-article", result)

    def test_missing_faq_and_reviews_are_added_before_footer(self):
        source = """
        <html><head><title>OLDCO</title></head><body>
          <main><h1>OLDCO Landing Page</h1><p>Old content.</p></main>
          <footer><p>OLDCO copyright</p></footer>
        </body></html>
        """
        result = server.inject_project_content(
            source,
            PROJECT,
            "missing-sections",
            server.project_default_media_urls(PROJECT),
            ["OLDCO"],
        )

        footer_position = server.find_footer_start(result)
        self.assertIsNotNone(footer_position)
        self.assertLess(result.index('class="adminseo-faq"'), footer_position)
        self.assertLess(result.index('class="adminseo-reviews"'), footer_position)
        self.assertEqual(5, result.count('class="adminseo-faq-item"'))
        self.assertEqual(5, result.count('class="adminseo-review-card"'))
        self.assertNotIn("adminseo-article", result)


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