{-# LANGUAGE DeriveGeneric, TemplateHaskell #-}

import Game.Cosanostra.Glue.Instances.JSON ()

import Game.Cosanostra.Lenses
import Game.Cosanostra.Types

import Control.Lens
import Data.Aeson.TH
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Data.Yaml
import GHC.Generics
import System.Environment

import System.IO

data ModKillArgs = ModKillArgs
    { target :: Player
    , reason :: T.Text
    , modifyPlan :: Bool
    } deriving (Generic)

deriveJSON defaultOptions{sumEncoding = ObjectWithSingleField} ''ModKillArgs

main :: IO ()
main = do
    [gamePath, planPath] <- getArgs
    game <- either error id <$> decodeEither <$> BS.readFile gamePath
    plan <- either error id <$> decodeEither <$> BS.readFile planPath :: IO Plan

    args <- either error id <$> decodeEither <$> BS.hGetContents stdin

    let game' = game & gameModActionIndex %~ (+1)
                     & gamePlayers %~ \(Players ps) -> Players $ M.adjust (Effect{ _effectType = Death (ModKilled (reason args))
                                                                                 , _effectUses = Nothing
                                                                                 , _effectConstraint = Trivial
                                                                                 , _effectTrace = EffectFromMod { _effectTraceIndex = game ^. gameModActionIndex }
                                                                                 }:) (target args) ps

    let plan' = if modifyPlan args then M.filter (\act -> not (target args `elem` (act ^. actTargets)) &&
                                                          (act ^. actSource) /= target args) plan
                                   else plan

    game' `seq` BS.writeFile gamePath $ encode game'
    plan' `seq` BS.writeFile planPath $ encode plan'
