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

-- Small report fixtures, not Markdown snapshots: check the actual emitted entry
-- links, their top-level sections, and selected YAML fields. The sole substituted
-- service is the link-bibliography file lookup, whose normal implementation cd's
-- to ~/wiki. Everything is otherwise generated in a disposable directory, using
-- real file discovery, author classification, transclusions, and Pandoc rendering.
-- Run from build/: ./test/generateDirectory.sh

import Control.Monad (forM_, unless)
import Data.List (sort)
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.Directory (createDirectoryIfMissing, withCurrentDirectory)
import System.FilePath (takeDirectory)
import System.IO.Temp (withSystemTempDirectory)
import Text.Pandoc (Block(Header), Inline(Link), Pandoc(Pandoc), def,
                    pandocExtensions, readMarkdown, readerExtensions, runPure)
import Text.Pandoc.Shared (stringify)
import Text.Pandoc.Walk (query)

import qualified Main as G
import LinkMetadataTypes (Metadata, MetadataItem)

type Entry = (FilePath, MetadataItem)

entry :: String -> FilePath -> String -> String -> String -> [String] -> String -> Entry
entry ident path title author added tags abstract =
  (path, (title, author, "2020-01-01", added, [("id", ident)], tags, abstract))

check :: String -> Bool -> IO ()
check label ok = unless ok (error $ "generateDirectory regression: " ++ label)

-- Each entry's primary link carries include-annotation. File transclusions,
-- navigation, and bibliography links can repeat URLs, so do not count those.
entryLinks :: Inline -> [T.Text]
entryLinks (Link (_, classes, _) _ (url, _))
  | "include-annotation" `elem` classes = [url]
entryLinks _ = []

sections :: T.Text -> [(T.Text, T.Text)]
sections markdown = case parseReport markdown of
  Pandoc _ blocks -> go "" blocks
 where
  go _ [] = []
  go _ (Header 1 _ title : rest) = go (stringify title) rest
  go section (block : rest) = map (\url -> (section, url)) (query entryLinks block) ++ go section rest

checkEntries :: String -> [(T.Text, FilePath)] -> T.Text -> IO ()
checkEntries label expected actual =
  let expectedLinks = sort [(section, T.pack path) | (section, path) <- expected]
      actualLinks = sort $ sections actual
  in check (label ++ ": expected " ++ show expectedLinks ++ "; got " ++ show actualLinks) $
       actualLinks == expectedLinks

parseReport :: T.Text -> Pandoc
parseReport markdown = either (error . show) id $
  runPure $ readMarkdown def{readerExtensions = pandocExtensions} markdown

allLinks :: Inline -> [T.Text]
allLinks (Link _ _ (url, _)) = [url]
allLinks _ = []

field :: T.Text -> T.Text -> T.Text
field name markdown = case filter (T.isPrefixOf $ name <> ": ") $ T.lines markdown of
  [line] -> T.drop (T.length name + 2) line
  found -> error $ "Expected one YAML field " ++ T.unpack name ++ ", found " ++ show found

fixtureFile :: FilePath -> IO ()
fixtureFile path = do
  let relative = dropWhile (== '/') path
  createDirectoryIfMissing True $ takeDirectory relative
  writeFile relative "fixture\n"

-- Complete metadata and archive fixtures prevent missing-annotation scraping
-- and archive-database insertion. Tiny fixtures stay below the sort-by-magic
-- threshold; bottom values make any accidental use of those databases fail.
render :: Bool -> [FilePath] -> FilePath -> Metadata -> IO T.Text
render newest dirs dir metadata = do
  createDirectoryIfMissing True dir
  G.generateDirectoryWith (\_ -> pure ("", "")) newest (M.map (const $ Left 0) metadata) metadata
    (error "fixture unexpectedly used the cluster-name database")
    (error "fixture unexpectedly used the magic-sort database")
    (error "fixture unexpectedly used embeddings") dirs dir
  TIO.readFile $ dir ++ "index.md"

main :: IO ()
main = withSystemTempDirectory "generate-directory-test" $ \temporary ->
  withCurrentDirectory temporary $ do
    let abstract = "<p>Fixture annotation.</p>"
        modelPaper = entry "fixture-model-free" "/doc/model-free/paper.pdf" "Cross-tagged paper" "Other Author" "2020-02-01" ["model", "model-free"] abstract
        directPaper = entry "fixture-direct" "/doc/model/direct.pdf" "Physical paper" "Other Author" "2020-01-01" ["model"] abstract
        childIndex = entry "fixture-child-index" "/doc/model/child/index" "Child tag" "Other Author" "2020-01-01" ["model"] abstract
    mapM_ fixtureFile [fst modelPaper, fst directPaper, "/doc/model/child/index.md"]
    model <- render False ["doc/model/"] "doc/model/" $ M.fromList [modelPaper, directPaper, childIndex]
    checkEntries "path-prefix collision and physical-file deduplication"
      [("Links", fst modelPaper), ("Links", fst directPaper)] model
    check "child tag appears only once in See Also" $
      length (filter (== "/doc/model/child/index") $ query allLinks $ parseReport model) == 1

    let wikipedia = entry "fixture-wikipedia" "https://en.wikipedia.org/wiki/Fixture" "Wikipedia fixture" "Other Author" "2020-01-01" ["wiki"] abstract
        untitled = entry "fixture-untitled" "https://example.org/untitled" "" "Other Author" "2020-01-01" ["wiki"] ""
    wikiOnly <- render False ["doc/wiki/"] "doc/wiki/" $ M.fromList [wikipedia]
    checkEntries "Wikipedia-only directory" [("Links", fst wikipedia)] wikiOnly
    wikiMixed <- render False ["doc/wiki/"] "doc/wiki/" $ M.fromList [wikipedia, untitled]
    checkEntries "Wikipedia plus untitled ordinary link"
      [("Links", fst wikipedia), ("Miscellaneous", fst untitled)] wikiMixed

    let comic = entry "fixture-comic" "/doc/own/comic.jpg" "Own comic" "Gwern, Example Model" "2020-03-01" ["own", "cross"] ""
        ownUntitled = entry "fixture-own-untitled" "/doc/own/untitled.txt" "" "Example Model, gwern" "2020-02-01" ["own", "cross"] ""
        svg = entry "fixture-svg" "/doc/own/diagram.svg" "Own SVG" "Gwern" "2020-04-01" ["own", "cross"] ""
        older = entry "fixture-older-image" "https://example.org/older" "Older image" "Other Author" "2020-01-01" ["own", "cross"]
                  "<p><img src=\"/doc/elsewhere/older.jpg\" alt=\"Old image\"></p>"
        ownMetadata = M.fromList [comic, ownUntitled, svg, older]
        expectedOwn = [("Gwern", fst comic), ("Gwern", fst svg), ("Miscellaneous", fst ownUntitled), ("Links", fst older)]
    mapM_ fixtureFile [fst comic, fst ownUntitled]
    forM_ ["doc/own/", "doc/cross/"] $ \dir -> do
      classified <- render False [dir] dir $ M.fromList [comic, ownUntitled]
      checkEntries ("physical/cross-tag classification without clustering: " ++ dir)
        [("Gwern", fst comic), ("Miscellaneous", fst ownUntitled)] classified
    mapM_ fixtureFile [fst svg, "/doc/elsewhere/older.jpg"]
    forM_ ["doc/own/", "doc/cross/"] $ \dir -> do
      own <- render False [dir] dir ownMetadata
      checkEntries ("physical/cross-tag author classification: " ++ dir) expectedOwn own
      check "own comic supplies thumbnail; SVG remains excluded" $ field "thumbnail" own == T.pack (fst comic)
      check "own work advances modified date" $ field "modified" own == "2020-04-01"
      check "tag classification does not depend on a next-page link" $ " tag'" `T.isSuffixOf` field "title" own
      again <- render False [dir] dir ownMetadata
      check "unchanged inputs produce byte-identical output" $ own == again

    let sole = entry "fixture-sole" "/doc/sole/own.pdf" "Only my work" "Gwern" "2020-05-01" ["sole"] abstract
    fixtureFile $ fst sole
    ownOnly <- render False ["doc/sole/"] "doc/sole/" $ M.fromList [sole]
    checkEntries "directory containing only a physical own work" [("Gwern", fst sole)] ownOnly
    check "own-only directory retains a valid creation date" $ field "created" ownOnly == "2020-05-01"

    let report = entry "fixture-report" "/doc/reports/research.md.txt" "Coauthored report" "Example Model, Gwern" "2020-06-01" ["reports"] ""
    fixtureFile $ fst report
    newest <- render True ["doc/", "doc/newest/", "/"] "doc/newest/" $ uncurry M.insert report ownMetadata
    checkEntries "newest preserves empty-abstract own works and excludes untitled own works"
      [("Gwern", fst report), ("Gwern", fst comic), ("Gwern", fst svg), ("Links", fst older)] newest
    check "newest navigation points at the homepage" $ field "next" newest == "/index"
    check "newest thumbnail includes own works" $ field "thumbnail" newest == T.pack (fst comic)
    check "newest modification date includes the report" $ field "modified" newest == "2020-06-01"

    let note = entry "fixture-note" "/note/demo/paper.pdf" "Note fixture" "Other Author" "2020-01-01" [] abstract
    fixtureFile $ fst note
    notes <- render False ["note/demo/", "doc/later/"] "note/demo/" $ M.fromList [note]
    checkEntries "ordinary non-tag directory" [("Links", fst note)] notes
    check "non-tag classification does not depend on its next tag link" $ " directory'" `T.isSuffixOf` field "title" notes
    putStrLn "generateDirectory integration fixtures passed."
