{-# LANGUAGE OverloadedStrings #-}
-- Run from static: ghc -package random -Wall -Werror -ibuild build/test/ImageDimensionsTest.hs -e 'main'
-- Fake identify responses exercise the production IO paths without real images
-- or network requests. Fully render the results: the old ratio failure was lazy.
module Main (main) where

import Control.Exception (SomeException, bracket, bracket_, evaluate, try)
import Control.Monad (filterM, forM_, unless, void)
import Data.List (isInfixOf)
import qualified Data.Text as T
import System.Directory (createDirectory, doesFileExist, getPermissions, setPermissions,
                         executable, withCurrentDirectory)
import System.Environment (getEnv, setEnv)
import System.FilePath ((</>))
import System.IO (SeekMode(AbsoluteSeek), hClose, hFlush, hGetContents, hSeek, stderr)
import System.IO.Temp (withSystemTempDirectory, withSystemTempFile)
import GHC.IO.Handle (hDuplicate, hDuplicateTo)
import Text.HTML.TagSoup (Tag(..))
import Text.Pandoc (Inline(..))

import Image (addImgDimensions, imageLinkHeightWidthSet, imageMagickDimensions,
              imageMagickDimensionsInt, sizeAspectRatioKV, staticImg, svgViewBoxDimensions)

assert :: String -> Bool -> IO ()
assert label ok = unless ok $ error ("FAIL: " ++ label)

forceShown :: Show a => a -> IO ()
forceShown value = void $ evaluate $ length $ show value

captureStderr :: IO a -> IO (a, String)
captureStderr action = withSystemTempFile "image-dimensions-stderr" $ \_ handle ->
  bracket (hDuplicate stderr) hClose $ \saved -> do
    result <- bracket_ (hDuplicateTo handle stderr)
                       (hFlush stderr >> hDuplicateTo saved stderr) action
    hSeek handle AbsoluteSeek 0
    output <- hGetContents handle
    void $ evaluate $ length output
    return (result,output)

expectFailure :: Show a => String -> [String] -> IO a -> IO ()
expectFailure label pieces action = do
  result <- try (action >>= forceShown) :: IO (Either SomeException ())
  case result of
    Right () -> error $ "FAIL: " ++ label ++ " did not fail"
    Left exception -> do
      let message = show exception
      forM_ pieces $ \piece ->
        assert (label ++ " identifies " ++ show piece ++ ": " ++ message) $ piece `isInfixOf` message
      assert (label ++ " avoids the anonymous ratio crash") $ not $ "Ratio has zero denominator" `isInfixOf` message

main :: IO ()
main = do
  pureDimensions
  pureSVGDimensions
  -- Keep the real regression asset in the test: its valid fractional coordinate
  -- system has produced both 0x0 and 1x1 from different identify installations.
  -- Standalone tests, sync.sh and Cabal run from static/, wiki/ and static/build/.
  assetPaths <- filterM doesFileExist ["img/icon/yud.svg", "static/img/icon/yud.svg", "../img/icon/yud.svg"]
  yudSVG <- case assetPaths of
    path:_ -> readFile path
    [] -> error "Cannot find the real yud.svg regression asset from this working directory"
  assert "real yud asset retains its exact viewBox ratio" $
    svgViewBoxDimensions yudSVG == Just (26755,16976)
  withSystemTempDirectory "image-dimensions-test" $ \directory -> do
    let bin = directory </> "bin"
        identify = bin </> "identify"
    createDirectory bin
    createDirectory $ directory </> "doc"
    writeFile identify fakeIdentify
    permissions <- getPermissions identify
    setPermissions identify permissions{executable=True}
    forM_ ["wide.png", "wider.png", "normal.png", "tall.png", "animated.gif",
           "zero.png", "negative.png", "empty.png", "malformed.png", "overflow.png",
           "identify-fail.png", "movie.mp4", "movie.mp4-poster.jpg", "no-poster.mp4"] $ \name ->
      writeFile (directory </> "doc" </> name) ""
    writeFile (directory </> "doc" </> "yud.svg") yudSVG
    writeFile (directory </> "doc" </> "explicit.svg")
      "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100px\" height=\"50px\" viewBox=\"0 0 1 1\"></svg>"
    oldPath <- getEnv "PATH"
    (_,warnings) <- captureStderr $
      bracket_ (setEnv "PATH" (bin ++ ":" ++ oldPath)) (setEnv "PATH" oldPath) $
        withCurrentDirectory directory (ioDimensions >> ioSVGDimensions)
    forM_ ["doc/wide.png", "2800x1", "doc/wider.png", "3000x1"] $ \piece ->
      assert ("thin-image warning identifies " ++ piece) $ piece `isInfixOf` warnings
  putStrLn "Image dimension and path-diagnostic regression tests passed."

pureDimensions :: IO ()
pureDimensions = do
  forM_ [(2800,1,"2800 / 1","1400","1"),
         (3000,1,"3000 / 1","1400","1"),
         (2800,200,"14 / 1","1400","100"),
         (1,3000,"1 / 3000","1","3000"),
         (maxBound,maxBound,"1 / 1","1400","1400"),
         (maxBound,1,show (maxBound :: Int) ++ " / 1","1400","1")] $
    \(width,height,ratio,expectedWidth,expectedHeight) -> do
      let attributes = sizeAspectRatioKV width height
          label = show width ++ "x" ++ show height
      forceShown attributes
      assert (label ++ " keeps the source ratio") $ lookup "data-aspect-ratio" attributes == Just ratio
      assert (label ++ " has the expected display width") $ lookup "width" attributes == Just expectedWidth
      assert (label ++ " has a positive display height") $ lookup "height" attributes == Just expectedHeight
  -- Check positivity, bounded display width, and conservation of the intrinsic
  -- ratio across the rounding boundary and at the largest representable input.
  forM_ [(w,h) | w <- [1,1399,1400,1401,2799,2800,3000,maxBound],
                  h <- [1,2,1400,maxBound]] $ \(width,height) -> do
    let attributes = sizeAspectRatioKV width height
        attr name = case lookup name attributes of
          Just value -> value
          Nothing -> error $ "Missing dimension attribute: " ++ name
        displayWidth = read (attr "width") :: Integer
        displayHeight = read (attr "height") :: Integer
    assert "display dimensions stay positive" $ displayWidth > 0 && displayHeight > 0
    assert "display width stays capped" $ displayWidth <= 1400
    case words $ attr "data-aspect-ratio" of
      [numerator,"/",denominator] ->
        assert "source aspect ratio survives integer rounding" $
          (read numerator :: Integer) * toInteger height == (read denominator :: Integer) * toInteger width
      _ -> error "Invalid data-aspect-ratio syntax"
  forM_ [(0,200),(100,0),(-1,200),(100,-1)] $ \(width,height) ->
    expectFailure "invalid pure dimensions" ["sizeAspectRatioKV",show width,show height] $
      pure $ sizeAspectRatioKV width height

pureSVGDimensions :: IO ()
pureSVGDimensions = do
  forM_ [("0 0 0.16976 0.26755", (26755,16976)),
         ("0 0 1200 830", (830,1200)),
         ("-1.5,+2,1e-4,2.5E-4", (5,2)),
         ("0 0 .5 .25", (1,2)),
         ("0 0 +2. 3.", (3,2)),
         ("0 0 +.5E+1 2.5", (1,2)),
         ("0 0 2.e-1 3.e-1", (3,2)),
         ("0 0 1e-400 2e-400", (2,1))] $ \(viewBox,dimensions) ->
    assert ("exact SVG viewBox: " ++ viewBox) $
      svgViewBoxDimensions ("<svg viewBox=\"" ++ viewBox ++ "\"></svg>") == Just dimensions
  assert "XML declaration and comment precede the SVG root" $
    svgViewBoxDimensions "<?xml version=\"1.0\"?><!-- icon --><svg viewBox=\"0 0 3 4\"/>" == Just (4,3)
  assert "nested SVG does not replace outer dimensions" $
    svgViewBoxDimensions "<svg viewBox=\"0 0 10 20\"><svg viewBox=\"0 0 1 1\"/></svg>" == Just (20,10)
  assert "nested viewBox is not an outer viewport" $
    svgViewBoxDimensions "<svg><svg viewBox=\"0 0 1 1\"/></svg>" == Nothing
  assert "non-SVG document root is not an SVG viewport" $
    svgViewBoxDimensions "<div><svg viewBox=\"0 0 1 1\"/></div>" == Nothing
  forM_ ["width=\"100\" height=\"50\"", "width=\"1in\"", "height=\"50%\"",
         "width=\"0\" height=\"0\"", "style=\"width: 100px; height: 50px\""] $ \viewport ->
    assert ("explicit SVG viewport defers to identify: " ++ viewport) $
      svgViewBoxDimensions ("<svg " ++ viewport ++ " viewBox=\"0 0 1 1\"/>") == Nothing
  let tooLarge = show (toInteger (maxBound :: Int) + 1)
  forM_ ["", "0 0 1", "0 0 1 2 3", "0 0 0 1", "0 0 1 0", "0 0 -1 2",
         ". 0 1 2", "0 .e1 1 2",
         "0 0 NaN 1", "0 0 1 Infinity", "0 0 2px 1", "0 0 1e1025 2e1025",
         "0 0 " ++ tooLarge ++ " 1", "0 0 1e-30 1.1"] $ \viewBox ->
    assert ("invalid or unrepresentable SVG viewBox is rejected: " ++ viewBox) $
      svgViewBoxDimensions ("<svg viewBox=\"" ++ viewBox ++ "\"/>") == Nothing

ioSVGDimensions :: IO ()
ioSVGDimensions = do
  -- The fake identify rejects yud.svg, so these calls prove that SVG coordinate
  -- dimensions bypass raster probing instead of depending on its 0x0/1x1 result.
  dimensions <- imageMagickDimensions "/doc/yud.svg"
  assert "real fractional SVG gets positive proportional dimensions" $
    dimensions == ("26755","16976")
  html <- addImgDimensions "<figure><img src=\"/doc/yud.svg\"></figure>"
  forceShown html
  assert "SVG HTML preserves exact non-square viewBox ratio" $
    "data-aspect-ratio=\"16976 / 26755\"" `isInfixOf` html
  link <- imageLinkHeightWidthSet $ Link ("",[],[]) [Str "yud"] ("/doc/yud.svg","")
  forceShown link
  case link of
    Link (_,_,attributes) _ _ -> do
      assert "SVG popup link preserves exact viewBox ratio" $
        lookup "data-aspect-ratio" attributes == Just "16976 / 26755"
      assert "SVG popup link uses positive proxy dimensions" $
        lookup "image-width" attributes == Just "16976" && lookup "image-height" attributes == Just "26755"
    _ -> error "imageLinkHeightWidthSet changed the SVG inline type"
  explicit <- imageMagickDimensions "/doc/explicit.svg"
  assert "explicit SVG viewport dimensions take precedence over square viewBox" $
    explicit == ("50","100")
  explicitHTML <- addImgDimensions "<img src=\"/doc/explicit.svg\">"
  forceShown explicitHTML
  assert "explicit SVG viewport ratio survives HTML rendering" $
    "data-aspect-ratio=\"2 / 1\"" `isInfixOf` explicitHTML

ioDimensions :: IO ()
ioDimensions = do
  forM_ ["doc/normal.png", "/doc/normal.png", "https://gwern.net/doc/normal.png"] $ \path -> do
    dimensions <- imageMagickDimensions path
    assert ("height/width order and path resolution: " ++ path) $ dimensions == ("200","2800")
    typed <- imageMagickDimensionsInt path
    assert ("typed positive dimensions: " ++ path) $ typed == (200,2800)
  frames <- imageMagickDimensions "/doc/animated.gif"
  assert "animated images use the first frame" $ frames == ("10","20")
  poster <- imageMagickDimensions "/doc/movie.mp4"
  assert "video dimensions come from its poster" $ poster == ("90","160")

  forM_ [("wide.png","2800 / 1"),("wider.png","3000 / 1")] $ \(name,ratio) -> do
    let path = "/doc/" ++ name
    tag <- staticImg $ TagOpen "img" [("src",path)]
    forceShown tag
    case tag of
      TagOpen "img" attributes -> do
        assert "static image has a positive one-pixel display height" $ lookup "height" attributes == Just "1"
        assert "static image preserves its source ratio" $ lookup "data-aspect-ratio" attributes == Just ratio
      _ -> error "staticImg changed the tag type"
    html <- addImgDimensions $ "<figure><img src=\"" ++ path ++ "\"></figure>"
    forceShown html
    assert "serialized strip keeps its source ratio" $ ("data-aspect-ratio=\"" ++ ratio ++ "\"") `isInfixOf` html
    link <- imageLinkHeightWidthSet $ Link ("",[],[]) [Str "image"] (T.pack path,"")
    forceShown link
    case link of
      Link (_,_,attributes) _ _ -> do
        assert "popup link preserves its source ratio" $ lookup "data-aspect-ratio" attributes == Just (T.pack ratio)
        assert "popup link keeps its intrinsic height" $ lookup "image-height" attributes == Just "1"
      _ -> error "imageLinkHeightWidthSet changed the inline type"

  forM_ [("zero.png",["0","1200"]),
         ("negative.png",["-7"]),
         ("empty.png",["empty diagnostic"]),
         ("malformed.png",["not-a-number","malformed diagnostic"]),
         ("overflow.png",["999999999999999999999999999999"]),
         ("identify-fail.png",["7","failed stdout","failed stderr"])] $ \(name,details) -> do
    let path = "/doc/" ++ name
    expectFailure ("invalid identify output: " ++ name) (path:("doc/" ++ name):details) $
      imageMagickDimensions path
  expectFailure "missing local image" ["/doc/missing.png","doc/missing.png"] $
    imageMagickDimensions "/doc/missing.png"
  expectFailure "missing video poster" ["/doc/no-poster.mp4","doc/no-poster.mp4-poster.jpg"] $
    imageMagickDimensions "/doc/no-poster.mp4"
  expectFailure "missing video poster in a popup link" ["no-poster.mp4","no-poster.mp4-poster.jpg"] $
    imageLinkHeightWidthSet $ Link ("",[],[]) [Str "video"] ("/doc/no-poster.mp4","")
  expectFailure "invalid dimensions through the HTML image path" ["zero.png","0","1200"] $
    addImgDimensions "<img src=\"/doc/zero.png\">"
  expectFailure "invalid dimensions through the popup link path" ["zero.png","0","1200"] $
    imageLinkHeightWidthSet $ Link ("",[],[]) [Str "image"] ("/doc/zero.png","")

fakeIdentify :: String
fakeIdentify = unlines
  [ "#!/usr/bin/env bash"
  , "set -e"
  , "case \"${!#}\" in"
  , "  */wide.png) printf '1 2800\\n' ;;"
  , "  */wider.png) printf '1 3000\\n' ;;"
  , "  */normal.png) printf '200 2800\\n' ;;"
  , "  */tall.png) printf '3000 1\\n' ;;"
  , "  */animated.gif) printf '10 20\\n5 7\\n' ;;"
  , "  */movie.mp4-poster.jpg) printf '90 160\\n' ;;"
  , "  */explicit.svg) printf '50 100\\n' ;;"
  , "  */zero.png) printf '0 1200\\n' ;;"
  , "  */negative.png) printf '1 -7\\n' ;;"
  , "  */empty.png) printf 'empty diagnostic\\n' >&2 ;;"
  , "  */malformed.png) printf 'not-a-number 1200\\n'; printf 'malformed diagnostic\\n' >&2 ;;"
  , "  */overflow.png) printf '999999999999999999999999999999 1200\\n' ;;"
  , "  */identify-fail.png) printf 'failed stdout\\n'; printf 'failed stderr\\n' >&2; exit 7 ;;"
  , "  *) printf 'unexpected identify path: %s\\n' \"${!#}\" >&2; exit 9 ;;"
  , "esac"
  ]
