#!/usr/bin/env python3
"""Test the production title conversion against the actual template positions.

Requires runghc and the site's Utils dependencies. Extract the titlePlainField
return expression so that a reverted escaping fix fails the rendering fixtures.
Hakyll's escapeHtml is exactly Blaze's renderHtml . toHtml; importing those two
functions avoids loading the whole site compiler for this focused regression.
See https://github.com/jaspervdj/hakyll/blob/master/lib/Hakyll/Web/Html.hs.
"""

from html.parser import HTMLParser
import json
from pathlib import Path
import re
import subprocess
import tempfile
import unittest


ROOT = Path(__file__).resolve().parents[2]


class Capture(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.tags = []
        self.text = []

    def handle_starttag(self, tag, attrs):
        self.tags.append((tag, attrs))

    def handle_data(self, data):
        self.text.append(data)


class TemplateTitleTest(unittest.TestCase):
    def test_title_and_markdown_link_roundtrip_special_characters(self):
        lines = [line.strip() for line in (ROOT / 'template/default.html').read_text().splitlines()
                 if '<title>' in line or 'type="text/markdown"' in line]
        self.assertEqual(len(lines), 3)
        source = (ROOT / 'build/app/hakyll.hs').read_text()
        field = source.split('titlePlainField ::', 1)[1].split('\nprogressField ::', 1)[0]
        expression = re.search(r'Just t -> return \((.+)\)', field)[1]
        program = '''module Main where
import Utils (simplifiedHTMLString)
import Text.Blaze.Html (toHtml)
import Text.Blaze.Html.Renderer.String (renderHtml)
import Data.Aeson (encode)
import qualified Data.ByteString.Lazy.Char8 as B
escapeHtml :: String -> String
escapeHtml = renderHtml . toHtml
renderTitle :: String -> String
renderTitle t = ''' + expression + '''
main :: IO ()
main = mapM_ (B.putStrLn . encode . renderTitle)
  [ "Conferences As D&amp;D Tabletops"
  , "<code>A \\"quoted\\" title</code> &amp; &lt;literal&gt;"
  , "<code>plain code</code> &amp; <em>plain emphasis</em>"
  ]
'''
        with tempfile.TemporaryDirectory() as directory:
            fixture = Path(directory) / 'TitleFixture.hs'
            fixture.write_text(program)
            result = subprocess.run(['runghc', '-i' + str(ROOT / 'build'), str(fixture)],
                                    check=True, text=True, capture_output=True)
        rendered_titles = [json.loads(line) for line in result.stdout.splitlines()]
        plain_titles = ['Conferences As D&D Tabletops', 'A “quoted” title & <literal>',
                        'plain code & plain emphasis']
        for title, rendered_title in zip(plain_titles, rendered_titles, strict=True):
            context = {"title-plain": rendered_title,
                       "author-escaped": "Gwern", "url": "/blog/2025/conference"}
            for line in lines:
                with self.subTest(title=title, line=line):
                    rendered = re.sub(r"\$([\w-]+)\$", lambda m: context[m[1]], line)
                    parsed = Capture()
                    parsed.feed(rendered)
                    if '<link ' in line:
                        attrs = dict(parsed.tags[0][1])
                        self.assertEqual(attrs["title"], f"Markdown source of ‘{title}’ page")
                        self.assertEqual(len(attrs), 4)
                    else:
                        self.assertEqual(parsed.tags, [("title", [])])
                        self.assertIn(title, ''.join(parsed.text))
                    self.assertNotIn('&D', rendered)


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