{-# LANGUAGE OverloadedStrings #-}
module Main (main) where

import Control.Monad (forM_, unless)
import Data.Char (isSpace)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.Directory (doesFileExist)
import Text.Pandoc
import Text.Pandoc.Shared (stringify)
import Text.Pandoc.Walk (query)

import Typography (typesetHtmlFieldPermanent, typographyTransformTemporary)
import Utils (safeHtmlWriterOptions)

-- Run from static: ghc -package random -Wall -Werror -ibuild build/test/FigureCaptionTest.hs -e 'main'
-- Fixtures are the original GTX figures from arxiv.org/abs/2301.10309#google,
-- retrieved from metadata/half.gtx on 2026-12-03; no live requests are needed.
assert :: String -> Bool -> IO ()
assert label ok = unless ok $ error ("FAIL: " ++ label)

parseHTML, parseMarkdown :: T.Text -> Pandoc
parseHTML = either (error . show) id . runPure . readHtml def{readerExtensions=pandocExtensions}
parseMarkdown = either (error . show) id . runPure . readMarkdown def{readerExtensions=pandocExtensions}

render :: Pandoc -> T.Text
render = either (error . show) id . runPure . writeHtml5String safeHtmlWriterOptions

captions :: Pandoc -> [[Block]]
captions = query getCaption
  where getCaption (Figure _ (Caption _ blocks) _) = [blocks]
        getCaption _ = []

onlyCaption :: Pandoc -> [Block]
onlyCaption document = case captions document of
  [blocks] -> blocks
  _ -> error "Expected exactly one figure caption"

paragraph :: Block -> Bool
paragraph (Para _) = True
paragraph _ = False

-- Cite/date typography can normalize spaces independently of this rewrite.
normalized :: T.Text -> T.Text
normalized = T.unwords . T.words . T.map (\c -> if isSpace c then ' ' else c)

imageData :: Pandoc -> [(Attr, T.Text, Target)]
imageData = query getImage
  where getImage (Image attr alt target) = [(attr, normalized $ stringify alt, target)]
        getImage _ = []

linkData :: Pandoc -> [(T.Text, Target)]
linkData = query getLink
  where getLink (Link _ label target) = [(normalized $ stringify label, target)]
        getLink _ = []

fixture :: Int -> IO T.Text
fixture n = findFile ["build/test/fixtures/figure-captions/", "test/fixtures/figure-captions/",
                      "static/build/test/fixtures/figure-captions/"]
  where
    name = "pilault-figure-" ++ show n ++ ".html"
    findFile [] = error $ "Cannot locate test fixture " ++ name
    findFile (directory:rest) = do
      exists <- doesFileExist (directory ++ name)
      if exists then TIO.readFile (directory ++ name) else findFile rest

main :: IO ()
main = do
  let expected =
        [ ["Figure 1: Interactive-Chain-Prompting (INTERCPT)."]
        , ["Figure 2: Translation queries with multiple possible predictions.",
           "Correctly solving subproblems around ambiguities with “you” and “it” greatly affects the BLEU (Papineni et al 2002) translation metric."]
        , ["Figure 3: INTERCPT enables large LMs to solve ambiguity subproblems in cross-lingual generation.",
           "The multistep disambiguate-translate capability is an emergent ability that is reached at higher parameter scales. Note that interactive = INTERCPT."]
        ]
  forM_ (zip [1..3] expected) $ \(n, text) -> do
    html <- fixture n
    let source = parseHTML html
        output = T.pack $ typesetHtmlFieldPermanent True (T.unpack html)
        result = parseHTML output
        blocks = onlyCaption result
    assert ("GTX figure " ++ show n ++ " has the expected visible paragraphs") $
      map (normalized . stringify) blocks == text
    -- The unaffected one-line Figure 1 may retain a Plain caption.
    assert ("GTX figure " ++ show n ++ " writes real paragraphs for the split") $
      n == 1 || all paragraph blocks
    assert ("GTX figure " ++ show n ++ " preserves images and alternative text") $
      imageData result == imageData source
    assert ("GTX figure " ++ show n ++ " preserves links") $
      linkData result == linkData source
    assert ("GTX figure " ++ show n ++ " is idempotent through HTML serialization") $
      T.pack (typesetHtmlFieldPermanent True $ T.unpack output) == output

  let heading = [Strong [Str "Figure 4"], Str ": ", Emph [Str "A short summary."]]
      complete = heading ++ [Str " A longer explanation."]
      attribute = ("figure-id", ["float-right"], [("data-test", "kept")])
      alternative = [Strong [Str "Figure A"], Str ": ", Emph [Str "Alternative summary."], Str " Alternative detail."]
      body = [Plain [Image ("image-id", ["invert"], [("width", "400")]) alternative ("/test.png", "Image title")]]
      document blocks = Pandoc nullMeta [Figure attribute (Caption (Just [Str "Short list caption"]) blocks) body]
      expectedBlocks = [Para heading, Para [Str "A longer explanation."]]
  forM_ [Plain, Para] $ \block -> do
    let input = document [block complete]
        result = typographyTransformTemporary input
    assert "both Plain and Para captions split into two paragraphs" $
      result == document expectedBlocks
    assert "figure rewrite preserves metadata, short caption, and image body" $
      case result of
        Pandoc _ [Figure attr (Caption short _) contents] ->
          attr == attribute && short == Just [Str "Short list caption"] && contents == body
        _ -> False
    assert "AST rewrite is idempotent" $ typographyTransformTemporary result == result
  let withTail = document [Plain complete, Para [Str "An existing later paragraph."]]
  assert "existing later caption paragraphs survive" $
    typographyTransformTemporary withTail == document (expectedBlocks ++ [Para [Str "An existing later paragraph."]])
  let punctuationOutside = [Strong [Str "Figure 4"], Str ": ", Emph [Str "A short summary"], Str ". A longer explanation."]
      outsideHeading = [Strong [Str "Figure 4"], Str ": ", Emph [Str "A short summary"], Str "."]
  assert "sentence punctuation outside emphasis stays with the heading" $
    typographyTransformTemporary (document [Para punctuationOutside]) ==
      document [Para outsideHeading, Para [Str "A longer explanation."]]

  let negativeCaptions =
        [ ("summary without explanation", heading)
        , ("manual line break", heading ++ [LineBreak, Str "Already separated."])
        , ("panel prefix", [Strong [Str "Figure 4"], Str ": (", Emph [Str "a"], Str ") A panel."])
        , ("another italic fragment", heading ++ [Space, Emph [Str "Continuation."]])
        , ("another bold fragment", heading ++ [Space, Strong [Str "Continuation."]])
        , ("no bold label", [Str "Figure 4: ", Emph [Str "Summary."], Str " Detail."])
        , ("emphasized publication name", [Strong [Str "Figure 4"], Str ": ", Emph [Str "People’s Daily"], Str " Reports on a discovery."])
        , ("emphasized panel direction", [Strong [Str "Figure 4"], Str ": ", Emph [Str "Left"], Str ": A panel."])
        , ("emphasis inside a word", [Strong [Str "Figure 4"], Str ": ", Emph [Str "p"], Str "-values are small."])
        , ("no whitespace after summary", heading ++ [Str "Continuation."])
        , ("later manual break", complete ++ [LineBreak, Str "Already formatted."])
        , ("raw HTML manual break", heading ++ [RawInline (Format "html") "<br>", Str "Already separated."])
        , ("nested manual break", [Strong [Str "Figure 4"], Str ": ", Emph [Str "First line.", LineBreak, Str "Second line."], Str " Detail."])
        ]
  forM_ negativeCaptions $ \(label, inlines) -> do
    let input = document [Para inlines]
    assert label $ typographyTransformTemporary input == input
  assert "an already paragraphized caption is unchanged" $
    typographyTransformTemporary (document expectedBlocks) == document expectedBlocks
  assert "empty captions are unchanged" $
    typographyTransformTemporary (document []) == document []

  -- Exercise both real reader shapes and the normal page typography entry point.
  let markdown = "![**Figure 4**: _A short summary._ A longer explanation.](/test.png)"
      markdownSource = parseMarkdown markdown
      markdownResult = typographyTransformTemporary markdownSource
  assert "Markdown reader creates a native Figure" $ length (captions markdownSource) == 1
  assert "Markdown visible caption is split" $ onlyCaption markdownResult == expectedBlocks
  assert "Markdown alternative text is preserved" $ imageData markdownResult == imageData markdownSource
  let markdownRoundtrip = onlyCaption (parseHTML $ render markdownResult)
  assert "Markdown HTML round trip retains two paragraphs" $
    all paragraph markdownRoundtrip && map stringify markdownRoundtrip == map stringify expectedBlocks
  forM_ ["", "<p>"] $ \opening -> do
    let closing = if T.null opening then "" else "</p>"
        html = "<figure><img src='/test.png' alt='Alternative text'><figcaption>" <> opening <>
               "<strong>Figure 4</strong>: <em>A short summary.</em> A longer explanation." <>
               closing <> "</figcaption></figure>"
        result = onlyCaption (parseHTML $ render $ typographyTransformTemporary $ parseHTML html)
    assert "HTML Plain/Para reader paths both split visible captions" $
      all paragraph result && map stringify result == map stringify expectedBlocks

  let nested = Pandoc nullMeta [BlockQuote [Div ("wrapper", [], [])
                 [Figure attribute (Caption Nothing [Plain complete]) body]]]
  assert "nested figures are visited" $ onlyCaption (typographyTransformTemporary nested) == expectedBlocks
  let inlineImage = Pandoc nullMeta [Para [Str "Inline ", Image nullAttr alternative ("/inline.png", ""), Str " image."]]
  assert "ordinary inline images are untouched" $ typographyTransformTemporary inlineImage == inlineImage
  let ordinary = Pandoc nullMeta [Para complete]
  assert "ordinary prose with caption-like formatting is untouched" $ typographyTransformTemporary ordinary == ordinary
  putStrLn "Figure caption regression tests passed."
