import json
import subprocess
import tempfile
import unittest
from pathlib import Path

import server


PROJECT = {
    "id": 999,
    "domain_url": "https://valid-amp.example",
    "hostname": "valid-amp.example",
    "seo_title": "GAN89 | Landing Page Valid AMP",
    "meta_description": "Landing page GAN89 yang diperiksa menggunakan validator AMP resmi.",
    "hero_subheading": "Informasi yang jelas untuk pengguna Indonesia.",
    "article_body": "Bagian Utama\nKonten utama GAN89 yang relevan dan bersih.\n\nBagian Lanjutan\nInformasi tambahan untuk membantu pengguna.",
    "cta_label": "Login GAN89",
    "cta_url": "https://valid-amp.example/",
    "amp_url": "https://amp.valid-amp.example/",
    "alternate_links": "id|https://valid-amp.example/\nen|https://valid-amp.example/en/",
    "logo_media_id": None,
    "icon_media_id": None,
    "main_media_id": None,
}


class AmpValidationTests(unittest.TestCase):
    def test_invalid_html_fails_official_validator(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            path = Path(temp_dir) / "invalid.html"
            path.write_text("<!doctype html><html><body><img src='x.jpg'></body></html>", encoding="utf-8")
            result = server.validate_amp_file(path)

        self.assertEqual("FAIL", result["status"])

    def test_every_available_ampall_layout_stays_valid_after_replacement(self):
        media = {
            "logo": "../adminseo-media/logo.webp",
            "icon": "../adminseo-media/icon.png",
            "main": "../adminseo-media/main.webp",
        }
        templates = server.discover_ampall()
        with tempfile.TemporaryDirectory() as temp_dir:
            paths = []
            keys = []
            for index, (key, metadata) in enumerate(templates.items()):
                source = (Path(metadata["path"]) / "index.html").read_text(encoding="utf-8", errors="ignore")
                legacy = server.template_legacy_brands(source, server.project_brand(PROJECT))
                markup = server.inject_amp_project_content(source, PROJECT, key, media, legacy)
                self.assertNotRegex(markup, r'<link\b[^>]*rel=["\']alternate["\']')
                path = Path(temp_dir) / f"{index:03d}.html"
                path.write_text(markup, encoding="utf-8")
                paths.append(str(path))
                keys.append(key)

            completed = subprocess.run(
                [server.node_executable(), str(server.AMP_VALIDATOR_SCRIPT), *paths],
                cwd=server.BASE_DIR,
                capture_output=True,
                text=True,
                timeout=60,
                check=False,
            )
            validation = json.loads(completed.stdout)

        failed = [
            keys[index]
            for index, result in enumerate(validation["results"])
            if result["status"] != "PASS"
        ]
        self.assertTrue(templates)
        self.assertEqual([], failed)

    def test_ampall_visual_structure_is_preserved(self):
        key = "eb5texastriangle-faq.pages.dev"
        metadata = server.discover_ampall()[key]
        source = (Path(metadata["path"]) / "index.html").read_text(encoding="utf-8", errors="ignore")
        media = {
            "logo": "../adminseo-media/logo.webp",
            "icon": "../adminseo-media/icon.png",
            "main": "../adminseo-media/main.webp",
        }
        markup = server.inject_amp_project_content(
            source,
            PROJECT,
            key,
            media,
            server.template_legacy_brands(source, server.project_brand(PROJECT)),
        )

        self.assertIn('class="container"', markup)
        self.assertIn('class="btn-login"', markup)
        self.assertIn("background: #000000", markup)
        self.assertIn("../adminseo-media/main.webp", markup)
        self.assertNotIn("adminseo-faq", markup)
        self.assertNotIn("adminseo-reviews", markup)
        self.assertNotRegex(markup, r'<link\b[^>]*rel=["\']alternate["\']')
        self.assertNotIn("WAK89", server.visible_document_text(markup).upper())


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