{-# LANGUAGE OverloadedStrings #-}
-- Exact, batched edits of the GTX miscellaneous key-value field. This module is
-- deliberately independent of the scraper and GTX's normalizing writer: changing
-- inversion must not rewrite authors, dates, tags, abstracts, or other records.
module Metadata.Edit
  ( Edit(..), Document, parseDocument, renderDocument, planEdits
  , canonicalizeURL, parseBatch, validateEdit, localInvertFiles, setKV, parseKV
  ) where

import Control.Monad (foldM, unless, when)
import qualified Data.ByteString as B
import Data.Char (chr, digitToInt, isControl, isHexDigit, isSpace, toLower)
import Data.List (isPrefixOf, nub, stripPrefix)
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import System.FilePath ((</>), isAbsolute, splitDirectories, takeExtension)
import Text.Read (readEither)

data Edit = Edit { editURL :: String, editKey :: String, editValue :: Maybe String }
  deriving (Eq, Show)

data Record = Record { recordURL :: String, recordLines :: [T.Text] }
  deriving (Eq, Show)

data Document = Document { documentNewline :: T.Text, documentRecords :: [Record] }
  deriving (Eq, Show)

parseDocument :: T.Text -> Either String Document
parseDocument raw
  | T.null raw = Right $ Document "\n" []
  | otherwise = do
      let nl = if "---\r\n" `T.isPrefixOf` raw then "\r\n" else "\n"
          header = "---" <> nl
      unless (header `T.isPrefixOf` raw) $ Left "GTX must begin with --- followed by a newline"
      records <- mapM (parseRecord nl) $ T.splitOn (nl <> "---" <> nl) $ T.drop (T.length header) raw
      pure $ Document nl records
  where
    parseRecord nl rawRecord = do
      let ls = T.splitOn nl rawRecord
      unless (length ls >= 7) $ Left "GTX record is missing mandatory fields"
      let url = T.unpack $ head ls
      when (null url || any isSpace url) $ Left $ "Invalid GTX URL: " ++ show url
      pure $ Record url ls

renderDocument :: Document -> T.Text
renderDocument (Document _ []) = ""
renderDocument (Document nl rs) = "---" <> nl <> T.intercalate (nl <> "---" <> nl) (map (T.intercalate nl . recordLines) rs)

-- Match the GTX dictionary forms without normalizing any other field. Refuse
-- ambiguous naked values instead of guessing which metadata should be discarded.
parseKV :: T.Text -> Either String [(String, String)]
parseKV raw
  | T.null s || s == "[]" = Right []
  | "[" `T.isPrefixOf` s = do
      kvs <- readEither (T.unpack s)
      unless (all (\(k,v) -> not (null k || null v)) kvs) $ Left "Empty GTX key/value"
      pure kvs
  | otherwise = do
      let parts = words $ T.unpack s
          dois = filter (elem '/') parts
          ids = filter (notElem '/') parts
      unless (length dois <= 1 && length ids <= 1) $ Left $ "Ambiguous naked DOI/ID field: " ++ T.unpack raw
      pure $ map ((,) "doi") dois ++ map ((,) "id") ids
  where s = T.strip raw

-- Keep the first occurrence's position and remove only further copies of the
-- edited key. Unrelated entries, including questionable duplicates, survive.
setKV :: String -> Maybe String -> [(String, String)] -> [(String, String)]
setKV key value = go
  where
    go [] = maybe [] (\v -> [(key,v)]) value
    go ((k,v):rest)
      | k == key = maybe [] (\v' -> [(key,v')]) value ++ filter ((/= key) . fst) rest
      | otherwise = (k,v) : go rest

validateEdit :: Edit -> Either String Edit
validateEdit e@(Edit url key value) = do
  when (null url || any isSpace url) $ Left $ "Invalid URL: " ++ show url
  unless ("/" `isPrefixOf` url || "https://" `isPrefixOf` url || "http://" `isPrefixOf` url) $
    Left $ "Expected a site path or HTTP(S) URL: " ++ url
  when (null key || any (\c -> isSpace c || isControl c || c == '=') key) $
    Left $ "Invalid metadata key: " ++ show key
  case value of
    Just "" -> Left "Empty metadata values are invalid; use --delete KEY instead"
    Just v | key == "invert" -> case map toLower v of
      "true" -> Right e { editValue = Just "True" }
      "false" -> Right e { editValue = Just "False" }
      _ -> Left "invert must be true or false (case-insensitive)"
    _ -> Right e

canonicalizeURL :: FilePath -> String -> Either String String
canonicalizeURL root input = do
  let local = case stripPrefix (root ++ "/") input of
        Just p -> '/' : p
        Nothing -> input
      host = foldl (\p prefix -> maybe p ('/':) (stripPrefix prefix p)) local
                   ["https://gwern.net/", "http://gwern.net/", "//gwern.net/"]
      relative = case stripPrefix "./" host of
        Just p -> '/' : p
        Nothing | "doc/" `isPrefixOf` host || "static/" `isPrefixOf` host -> '/' : host
                | otherwise -> host
      path = takeWhile (\c -> c /= '?' && c /= '#') relative
      image = map toLower (takeExtension path) `elem`
                [".jpg", ".jpeg", ".png", ".gif", ".svg", ".webp", ".avif", ".bmp", ".ico", ".tif", ".tiff"]
      canonical | image && "/" `isPrefixOf` relative = path
                | image = takeWhile (/= '#') relative
                | otherwise = relative
  _ <- validateEdit (Edit canonical "_validation" (Just "value"))
  pure canonical

-- GTX keys may already contain literal percent signs or hashes. Check the exact
-- filename first, then a URL-decoded alternative, without changing the key/case.
-- Only safe paths inside root are candidates; deletion needs no existing file.
localInvertFiles :: FilePath -> Edit -> Either String [FilePath]
localInvertFiles root (Edit url "invert" (Just _))
  | "/" `isPrefixOf` url && not ("//" `isPrefixOf` url) = do
      let literal = drop 1 url
          safe candidate = not (null candidate || isAbsolute candidate || ".." `elem` splitDirectories candidate || any isControl candidate)
          path = takeWhile (`notElem` ("?#" :: String)) literal
          bytes = B.unpack $ TE.encodeUtf8 $ T.pack path
          decode [] = Right []
          decode (37:a:b:rest)
            | all (isHexDigit . chr . fromIntegral) [a,b] =
                let digit = digitToInt . chr . fromIntegral
                in (fromIntegral (16 * digit a + digit b) :) <$> decode rest
          decode (37:_) = Left ()
          decode (c:rest) = (c :) <$> decode rest
          decoded = do
            decodedBytes <- decode bytes
            either (const $ Left ()) (Right . T.unpack) $ TE.decodeUtf8' $ B.pack decodedBytes
          alternatives = either (const []) (\p -> [p | safe p]) decoded
      unless (safe literal) $ Left $ "Invalid local image path: " ++ url
      pure $ map (root </>) $ nub $ literal : alternatives
localInvertFiles _ _ = Right []

parseBatch :: FilePath -> T.Text -> Either String [Edit]
parseBatch root raw = mapM parseLine $ filter significant $ zip [(1 :: Int)..] $ T.lines raw
  where
    significant (_,line) = not (T.null (T.strip line) || "#" `T.isPrefixOf` line)
    parseLine (n,line) = case T.splitOn "\t" (T.dropWhileEnd (== '\r') line) of
      [url,key,value] -> do
        canonical <- canonicalizeURL root (T.unpack url)
        validateEdit $ Edit canonical (T.unpack key) (Just $ T.unpack value)
      _ -> Left $ "Batch line " ++ show n ++ ": expected URL<TAB>KEY<TAB>VALUE"

-- The four inputs are me, full, half, auto, in lookup precedence order. Resolve
-- edits once, traverse each database once, and append promoted/new entries once.
-- Duplicate *targeted* URL records in the winning file are errors. Other records
-- are never deduplicated by converting an entire GTX file into a Map.
planEdits :: String -> [Edit] -> [Document] -> Either String [Document]
planEdits today edits docs = do
  unless (length docs == 4) $ Left "Expected me/full/half/auto GTX documents"
  normalized <- mapM validateEdit edits
  editMap <- foldM insertEdit M.empty normalized
  let indices = map (M.fromListWith (++) . map (\r -> (recordURL r,[r])) . documentRecords) docs
      byURL = M.fromListWith (++) [(u,[(k,v)]) | ((u,k),v) <- M.toList editMap]
  destinations <- mapM (destination indices) $ M.toList byURL
  let changes = M.fromList [(u,(i,kvs)) | (u,i,kvs) <- destinations]
  modified <- mapM (modifyDoc changes) $ zip [(0 :: Int)..] docs
  let half = modified !! 2
      promoted = [r | r <- documentRecords (modified !! 3), maybe False ((== 3) . fst) (M.lookup (recordURL r) changes)]
      auto = (modified !! 3) { documentRecords = filter (\r -> maybe True ((/= 3) . fst) (M.lookup (recordURL r) changes)) $ documentRecords (modified !! 3) }
      new = [newRecord today u kvs | (u,i,kvs) <- destinations, i == 4, any (maybe False (const True) . snd) kvs]
      half' = half { documentRecords = documentRecords half ++ promoted ++ new }
  pure [modified !! 0, modified !! 1, half', auto]
  where
    insertEdit m (Edit u k v) = case M.lookup (u,k) m of
      Just old | old /= v -> Left $ "Conflicting batch values for " ++ u ++ " / " ++ k
      _ -> Right $ M.insert (u,k) v m
    destination indices (u,kvs) = do
      let found = [(i,rs) | (i,index) <- zip [(0 :: Int)..] indices, Just rs <- [M.lookup u index]]
      case found of
        [] -> pure (u,4,kvs)
        ((i,rs):_) -> do
          unless (length rs == 1) $ Left $ "Duplicate targeted URL in " ++ ["me","full","half","auto"] !! i ++ ".gtx: " ++ u
          pure (u,i,kvs)
    modifyDoc changes (i,doc) = do
      rs <- mapM (modifyRecord changes i) $ documentRecords doc
      pure $ doc { documentRecords = rs }
    modifyRecord changes i r = case M.lookup (recordURL r) changes of
      Just (source,kvs) | i == source -> do
        old <- parseKV $ recordLines r !! 5
        let new = foldl (\xs (k,v) -> setKV k v xs) old kvs
        pure $ if new == old then r else r { recordLines = take 5 (recordLines r) ++
                          [if null new then "" else T.pack (show new)] ++ drop 6 (recordLines r) }
      _ -> Right r
    newRecord date u kvs = Record u $ map T.pack
      [u,"","","",date,show [(k,v) | (k,Just v) <- kvs],"",""]
