import tempfile
import unittest
from pathlib import Path
from unittest import mock

import server


PROJECT = {
    "id": 99,
    "domain_url": "https://audit-example.test",
    "hostname": "audit-example.test",
    "slug": "audit-example-test",
    "seo_title": "GAN89 | Audit Landing Page",
    "meta_description": "Audit landing page GAN89 yang lengkap.",
    "keywords": "GAN89, GAN89 Login",
    "hero_heading": "GAN89 | Audit Landing Page",
    "hero_subheading": "Audit landing page GAN89 yang lengkap.",
    "article_body": "Panduan GAN89\nIsi landing page yang telah diperiksa.",
    "cta_label": "Login GAN89",
    "cta_url": "https://audit-example.test",
    "amp_url": "https://amp.audit-example.test/",
    "alternate_links": "id|https://audit-example.test/",
    "generate_faq": 1,
    "generate_reviews": 1,
    "logo_media_id": 1,
    "icon_media_id": 2,
    "main_media_id": 3,
    "last_template_key": "",
    "last_amp_template_key": "",
}

MEDIA_ROW = {"id": 1, "file_path": "selected.png", "content_type": "image/png"}


def page_markup(media_prefix: str, old_brand: str = "") -> str:
    visible_brand = old_brand or "GAN89"
    return f"""<!doctype html>
    <html><head>
      <title>GAN89 | Audit Landing Page</title>
      <meta name="description" content="Audit landing page GAN89 yang lengkap.">
      <meta property="og:title" content="GAN89 | Audit Landing Page">
      <link rel="canonical" href="https://audit-example.test/">
      <link rel="amphtml" href="https://amp.audit-example.test/">
      <link rel="alternate" hreflang="id" href="https://audit-example.test/">
    </head><body>
      <header><h1>GAN89 | Audit Landing Page</h1></header>
      <main>
        <p>{visible_brand} menyediakan informasi yang telah diperiksa.</p>
        <img src="{media_prefix}logo.png" alt="Logo GAN89">
        <img src="{media_prefix}icon.png" alt="Icon GAN89">
        <img src="{media_prefix}main.png" alt="Gambar utama GAN89">
        <section class="faq-section"><h2>FAQ GAN89</h2><details><summary>Pertanyaan?</summary><p>Jawaban.</p></details></section>
        <section class="member-reviews"><h2>Review GAN89</h2><blockquote>Review pengguna.</blockquote></section>
      </main>
      <footer><p>GAN89</p></footer>
    </body></html>"""


class FinishingAuditTests(unittest.TestCase):
    def build_output(self, root: Path, old_brand: str = "") -> None:
        folder = root / PROJECT["slug"]
        media = folder / "adminseo-media"
        amp = folder / "amp"
        media.mkdir(parents=True)
        amp.mkdir()
        for role in ("logo", "icon", "main"):
            (media / f"{role}.png").write_bytes(b"image")
        (folder / "index.html").write_text(page_markup("adminseo-media/", old_brand), encoding="utf-8")
        (amp / "index.html").write_text(page_markup("../adminseo-media/", old_brand), encoding="utf-8")
        (folder / "sitemap.xml").write_text("<urlset></urlset>", encoding="utf-8")
        (folder / "robots.txt").write_text("User-agent: *", encoding="utf-8")

    def test_complete_output_passes_finishing_audit(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            root = Path(temp_dir)
            self.build_output(root)
            with (
                mock.patch.object(server, "GENERATED_DIR", root),
                mock.patch.object(server, "media_record", return_value=MEDIA_ROW),
                mock.patch.object(server, "validate_amp_file", return_value={"status": "PASS", "available": True, "errors": []}),
            ):
                report = server.analyze_generated_project(PROJECT)

        self.assertEqual("pass", report["status"])
        self.assertEqual(0, report["failed_count"])

    def test_source_brand_is_reported_before_approval(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            root = Path(temp_dir)
            self.build_output(root, "OLDCO")
            with (
                mock.patch.object(server, "GENERATED_DIR", root),
                mock.patch.object(server, "media_record", return_value=MEDIA_ROW),
                mock.patch.object(server, "generated_source_legacy_brands", return_value=["OLDCO"]),
                mock.patch.object(server, "validate_amp_file", return_value={"status": "PASS", "available": True, "errors": []}),
            ):
                report = server.analyze_generated_project(PROJECT)

        failed_keys = {item["key"] for item in report["checks"] if item["status"] == "fail"}
        self.assertEqual("fail", report["status"])
        self.assertIn("brand_visible", failed_keys)
        self.assertIn("template_cleanup", failed_keys)


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