{-# LANGUAGE OverloadedStrings #-}
module TestHost (testHost) where

-- Exercise the real parser and its diagnostics, not just the empty result shared
-- by valid relative URLs and malformed URLs. Run from build/:
--   cabal exec -- ghc -Wall -i. -e TestHost.testHost TestHost.hs
-- Also run by Test.testAll. This named module compiles independently in sync.sh.

import Control.DeepSeq (force)
import Control.Exception (bracket, evaluate, finally)
import Control.Monad (forM_, unless)
import Data.IORef (newIORef, readIORef)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import GHC.IO.Handle (hDuplicate, hDuplicateTo)
import System.IO (hClose, hFlush, stderr)
import System.IO.Temp (withSystemTempFile)

import Utils (host)

testHost :: IO ()
testHost = forM_ cases $ \(input, expected, warning) -> do
    -- host's warning is a pure-looking side effect. Read the argument through IO
    -- so repeating this suite cannot reuse an already-evaluated host thunk.
    freshInput <- newIORef input >>= readIORef
    (actual, diagnostic) <- captureStderr $ evaluate $ force $ host freshInput
    let correctDiagnostic = case warning of
          Nothing -> T.null diagnostic
          Just prefix -> (prefix <> T.pack (show input)) `T.isInfixOf` diagnostic
    unless (actual == expected && correctDiagnostic) $
        ioError $ userError $ "Utils.host regression for " ++ show input ++
          ": expected " ++ show (expected, warning) ++
          "; got " ++ show (actual, diagnostic)
  where
    cases =
      [(base <> fragment, "", Just "Utils.host: Invalid URL; input was: ")
       | base <- ["/lorem-link", "https://example.com/page"],
         fragment <- ["#start#end", "#start#", "##end", "##"]] ++
      [(base <> fragment, expected, Nothing)
       | (base, expected) <- [("/lorem-link", ""), ("https://example.com/page", "example.com")],
         fragment <- ["#start:end", "#start:", "#:end", "#:", "#section", "#literal%23hash"]] ++
      [("https://example.com/", "example.com", Nothing)
      ,("https://example.com/path", "example.com", Nothing)
      ,("https://example.com/café", "example.com", Nothing)
      ,("#section", "", Nothing)
      ,("!W", "", Nothing)
      ,("mailto:gwern@example.com", "", Nothing)
      ,("irc://example.com/channel", "", Nothing)
      ,("https://rauno.me", "rauno.me", Just "Utils.host: Root domain lacks trailing slash; original input was: ")]

-- Both Debug.Trace.trace and printRed write to stderr. Force host inside the
-- capture, flush before redirecting/restoring, and restore even on exceptions.
captureStderr :: IO a -> IO (a, T.Text)
captureStderr action = withSystemTempFile "utils-host-stderr" $ \path temporary -> do
    result <- bracket (hFlush stderr >> hDuplicate stderr)
                      (\saved -> hDuplicateTo saved stderr `finally` hClose saved)
                      (\_ -> do hDuplicateTo temporary stderr
                                action `finally` hFlush stderr)
    hClose temporary
    diagnostic <- TIO.readFile path
    return (result, diagnostic)
