diff --git a/Cargo.lock b/Cargo.lock
index 56e1f13..c87971d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -17,6 +17,15 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aho-corasick"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "anstream"
version = "0.6.21"
@@ -96,7 +105,10 @@ name = "bin_efo"
version = "0.1.0"
dependencies = [
"clap",
+ "derive_more",
+ "env_logger",
"lib_efo",
+ "log",
"miette",
"serde",
"serde_json",
@@ -109,6 +121,12 @@ version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
+[[package]]
+name = "bumpalo"
+version = "3.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
+
[[package]]
name = "cfg-if"
version = "1.0.4"
@@ -155,12 +173,109 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
+[[package]]
+name = "cli-table"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14da8d951cef7cc4f13ccc9b744d736963d57863c7e6fc33c070ea274546082c"
+dependencies = [
+ "cli-table-derive",
+ "csv",
+ "termcolor",
+ "unicode-width 0.2.2",
+]
+
+[[package]]
+name = "cli-table-derive"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c1b60bae2c3d45228dfb096046aa51ef6c300de70b658d7a13fcb0c4f832e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
+[[package]]
+name = "colored"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e"
+dependencies = [
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "csv"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
+dependencies = [
+ "csv-core",
+ "itoa",
+ "ryu",
+ "serde_core",
+]
+
+[[package]]
+name = "csv-core"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "derive_more"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678"
+dependencies = [
+ "derive_more-impl",
+]
+
+[[package]]
+name = "derive_more-impl"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "unicode-xid",
+]
+
+[[package]]
+name = "env_filter"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2"
+dependencies = [
+ "log",
+ "regex",
+]
+
+[[package]]
+name = "env_logger"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "env_filter",
+ "jiff",
+ "log",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -171,6 +286,18 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "wasip2",
+]
+
[[package]]
name = "gimli"
version = "0.32.3"
@@ -201,15 +328,57 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
+[[package]]
+name = "jiff"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49cce2b81f2098e7e3efc35bc2e0a6b7abec9d34128283d7a26fa8f32a6dbb35"
+dependencies = [
+ "jiff-static",
+ "log",
+ "portable-atomic",
+ "portable-atomic-util",
+ "serde_core",
+]
+
+[[package]]
+name = "jiff-static"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.83"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8"
+dependencies = [
+ "once_cell",
+ "wasm-bindgen",
+]
+
[[package]]
name = "lib_efo"
version = "0.1.0"
dependencies = [
"clap",
+ "cli-table",
+ "colored",
+ "derive_more",
+ "env_logger",
+ "log",
"miette",
+ "once_cell",
+ "rand",
"serde",
"serde_json",
"thiserror",
+ "uuid",
]
[[package]]
@@ -224,6 +393,12 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
+[[package]]
+name = "log"
+version = "0.4.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
+
[[package]]
name = "memchr"
version = "2.7.6"
@@ -278,6 +453,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "once_cell"
+version = "1.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
@@ -290,6 +471,30 @@ version = "4.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52"
+[[package]]
+name = "portable-atomic"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.103"
@@ -308,6 +513,70 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "rand"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
+dependencies = [
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
+dependencies = [
+ "getrandom",
+]
+
+[[package]]
+name = "regex"
+version = "1.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"
+
[[package]]
name = "rustc-demangle"
version = "0.1.26"
@@ -327,6 +596,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
[[package]]
name = "ryu"
version = "1.0.20"
@@ -414,6 +689,15 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "termcolor"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
+dependencies = [
+ "winapi-util",
+]
+
[[package]]
name = "terminal_size"
version = "0.4.3"
@@ -478,25 +762,115 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+[[package]]
+name = "uuid"
+version = "1.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"
+dependencies = [
+ "getrandom",
+ "js-sys",
+ "serde",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasip2"
+version = "1.0.1+wasi-0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
- "windows-targets",
+ "windows-targets 0.53.5",
]
[[package]]
@@ -508,6 +882,22 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
[[package]]
name = "windows-targets"
version = "0.53.5"
@@ -515,60 +905,134 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link",
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
- "windows_i686_gnullvm",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
]
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea879c944afe8a2b25fef16bb4ba234f47c694565e97383b36f3a878219065c"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf955aa904d6040f70dc8e9384444cb1030aed272ba3cb09bbc4ab9e7c1f34f5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
diff --git a/Cargo.toml b/Cargo.toml
index 12fd715..12f5a22 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,3 +8,6 @@ clap = { version = "4.5.51", features = ["derive"] }
thiserror = "2.0.17"
serde_json = "1.0.145"
miette = { version = "7.6.0", features = ["fancy"] }
+env_logger = "0.11.8"
+log = "0.4.28"
+derive_more = { version = "2.0.1", features = ["display"] }
diff --git a/Jenkinsfile b/Jenkinsfile
index f9e155d..91b40e0 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -29,7 +29,7 @@ pipeline {
} else if (env.BRANCH_NAME == 'origin/master' || env.BRANCH_NAME == 'master') {
sh 'cargo test'
} else {
- echo "Unknown branch: ${env.BRANCH_NAME} — skipping build."
+ echo "Unknown branch: ${env.BRANCH_NAME} - skipping build."
}
}
}
diff --git a/LICENSE b/LICENSE
index c17e26f..d5ef671 100644
--- a/LICENSE
+++ b/LICENSE
@@ -6,10 +6,10 @@ treat the Software as is, without restriction, subject to the following
condition:
• The Software may not be used, directly or indirectly, for training,
- fine‑tuning, or otherwise feeding into any artificial‑intelligence
+ fine-tuning, or otherwise feeding into any artificial-intelligence
model or system. This includes, but is not limited to, usage as a
- training dataset for machine‑learning or deep‑learning models,
- model‑optimization, reinforcement‑learning, or any AI‑based analytics
+ training dataset for machine-learning or deep-learning models,
+ model-optimization, reinforcement-learning, or any AI-based analytics
pipeline.
• The Software may not be “scraped,” extracted, or otherwise harvested
@@ -24,8 +24,8 @@ condition:
All other rights granted under the MIT license remain in force, namely:
- • The Software may be used for any non‑AI purpose, including commercial
- or non‑commercial use, modification, distribution, private or public
+ • The Software may be used for any non-AI purpose, including commercial
+ or non-commercial use, modification, distribution, private or public
deployment, and so on.
• The Software is provided “as is,” without warranty of any kind,
diff --git a/README.md b/README.md
index 5c963ba..557228f 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,9 @@
# 📦 Epoch Forge (`epoch_forge`)
-> **A Rust‑powered CLI for managing fantasy organisations across time.**
-> *Think of it as a living, breathing world‑state engine that lets you “rewind”, “fast‑forward”, and **alter** the history of guilds, towns, wars, and characters.*
+> **A Rust-powered CLI for managing fantasy organisations across time.**
+> *Think of it as a living, breathing world-state engine that lets you “rewind”, “fast-forward”, and **alter** the history of guilds, towns, wars, and characters.*
-> 🚀 *Fast, type‑safe, and fully testable.*
+> 🚀 *Fast, type-safe, and fully testable.*
## ✨ Quick start
@@ -40,19 +40,19 @@ cat world.json
| Feature | What it gives you | Where it lives |
|---------|------------------|----------------|
| **Epoch management** | Switch, advance, or rewind the timeline | `core::epoch` |
-| **Event handling** | Add/remove world‑shaping events (storms, festivals, wars) | `core::event` |
+| **Event handling** | Add/remove world-shaping events (storms, festivals, wars) | `core::event` |
| **Organisation CRUD** | Guilds, factions, corporations | `core::org` |
| **Character CRUD** | Heroes, villains, NPCs | `core::character` |
| **Town CRUD** | Villages, cities, trade hubs | `core::town` |
| **Link network** | Alliances, wars, roads, trade routes | `core::link` |
-| **Persistence** | JSON/YAML stores, pluggable back‑ends | `core::storage` |
-| **CLI** | `efo` binary with sub‑commands | `efo` crate |
+| **Persistence** | JSON/YAML stores, pluggable back-ends | `core::storage` |
+| **CLI** | `efo` binary with sub-commands | `efo` crate |
| **Tests** | Unit & integration coverage | `tests/` |
### 📃 Quick reference table
-| Sub‑command | Usage | What it changes |
+| Sub-command | Usage | What it changes |
|-------------|-------|-----------------|
| `epoch` | `efo epoch --init`
`efo epoch --advance N`
`efo epoch --target ID` | Creates a world; moves time forward or back. |
| `event` | `efo event add ...`
`efo event remove ...` | Adds or removes an event. |
diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml
index d381520..9537697 100644
--- a/bin_efo/Cargo.toml
+++ b/bin_efo/Cargo.toml
@@ -10,3 +10,6 @@ clap = {workspace = true}
thiserror = {workspace = true}
serde_json = {workspace = true}
miette = {workspace = true}
+env_logger = {workspace = true}
+log = {workspace = true}
+derive_more = {workspace = true}
diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs
index 507983a..83357b0 100644
--- a/bin_efo/src/commands.rs
+++ b/bin_efo/src/commands.rs
@@ -1,11 +1,19 @@
//! # `commands` module
//!
-//! This module is the entry point for all CLI sub‑commands of the `efo` binary.
-//! Each sub‑command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its
-//! own file inside this directory and is re‑exported here so that the main
+//! This module is the entry point for all CLI sub-commands of the `efo` binary.
+//! Each sub-command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its
+//! own file inside this directory and is re-exported here so that the main
//! `efo::main.rs` can simply `use commands::*;` and dispatch based on the
-//! clap‑parsed enum.
+//! clap-parsed enum.
+
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
pub mod epoch;
-pub mod error;
+pub mod generate;
pub mod init;
+pub mod show;
+// pub mod diff;
+// pub mod utils;
+// pub mod event;
+// pub mod town;
+// pub mod chr;
diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs
index 587f283..930d1a7 100644
--- a/bin_efo/src/commands/epoch.rs
+++ b/bin_efo/src/commands/epoch.rs
@@ -1,80 +1,226 @@
-//! # `epoch` sub‑command
+//! # `epoch` sub-command
//!
-//! Handles all epoch‑related logic – logging, switching, computing the
+//! Handles all epoch-related logic - logging, switching, computing the
//! next epoch, and resetting future events.
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+use crate::{
+ error::AppError,
+ success::{SuccessMessages, display_success},
+};
use lib_efo::{
- epoch_struct::{ConfigWritable, EpochConfig},
+ epoch::{EpochConfig, EpochId, epoch_traits::ConfigWritable},
error::EpochError,
};
-
-use crate::error::AppError;
+use log::{debug, info};
pub mod cli_epoch;
-/// **Public entry point used by `efo::main`** – dispatches to the real
+
+/// **Public entry point used by `efo::main`** - dispatches to the real
/// handler that lives in `crate::world::EpochManager`.
-pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> {
+///
+/// # Arguments
+/// * `cmd` - The command to execute. This is an enum that represents
+/// one of the possible sub-commands for the `epoch` feature.
+///
+/// # Returns
+/// * `Ok(())` on success.
+/// * `Err(AppError)` if any step of the command handling fails.
+///
+/// # Examples
+/// ```no_run
+/// // Create a command to switch to epoch 3.
+/// let cmd = cli_epoch::EpochCmd::Switch(cli_epoch::Switch { target: 3 });
+/// // Execute the command.
+/// let result = handle_cmd(cmd);
+/// assert!(result.is_ok());
+/// ```
+///
+/// The function never panics under normal operation. All errors are
+/// reported via the returned `Result`.
+pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
- // TODO: Remove this debug
- println!("The main epoch is {:#?}", main_epoch);
+ // // TODO[2]: Remove this debug
+ debug!("The main epoch befor any action is {:#?}", main_epoch);
match cmd {
- cli_epoch::EpochCmd::Log(args) => handle_log(args),
+ cli_epoch::EpochCmd::Log(args) => handle_log(args, &mut main_epoch),
cli_epoch::EpochCmd::Switch(args) => handle_switch(args, &mut main_epoch),
- cli_epoch::EpochCmd::Next(args) => handle_next(args),
+ cli_epoch::EpochCmd::Next(args) => handle_next(args, &mut main_epoch),
cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch),
cli_epoch::EpochCmd::Diff(args) => handle_diff(args),
cli_epoch::EpochCmd::Tag(args) => handle_taging(args, &mut main_epoch),
- }
+ cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch),
+ cli_epoch::EpochCmd::Summary(args) => handle_summary(args, &mut main_epoch),
+ }?;
+
+ info!("The main epoch after all actions is {:#?}", main_epoch);
+ Ok(())
}
-fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> {
+/// Edits the summary for the current epoch.
+///
+/// The function loads the epoch that is currently active in
+/// `main_epoch`, then replaces its `summary` field with the value
+/// supplied in `args.summary`. The epoch map in `main_epoch` is
+/// modified in place.
+///
+/// This helper is internal to the `epoch` sub-command and is not part
+/// of the public API.
+fn handle_summary(args: &cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
+ let epoch_id = main_epoch.epoch_id;
+ main_epoch.try_load(&epoch_id)?;
+ #[allow(clippy::unwrap_used)] // The epoch_id must exists at this point
+ if let Some(epoch) = main_epoch.list_existing_epochs.get_mut(&epoch_id).unwrap() {
+ epoch.summary = args.summary.clone();
+ epoch.save_with_context("Saving new summary", &lib_efo::epoch::SaveMode::Erase)?;
+ display_success(&SuccessMessages::ChangedSummary(
+ epoch_id,
+ args.summary.clone(),
+ ));
+ }
+
+ Ok(())
+}
+
+/// Show a diff between two epochs.
+///
+/// Currently unimplemented. The function is a placeholder until a
+/// world-level diff algorithm is available.
+///
+/// This helper is internal to the `epoch` sub-command and is not part
+/// of the public API.
+fn handle_diff(args: &cli_epoch::Diff) -> Result<(), AppError> {
let _ = args;
unimplemented!("Blocker: There is actually no way to diff the world yet")
}
-fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> {
- println!("Epoch log (most recent first):");
- unimplemented!("Just needs for the epoch to implement lvels of displays trait: DisplayLevels");
+/// Show a log of all epochs up to the current one.
+///
+/// The function collects the identifiers of all epochs that are
+/// less than or equal to the currently active epoch (`main_epoch.epoch_id`),
+/// sorts them, and then asks the configuration to log the elements
+/// up to the supplied limit. The log is written by the
+/// underlying `EpochConfig::log_elements` implementation.
+///
+/// This helper is internal to the `epoch` sub-command.
+fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
+ let limit = args.limit;
+ let start_id = &main_epoch.epoch_id;
+
+ let mut list_id: Vec = main_epoch
+ .list_existing_epochs
+ .iter()
+ .filter(|(id, _)| id <= &start_id)
+ .map(|(id, _)| *id)
+ .collect();
+ list_id.sort();
+ main_epoch.log_elements(&list_id[..std::cmp::min(list_id.len(), limit)])?;
+ Ok(())
}
-/// Switch the current epoch for another
-fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
+/// Switches the current epoch to the one specified by the user.
+///
+/// The function loads the target epoch, updates the epoch identifier
+/// in the configuration, and persists the change. It also prints a
+/// success message via `display_success`.
+///
+/// This helper is internal to the `epoch` sub-command.
+fn handle_switch(args: &cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let target = main_epoch.get(&args.target)?;
main_epoch.try_load(&target)?;
main_epoch.epoch_id = target;
- println!("Switched to epoch {:?}", target);
- main_epoch.save(
- "Saving modified epoch config".into(),
- lib_efo::epoch_struct::SaveMode::Erase,
+ main_epoch.save_with_context(
+ "Saving modified epoch config",
+ &lib_efo::epoch::SaveMode::Erase,
)?;
+ display_success(&SuccessMessages::EpochSwitchSuccess(target));
Ok(())
}
-fn handle_next(args: cli_epoch::Next) -> Result<(), AppError> {
- let _ = args;
- println!("⚡ Next",);
- unimplemented!("Missing logic to process a next event");
+/// Handle the `next` sub-command.
+///
+/// Advances the epoch to the next scheduled event. If the current
+/// configuration contains any epochs with an identifier larger than
+/// the current one, an error is returned - otherwise the next epoch
+/// is computed.
+///
+/// # Arguments
+/// * `main_epoch` - mutable reference to the current `EpochConfig`
+/// (the `cli_epoch::Next` argument is unused).
+///
+/// # Returns
+/// * `Ok(())` if the next epoch was successfully computed.
+/// * `Err(AppError::Epoch(EpochError::FutureEpochExist))` if there are
+/// no future epochs to advance to.
+fn handle_next(_args: &cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
+ let current_id = main_epoch.epoch_id;
+
+ // Check that there are no future epochs
+ if main_epoch
+ .list_existing_epochs
+ .keys()
+ .any(|id| id > ¤t_id)
+ {
+ Err(AppError::Epoch(EpochError::FutureEpochExist))
+ } else {
+ let new_epoch = main_epoch.compute_next()?;
+ let new_id = new_epoch.epoch_id;
+
+ // Insert new epoch
+ main_epoch.insert_and_save(new_epoch, &lib_efo::epoch::SaveMode::DoNotErase)?;
+ display_success(&SuccessMessages::EpochNextSuccess(current_id, new_id));
+ Ok(())
+ }
}
-/// Reset all future events by deleting them
-fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
+/// Handle the `reset` sub-command.
+///
+/// Deletes all epochs whose identifier is greater than the current one,
+/// effectively rolling back to the present epoch.
+///
+/// # Arguments
+/// * `main_epoch` - mutable reference to the current `EpochConfig`
+/// (the `cli_epoch::Reset` argument is unused).
+///
+/// # Returns
+/// * `Ok(())` if all future epochs were successfully removed.
+/// * `Err(AppError)` if any deletion fails.
+fn handle_reset(args: &cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let _ = args;
let current_id = main_epoch.epoch_id;
+ // for id in main_epoch
for id in main_epoch
.list_existing_epochs
.keys()
.filter(|&k| k > ¤t_id)
+ .copied()
+ // Middle step necessary for borrowing purposes
+ .collect::>()
{
- main_epoch.delete_id(*id)?
+ main_epoch.delete_id(id)?
}
- println!("All future events deleted – back to epoch {current_id}",);
+ display_success(&SuccessMessages::DeletedAllFutureEvents(current_id));
Ok(())
}
-/// Adds a tag to the current epoch
-fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
+/// Handle the `tag` sub-command.
+///
+/// Adds a tag to the current epoch. The tag must not already exist
+/// elsewhere in the configuration; otherwise an error is returned.
+///
+/// # Arguments
+/// * `args` - `cli_epoch::Tag` containing the tag to add.
+/// * `main_epoch` - mutable reference to the current `EpochConfig`.
+///
+/// # Returns
+/// * `Ok(())` if the tag was successfully added.
+/// * `Err(AppError::Epoch(EpochError::TagAlreadyExists))` if the tag
+/// already exists in another epoch.
+/// * `Err(AppError::Epoch(EpochError::Unknown))` if the epoch cannot
+/// be found or saved.
+fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
// Load into memory the current epoch
main_epoch.try_load(&main_epoch.epoch_id.clone())?;
@@ -87,22 +233,21 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(
}
// Modify the epoch to add the tag inside
+ #[allow(clippy::unwrap_used)]
if let Some(current_epoch_info) = main_epoch
.list_existing_epochs
.get_mut(&main_epoch.epoch_id)
.unwrap()
{
current_epoch_info.tags.push(args.tag.clone());
- current_epoch_info.save(
- "Saving modified epoch".to_owned(),
- lib_efo::epoch_struct::SaveMode::Erase,
- )?;
+ current_epoch_info
+ .save_with_context("Saving modified epoch", &lib_efo::epoch::SaveMode::Erase)?;
main_epoch
.tags
.insert(args.tag.clone(), main_epoch.epoch_id);
- main_epoch.save(
- "Saving modified main config".into(),
- lib_efo::epoch_struct::SaveMode::Erase,
+ main_epoch.save_with_context(
+ "Saving modified main config",
+ &lib_efo::epoch::SaveMode::Erase,
)?;
Ok(())
} else {
@@ -111,3 +256,18 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(
)))
}
}
+
+/// Perform a filesystem consistency check on the epoch data.
+///
+/// The function invokes the internal consistency-check logic of
+/// `EpochConfig`. It is intended for use from the `fsck` sub-command
+/// and does **not** modify the current epoch. Any problems that
+/// are detected are reported through the returned `Result`; the
+/// command may also print a diagnostic message to the user.
+///
+/// This helper is internal to the `epoch` sub-command.
+fn handle_fsck(args: &cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
+ let _ = main_epoch;
+ let _ = args;
+ unimplemented!()
+}
diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs
index 25b53a4..63e9f8b 100644
--- a/bin_efo/src/commands/epoch/cli_epoch.rs
+++ b/bin_efo/src/commands/epoch/cli_epoch.rs
@@ -1,10 +1,30 @@
-use clap::{Args, Subcommand};
-use lib_efo::epoch_struct::EpochIdentifier;
+//! # `epoch` CLI module
+//!
+//! This module defines the command-line interface for the `efo epoch`
+//! sub-command.
+//!
+//! ## Overview of commands
+//!
+//! * **`log`** - list epochs in a git-log style.
+//! * **`switch`** - switch to a specific epoch (by id, name or tag).
+//! * **`next`** - compute the next epoch from the current one.
+//! * **`reset`** - delete all future events after the current epoch.
+//! * **`diff`** - show differences between two epochs.
+//! * **`tag`** - add a tag to the current epoch.
+//! * **`fsck`** - perform basic filesystem level maintenance.
-/// The outer clap entry that the binary will dispatch to
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+
+use clap::{Args, Subcommand};
+use lib_efo::epoch::EpochIdentifier;
+
+/// Top-level sub-command for the `efo epoch` command.
+///
+/// Each variant represents a distinct epoch operation that can be
+/// invoked from the command line.
#[derive(Subcommand, Debug)]
pub enum EpochCmd {
- /// List all epochs – a git‑log style view
+ /// List all epochs - a git-log style view
Log(Log),
/// Switch to an epoch (by numeric ID, name, or tag)
@@ -18,12 +38,22 @@ pub enum EpochCmd {
/// Show the differences between two epochs
Diff(Diff),
- // Tag and next could be implemented as subcommands of epoch
- // even if they barely belong here
+
+ /// Add a tag to the current epoch
Tag(Tag),
+
+ /// Basic filesystem level maintenance
+ Fsck(Fsck),
+
+ /// Edits the summary for the current epoch
+ Summary(Summary),
}
-/// `efo epoch log`
+/// Displays a git-log style list of epochs.
+///
+/// # Arguments
+/// * `limit` - (Optional) Limit the number of entries shown.
+/// Default: `50`.
#[derive(Args, Debug)]
pub struct Log {
/// (Optional) Limit the number of entries shown.
@@ -31,27 +61,37 @@ pub struct Log {
pub limit: usize,
}
-/// `efo epoch switch `
+/// Switches to the specified epoch. The target can be an integer,
+/// a name, or a tag.
+///
+/// # Arguments
+/// * `target` - The epoch to switch to.
+/// * `force` - If set, drops all pending work and forces the switch.
#[derive(Args, Debug)]
pub struct Switch {
- /// The epoch to switch to – can be an integer, a name, or a tag.
+ /// The epoch to switch to - can be an integer, a name, or a tag.
#[arg(required = true)]
pub target: EpochIdentifier,
- /// Optional confirmation flag (if you ever want to force‑switch)
- #[arg(long, short, help = "Force‑switch dropping all the pending work")]
+ /// Optional confirmation flag (if you ever want to force-switch)
+ #[arg(long, short, help = "Force-switch dropping all the pending work")]
pub force: bool,
}
-/// `efo epoch next`
+/// Computes the next epoch from the current one.
#[derive(Args, Debug)]
pub struct Next;
-/// `efo epoch reset`
+/// Deletes all future events after the current epoch.
#[derive(Args, Debug)]
pub struct Reset;
-/// `efo epoch diff `
+/// Shows the differences between two epochs.
+///
+/// # Arguments
+/// * `start` - The starting point to compute the differences.
+/// * `end` - The end point to compute the differences; defaults to the
+/// current epoch if omitted.
#[derive(Args, Debug)]
pub struct Diff {
#[arg(required = true)]
@@ -62,10 +102,25 @@ pub struct Diff {
pub end: Option,
}
-/// `efo epoch tag "tag"`
+/// Adds a tag to the current epoch.
+///
+/// # Arguments
+/// * `tag` - The tag to tag the current epoch with.
#[derive(Args, Debug)]
pub struct Tag {
#[arg(required = true)]
- /// The tag to tag the current epoch with
+ #[allow(clippy::missing_docs_in_private_items)]
pub tag: String,
}
+
+/// Performs basic filesystem level maintenance.
+#[derive(Debug, Args)]
+pub struct Fsck {}
+
+/// Edits the current's epoch summary.
+#[derive(Debug, Args)]
+pub struct Summary {
+ #[arg(required = true)]
+ #[allow(clippy::missing_docs_in_private_items)]
+ pub summary: String,
+}
diff --git a/bin_efo/src/commands/error.rs b/bin_efo/src/commands/error.rs
deleted file mode 100644
index d4ba9bd..0000000
--- a/bin_efo/src/commands/error.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-//! Error types that can arise while manipulating epochs.
-//!
-//! These errors are returned by the `epoch` sub‑command handlers and
-//! the underlying `EpochManager`. They are lightweight, strongly‑typed
-//! and can be converted into a top‑level error with `thiserror`.
-
-// use thiserror::Error;
diff --git a/bin_efo/src/commands/generate.rs b/bin_efo/src/commands/generate.rs
new file mode 100644
index 0000000..c878639
--- /dev/null
+++ b/bin_efo/src/commands/generate.rs
@@ -0,0 +1,18 @@
+//! Subcommand for fast generating ideas and displaying them
+//! This module does not add any structure (that would be either the prerogative of the bulk generator or the individual modules)
+
+use clap::Subcommand;
+
+use crate::error::AppError;
+/// The types of examples to generate
+#[derive(Subcommand, Debug)]
+pub enum GenCmd {
+ /// Generate a character
+ Character,
+}
+
+/// Handle all the generation
+pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> {
+ let _ = cmd;
+ Ok(())
+}
diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs
index 8e5527f..f6bea46 100644
--- a/bin_efo/src/commands/init.rs
+++ b/bin_efo/src/commands/init.rs
@@ -1,23 +1,49 @@
+//! # `init` module
+//!
+//! Provides the implementation of the `init` sub-command for the
+//! command-line interface. The sub-command creates an empty
+//! repository, writes the default configuration (`.epoch`),
+//! and sets up the first epoch (epoch 0).
+//!
+//! The main public API consists of:
+//!
+//! * `InitCmd` - a struct containing the command-line arguments.
+
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+
use clap::Args;
-use lib_efo::epoch_struct::{ConfigWritable, EpochInfo};
-use lib_efo::{epoch_struct::EpochConfig, error::EpochError};
+use lib_efo::{
+ epoch::{EpochConfig, EpochInfo, epoch_traits::ConfigWritable},
+ error::EpochError,
+};
use std::fs::read_dir;
-use crate::error::AppError;
+use crate::{
+ error::AppError,
+ success::{SuccessMessages, display_success},
+};
#[derive(Args, Debug)]
+
+/// Arguments for the `init` subcommand.
+///
+/// The `--force` flag forces initialisation even when the target
+/// directory already contains files.
pub struct InitCmd {
/// Force initialisation even if the directory isn't empty
#[arg(long)]
force: bool,
}
-/// Init an empty repository
+/// Initialise an empty repository.
+///
+/// Creates the default `EpochConfig`, verifies that the target directory
+/// is empty, and writes the initial configuration and epoch data.
+//TODO[5]: Upholster the logic behind force and empty detection
pub fn init(args: &InitCmd) -> Result<(), AppError> {
let epoch_config = EpochConfig::default();
let root = epoch_config.save_folder();
- //TODO: This can be really deceiving when only .epoch is present
if read_dir(root)?.count() != 0 {
Err(EpochError::FolderNotEmpty {
name: None,
@@ -26,9 +52,9 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> {
}
init_epoch(args)?;
epoch_config
- .save(
- "Creatig initial config".into(),
- lib_efo::epoch_struct::SaveMode::DoNotErase,
+ .save_with_context(
+ "Creatig initial config",
+ &lib_efo::epoch::SaveMode::DoNotErase,
)
.map_err(|_| EpochError::AlreadyInitialized {
advice: Some(
@@ -36,16 +62,21 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> {
.to_string(),
),
})?;
+
+ display_success(&SuccessMessages::FolderInitializedSuccessfully("."));
Ok(())
}
-/// Tries to init the epoch 0
+/// Helper that creates the initial epoch (epoch 0).
+///
+/// This function is not part of the public API; it is kept internal
+/// to `init`. It creates an empty `EpochInfo`, crea
fn init_epoch(_args: &InitCmd) -> Result<(), AppError> {
let empty = EpochInfo::default();
_ = empty.create_subfolders();
- empty.save(
- "Creating empty epoch file 0".into(),
- lib_efo::epoch_struct::SaveMode::DoNotErase,
+ empty.save_with_context(
+ "Creating empty epoch file 0",
+ &lib_efo::epoch::SaveMode::DoNotErase,
)?;
Ok(())
}
diff --git a/bin_efo/src/commands/show.rs b/bin_efo/src/commands/show.rs
new file mode 100644
index 0000000..39575d0
--- /dev/null
+++ b/bin_efo/src/commands/show.rs
@@ -0,0 +1,38 @@
+//! The show commands
+//! Used to display structures with various degree of verbosity
+
+use clap::Subcommand;
+use lib_efo::{Displayable, entity::Entity, naming::NAMING};
+
+use crate::error::AppError;
+#[derive(Subcommand, Debug)]
+/// Show command
+pub enum ShowCmd {
+ /// Show an event
+ Event,
+}
+
+/// Handle all show cmds
+pub fn handle_show_cmd(cmd: &ShowCmd) -> Result<(), AppError> {
+ let _ = cmd;
+ let mut e = Entity::default();
+ e.name = NAMING.generate_long_character_name();
+ println!("Original Struct: \n{e:#?}");
+ println!("\n\n\nONELINES");
+ println!("{}", e.oneline_display());
+ println!("{}", e.oneline_display());
+ println!("{}", e.oneline_display());
+ println!("{}", e.oneline_display());
+ println!("{}", e.oneline_display());
+ println!("{}", e.oneline_display());
+ println!("{}", e.oneline_display());
+ println!("\n\n\n SHORT");
+ e.print_short();
+
+ println!("\n\n\n LONG");
+ e.print_full();
+ println!("\n\n\n TREE");
+ println!("{}", e.to_pretty_tree());
+
+ Ok(())
+}
diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs
index 9820956..cf2e886 100644
--- a/bin_efo/src/error.rs
+++ b/bin_efo/src/error.rs
@@ -1,7 +1,9 @@
//! General error type that the CLI propagates.
//!
//! `AppError` aggregates all error kinds that may surface during a command
-//! execution: parsing, I/O, epoch logic, storage, and a catch‑all.
+//! execution: parsing, I/O, epoch logic, storage, and a catch-all.
+
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use lib_efo::error::{EpochError, StorageError};
use miette::Diagnostic;
@@ -11,8 +13,8 @@ use thiserror::Error;
#[derive(Debug, Error, Diagnostic)]
#[allow(dead_code)]
pub enum AppError {
- /// Generic “invalid command / missing flag” – emitted by clap.
- #[error("Command‑line error: {0}")]
+ /// Generic “invalid command / missing flag” - emitted by clap.
+ #[error("Command-line error: {0}")]
// #[diagnostic(transparent)]
Clap(#[from] clap::Error),
@@ -21,17 +23,17 @@ pub enum AppError {
// #[diagnostic(transparent)]
Io(#[from] std::io::Error),
- /// Domain‑specific problems (see `EpochError`).
+ /// Domain-specific problems (see `EpochError`).
#[error("Epoch error:")]
#[diagnostic(transparent)]
Epoch(#[from] EpochError),
- /// Storage‑layer (e.g. DB) errors.
+ /// Storage-layer (e.g. DB) errors.
#[error("Storage error: {0}")]
// #[diagnostic(transparent)]
Storage(#[from] StorageError),
- /// Anything else we didn’t anticipate.
+ /// Anything else we didn't anticipate.
#[error("Unknown error: {0}")]
Other(String),
}
diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs
index d5e4391..e86fc23 100644
--- a/bin_efo/src/main.rs
+++ b/bin_efo/src/main.rs
@@ -1,16 +1,16 @@
//! # `efo`
//!
-//! The **command‑line interface** for `epoch_forge`. It exposes a single
-//! binary `efo` that supports the following sub‑commands:
+//! The **command-line interface** for `epoch_forge`. It exposes a single
+//! binary `efo` that supports the following sub-commands:
//!
-//! - `epoch` – switch / advance time
-//! - `event` – add / remove events
-//! - `org` – add / remove organisations
-//! - `chr` – add / remove characters
-//! - `town` – add / remove towns
-//! - `link` – add / remove links (alliances, wars, roads, etc.)
+//! - `epoch` - switch / advance time
+//! - `event` - add / remove events
+//! - `org` - add / remove organisations
+//! - `chr` - add / remove characters
+//! - `town` - add / remove towns
+//! - `link` - add / remove links (alliances, wars, roads, etc.)
//!
-//! Each sub‑command is implemented in its own module under `commands/`.
+//! Each sub-command is implemented in its own module under `commands/`.
//! The `main.rs` file simply parses arguments with `clap` and dispatches
//! to the appropriate handler. The handlers share a common `World`
//! instance that they load from / persist to disk.
@@ -19,63 +19,98 @@
//! ```sh
//! efo epoch switch 5
//! ```
-use clap::{Parser, Subcommand};
-use crate::commands::init::InitCmd;
-use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError};
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+#![deny(clippy::unwrap_used)]
+
+use std::fmt::Debug;
+
+use clap::{ArgAction, Parser, Subcommand};
+
+use crate::{
+ commands::{epoch::cli_epoch::EpochCmd, generate::GenCmd, init::InitCmd, show::ShowCmd},
+ error::AppError,
+};
mod commands;
mod error;
+mod success;
-/// Root parser – the “efo” program
+/// The root command-line parser for the `efo` binary.
+///
+/// It uses `clap` to parse the top-level sub-commands (`init`, `epoch`, …)
+/// and stores them in the `command` field.
#[derive(Parser, Debug)]
#[command(name = "efo")]
-#[command(about = "Epoch Forge – manage organisations over time")]
+#[command(about = "Epoch Forge - manage organisations over time")]
struct Cli {
+ /// The level of verbosity
+ #[arg(short, long, action = ArgAction::Count, global = true)]
+ verbose: u8,
+
#[command(subcommand)]
+ /// The top level command to be executed
command: TopLevelCmd,
}
+/// Enumeration of the top-level sub-commands that `efo` accepts.
+///
+/// Each variant corresponds to a single sub-command and holds its own
+/// argument structure.
#[derive(Subcommand, Debug)]
enum TopLevelCmd {
+ /// Initialise a new epoch folder.
Init(InitCmd),
+ /// Advance or query the current epoch.
#[command(subcommand)]
Epoch(EpochCmd),
+ /// Display some elements
+ #[command(subcommand)]
+ Show(ShowCmd),
// Event(commands::event::EventCmd),
// Org(commands::org::OrgCmd),
// Chr(commands::chr::ChrCmd),
// Town(commands::town::TownCmd),
// Link(commands::link::LinkCmd),
+ #[command(subcommand)]
+ /// Generate random structures and display them
+ Gen(GenCmd),
}
+/// Program entry point.
+///
+/// Parses the command-line arguments and dispatches to the selected
+/// sub-command. Errors returned by the sub-command handlers are shown
+/// in stdout and returned as a `miette::Result<()>`.
fn main() -> miette::Result<()> {
+ env_logger::init();
+
let cli = Cli::parse();
if let Err(e) = exec_dispatch(cli) {
- // match e{
- // AppError::Clap(error) => todo!(),
- // AppError::Io(error) => todo!(),
- // AppError::Epoch(epoch_error) => todo!(),
- // AppError::Storage(storage_error) => todo!(),
- // AppError::Other(_) => todo!(),
- // }
- println!("The program didn't exit properly and returned the following error:");
- // println!("{}", e);
Err(e)?;
}
Ok(())
}
+/// Dispatches the parsed command to the appropriate handler.
+///
+/// # Arguments
+/// * `cli` - The parsed command-line options.
+///
+/// # Returns
+/// * `Ok(())` on success.
+/// * `Err(AppError)` if the chosen sub-command handler fails.
+///
+/// The function matches on the `TopLevelCmd` variant and calls the
+/// corresponding handler in the `commands` module. Any error is
+/// propagated to the caller, which in `main` will be shown to
+/// stdout and returned as a `miette::Result<()>`.
fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
match cli.command {
- TopLevelCmd::Init(cmd) => {
- commands::init::init(&cmd)?;
- println!("The folder was initialized as an epoch folder")
- }
- TopLevelCmd::Epoch(cmd) => {
- commands::epoch::handle_cmd(cmd)?;
- // println!("")
- }
+ TopLevelCmd::Init(cmd) => commands::init::init(&cmd),
+ TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd),
+ TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd),
+ TopLevelCmd::Gen(cmd) => commands::generate::gen_handler(&cmd),
}
- Ok(())
}
diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs
new file mode 100644
index 0000000..60ffc71
--- /dev/null
+++ b/bin_efo/src/success.rs
@@ -0,0 +1,28 @@
+//! List of all success messages possible
+
+use derive_more::Display;
+use lib_efo::epoch::EpochId;
+
+#[derive(Display, Clone, Debug)]
+#[allow(missing_docs, clippy::missing_docs_in_private_items)]
+pub enum SuccessMessages {
+ #[display("Switched to epoch {_0}")]
+ EpochSwitchSuccess(lib_efo::epoch::EpochId),
+
+ #[display("All future events deleted - back to epoch {_0}")]
+ DeletedAllFutureEvents(lib_efo::epoch::EpochId),
+
+ #[display("The folder was initialized as an epoch folder")]
+ FolderInitializedSuccessfully(&'static str),
+
+ #[display("Changed the summary of epoch {_0} with: '{_1}'")]
+ ChangedSummary(EpochId, String),
+
+ #[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")]
+ EpochNextSuccess(EpochId, EpochId),
+}
+
+/// Display the success message to stdout
+pub fn display_success(message: &SuccessMessages) {
+ println!("{}", message)
+}
diff --git a/config.toml b/config.toml
new file mode 100644
index 0000000..ee4de04
--- /dev/null
+++ b/config.toml
@@ -0,0 +1,7 @@
+[[patterns]]
+regex = "\\p{Pd}"
+replacement = "-"
+[[patterns]]
+regex = "[\u2018\u2019\u201A\u201B\u02BC\u02BB\u00B4\uFF40\uFF07]"
+replacement = "'"
+
diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml
index 9398e9c..624361b 100644
--- a/lib_efo/Cargo.toml
+++ b/lib_efo/Cargo.toml
@@ -9,3 +9,11 @@ serde = {workspace = true}
thiserror = {workspace = true}
clap = {workspace = true}
miette = {workspace = true}
+env_logger = {workspace = true}
+log = {workspace = true}
+derive_more = {workspace = true}
+cli-table = "0.5.0"
+uuid = { version = "1.18.1", features = ["serde", "v4"] }
+colored = "3.0.0"
+rand = "0.9.2"
+once_cell = "1.21.3"
diff --git a/lib_efo/naming.json b/lib_efo/naming.json
new file mode 100644
index 0000000..2bc4de8
--- /dev/null
+++ b/lib_efo/naming.json
@@ -0,0 +1,1350 @@
+{
+ "first_names": [
+ "Aeron",
+ "Brienne",
+ "Cedric",
+ "Darya",
+ "Eldon",
+ "Fiora",
+ "Galen",
+ "Hela",
+ "Ivor",
+ "Juno",
+ "Aldric",
+ "Briar",
+ "Caelum",
+ "Dorin",
+ "Elysia",
+ "Fendrel",
+ "Gryphon",
+ "Hector",
+ "Iseult",
+ "Kael",
+ "Lysander",
+ "Morgath",
+ "Nyx",
+ "Odin",
+ "Riven",
+ "Sylvan",
+ "Thorne",
+ "Valen",
+ "Wraith",
+ "Xander",
+ "Yara",
+ "Zarek",
+ "Artemis",
+ "Baldric",
+ "Corvin",
+ "Draven",
+ "Eira",
+ "Fenris",
+ "Gale",
+ "Helios",
+ "Ivy",
+ "Jasper",
+ "Kara",
+ "Luna",
+ "Mira",
+ "Nimrod",
+ "Onyx",
+ "Peregrine",
+ "Quinn",
+ "Aegon",
+ "Brek",
+ "Calandra",
+ "Darrion",
+ "Eryndor",
+ "Fenn",
+ "Galax",
+ "Hestia",
+ "Ilarion",
+ "Jareth",
+ "Kassandra",
+ "Lyris",
+ "Maelor",
+ "Nyssa",
+ "Oren",
+ "Phaedra",
+ "Quillon",
+ "Rhea",
+ "Soren",
+ "Thalia",
+ "Uther",
+ "Vesper",
+ "Wulfric",
+ "Xara",
+ "Yoren",
+ "Zorath",
+ "Aerith",
+ "Baldrick",
+ "Cress",
+ "Dazai",
+ "Elara",
+ "Fira"
+ ],
+ "last_names": [
+ "Ashwood",
+ "Blackthorn",
+ "Cinderglow",
+ "Dunwynn",
+ "Everfield",
+ "Frosthelm",
+ "Goldleaf",
+ "Holloway",
+ "Iverson",
+ "Jasper",
+ "Ravencrest",
+ "Stormblade",
+ "Nightshade",
+ "Wraithborne",
+ "Dreadmoor",
+ "Ironhart",
+ "Bloodstone",
+ "Stonegate",
+ "Gloomreach",
+ "Sablewick",
+ "Rookhaven",
+ "Ironcrest",
+ "Bleakmoor",
+ "Thornshield",
+ "Wyrmwood",
+ "Darkwater",
+ "Stormbreaker",
+ "Ebonhart",
+ "Bloodbane",
+ "Eclipseborne",
+ "Firethorn",
+ "Silvershade",
+ "Blackfrost",
+ "Sorrowblade",
+ "Stonehelm",
+ "Gravelock",
+ "Voidwalker",
+ "Nightfall",
+ "Ashenfall",
+ "Ashenridge",
+ "Duskfall",
+ "Thornhaven",
+ "Gloombreaker",
+ "Riftwalker",
+ "Althmar",
+ "Brimstone",
+ "Cinderfall",
+ "Duskbane",
+ "Emberforge",
+ "Frostbane",
+ "Grimsbane",
+ "Ironbark",
+ "Jaggedspire",
+ "Keldrith",
+ "Lament",
+ "Mistveil",
+ "Nightglow",
+ "Oathbreaker",
+ "Palegrave",
+ "Quicksilver",
+ "Riftshard",
+ "Shadowforge",
+ "Thornbane",
+ "Umbral",
+ "Vengeance",
+ "Wraithbane",
+ "Xylander",
+ "Yester",
+ "Zephyr",
+ "Blackfire",
+ "Bloodthorn",
+ "Crimsonveil",
+ "Dreadspire",
+ "Eboncrest",
+ "Firebrand",
+ "Grimshard",
+ "Ironheart",
+ "Javelin",
+ "Krait",
+ "Luminous",
+ "Marrowbone",
+ "Nocturne",
+ "Obsidian",
+ "Pyre",
+ "Quagmire",
+ "Reaver",
+ "Sableheart",
+ "Tidebreaker"
+ ],
+ "town_prefixes": [
+ "Ash",
+ "Bright",
+ "Cedar",
+ "Deep",
+ "Elder",
+ "Frost",
+ "Glen",
+ "High",
+ "Iron",
+ "Jade",
+ "Ashen",
+ "Blood",
+ "Cobalt",
+ "Dusk",
+ "Ebon",
+ "Gloom",
+ "Ironforge",
+ "Keen",
+ "Mourn",
+ "Raven",
+ "Storm",
+ "Void",
+ "Wraith",
+ "Night",
+ "Silvers",
+ "Black",
+ "Crimson",
+ "Fire",
+ "Grim",
+ "Briar",
+ "Obsidian",
+ "Shade",
+ "Thorn",
+ "Sable",
+ "Rift",
+ "Dread",
+ "Sorrow",
+ "Bleak",
+ "Eclipse",
+ "Eternity",
+ "Glint",
+ "Gleam",
+ "Hollow",
+ "Lament",
+ "Mire",
+ "Molt",
+ "Nocturne",
+ "Onyx",
+ "Pale",
+ "Rook",
+ "Shimmer",
+ "Stonem",
+ "Stone",
+ "Stonehold",
+ "Stonekeep",
+ "Stoneforge",
+ "Stormfall",
+ "Stormgate",
+ "Stormhold",
+ "Stormreach",
+ "Stormspire",
+ "Stormwind",
+ "Throne",
+ "Twilight",
+ "Valiant",
+ "Valest",
+ "Valer",
+ "Vex",
+ "Vile",
+ "Warden"
+ ],
+ "town_suffixes": [
+ "brook",
+ "dale",
+ "field",
+ "haven",
+ "keep",
+ "moor",
+ "port",
+ "reach",
+ "stone",
+ "vale",
+ "forge",
+ "shard",
+ "hollow",
+ "cove",
+ "hall",
+ "watch",
+ "spire",
+ "glade",
+ "cliff",
+ "glen",
+ "tower",
+ "fort",
+ "hold",
+ "bastion",
+ "crypt",
+ "crossing",
+ "crown",
+ "ridge",
+ "fell",
+ "breach",
+ "briar",
+ "bloom",
+ "field",
+ "river",
+ "canyon",
+ "fen",
+ "crag",
+ "gate",
+ "bridge",
+ "watchtower",
+ "watcher",
+ "mire",
+ "waste",
+ "breach",
+ "fall",
+ "crone",
+ "shadow",
+ "veil",
+ "blight",
+ "soul",
+ "night",
+ "storm",
+ "fire",
+ "ice",
+ "iron",
+ "dark",
+ "glimmer",
+ "glare",
+ "scar",
+ "scarred",
+ "spire",
+ "peak",
+ "ridge",
+ "hall",
+ "hold",
+ "spire",
+ "vale",
+ "vale",
+ "haven",
+ "hollow",
+ "breach",
+ "crust"
+ ],
+ "character_adjectives": [
+ "the Blind",
+ "the Magnificent",
+ "the Cunning",
+ "the Swift",
+ "the Stoic",
+ "the Fearless",
+ "the Enigmatic",
+ "the Shadow",
+ "the Light",
+ "the Wanderer",
+ "the Unbroken",
+ "the Relentless",
+ "the Ruthless",
+ "the Merciless",
+ "the Devourer",
+ "the Ancient",
+ "the Fallen",
+ "the Immortal",
+ "the Vengeful",
+ "the Stormborn",
+ "the Silent",
+ "the Bloodied",
+ "the Corrupt",
+ "the Darkened",
+ "the Ember",
+ "the Crimson",
+ "the Iron",
+ "the Sable",
+ "the Radiant",
+ "the Tempest",
+ "the Gloom",
+ "the Warlord",
+ "the Titan",
+ "the Behemoth",
+ "the Leviathan",
+ "the Doombringer",
+ "the Wraith",
+ "the Sundered",
+ "the Gloomstalker",
+ "the Blight",
+ "the Harbinger",
+ "the Abyssal",
+ "the Scourge",
+ "the Dread",
+ "the Fury",
+ "the Specter",
+ "the Maw",
+ "the Protector",
+ "the Guardian",
+ "the Champion",
+ "the Savior",
+ "the Reaper",
+ "the Harvester",
+ "the Seeker",
+ "the Whisperer",
+ "the Tempest-born",
+ "the Iron-clad",
+ "the Moonlit",
+ "the Sun-scarred",
+ "the Bone-choked",
+ "the Frost-kissed",
+ "the Ashen",
+ "the Shattered",
+ "the Echo-bound",
+ "the Vile",
+ "the Harsh",
+ "the Unseen",
+ "the Unyielding",
+ "of the North",
+ "of the South",
+ "of the East",
+ "of the West",
+ "of the Dark",
+ "of the Light",
+ "of the Forgotten",
+ "of the Broken",
+ "of the Eternal",
+ "of the Shadowlands",
+ "of the Burning",
+ "of the Frozen",
+ "of the Storm",
+ "of the Depths",
+ "of the Maw",
+ "of the Ashen Sea",
+ "of the Crimson Dawn"
+ ],
+ "character_prefixes": [
+ "Sir",
+ "Lady",
+ "Mighty",
+ "Elder",
+ "Grand",
+ "Humble",
+ "Radiant",
+ "Lord",
+ "High",
+ "Royal",
+ "Ancient",
+ "Warden",
+ "Seer",
+ "Master"
+ ],
+ "event_ideas": [
+ {
+ "name": "storm_flood",
+ "description": "A sudden storm floods the river, threatening the local farms.",
+ "stats": [
+ { "stat": "Population", "value": -5 },
+ { "stat": "Food", "value": -12 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 10, "max": 70 },
+ "strength": 20
+ },
+ {
+ "name": "earthquake",
+ "description": "A massive quake ripples across the region.",
+ "stats": [
+ { "stat": "Transportation", "value": -9 },
+ { "stat": "Sprawl", "value": -5 },
+ { "stat": "Health", "value": -3 },
+ { "stat": "Industry", "value": -2 },
+ { "stat": "Population", "value": -10 },
+ { "stat": "Happiness", "value": -8 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 10, "max": 110 },
+ "strength": 80
+ },
+
+ {
+ "name": "region_blood_monsoon",
+ "description": "A crimson rain falls over the region, poisoning crops and water sources.",
+ "stats": [
+ { "stat": "Food", "value": -18 },
+ { "stat": "Health", "value": -12 },
+ { "stat": "Population", "value": -7 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 10, "max": 110 },
+ "strength": 70
+ },
+
+ {
+ "name": "town_haunted_market",
+ "description": "Spectral merchants appear, selling cryptic ware from a bygone era.",
+ "stats": [
+ { "stat": "Trade", "value": 9 },
+ { "stat": "Science", "value": 9 },
+ { "stat": "Food", "value": 13 },
+ { "stat": "Crime", "value": 7 },
+ { "stat": "Threat", "value": 11 }
+ ],
+ "duration": { "Duration": 3 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 10, "max": 80 },
+ "strength": 60
+ },
+
+ {
+ "name": "region_darkening_sun",
+ "description": "The sky is shrouded in an unnatural pallid dusk, lowering morale and crop yields.",
+ "stats": [
+ { "stat": "Happiness", "value": -14 },
+ { "stat": "Food", "value": -10 },
+ { "stat": "Culture", "value": -5 }
+ ],
+ "duration": { "Duration": 6 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 75
+ },
+
+ {
+ "name": "town_giant_earthworm",
+ "description": "A colossal earthworm burrows beneath the town, destabilizing foundations and causing tremors.",
+ "stats": [
+ { "stat": "Food", "value": -5 },
+ { "stat": "Industry", "value": -2 },
+ { "stat": "Happiness", "value": -12 },
+ { "stat": "Fortification", "value": -8 },
+ { "stat": "Population", "value": -4 }
+ ],
+ "duration": { "Duration": 4 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 30, "max": 70 },
+ "strength": 65
+ },
+ {
+ "name": "region_arcane_surge",
+ "description": "An uncontrollable surge of raw sangressence tears through reality, causing unpredictable effects.",
+ "stats": [
+ { "stat": "Science", "value": 12 },
+ { "stat": "Education", "value": 8 },
+ { "stat": "Population", "value": -6 }
+ ],
+ "duration": { "Duration": 6 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 30, "max": 70 },
+ "strength": 80
+ },
+ {
+ "name": "town_mushroom_meteor",
+ "description": "A meteor of colossal fungi explodes over a town, releasing spores that induce vivid hallucinations.",
+ "stats": [
+ { "stat": "Health", "value": -10 },
+ { "stat": "Crime", "value": 6 },
+ { "stat": "Population", "value": -3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 60
+ },
+ {
+ "name": "region_infernal_flood",
+ "description": "Molten rivers run through the region, boiling over cities and devouring forests.",
+ "stats": [
+ { "stat": "Transportation", "value": -4 },
+ { "stat": "Sprawl", "value": -5 },
+ { "stat": "Happiness", "value": -19 },
+ { "stat": "Food", "value": -15 },
+ { "stat": "Population", "value": -12 }
+ ],
+ "duration": { "Duration": 5 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "region_sand_vortex",
+ "description": "A vortex of shifting sands sweeps the region, burying entire nations under dunes.",
+ "stats": [
+ { "stat": "Bureaucracy", "value": -14 },
+ { "stat": "Transportation", "value": -14 },
+ { "stat": "Sprawl", "value": -14 },
+ { "stat": "Population", "value": -16 },
+ { "stat": "Trade", "value": -10 }
+ ],
+ "duration": { "Duration": 5 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 65
+ },
+ {
+ "name": "region_wind_of_gods",
+ "description": "A relentless gale from the gods tears through the region, scattering armies and wrecking supply lines.",
+ "stats": [
+ { "stat": "Transportation", "value": -12 },
+ { "stat": "Army", "value": -9 },
+ { "stat": "Population", "value": -3 }
+ ],
+ "duration": { "Duration": 8 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 75
+ },
+ {
+ "name": "region_ancient_sunrise",
+ "description": "The sun rises in a crimson glow, amplifying the power of all dark cults and spreading fear.",
+ "stats": [
+ { "stat": "Crime", "value": 9 },
+ { "stat": "Happiness", "value": -8 },
+ { "stat": "Influence", "value": -5 }
+ ],
+ "duration": { "Duration": 7 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "town_forest_of_eyes",
+ "description": "A forest that watches every step, slowly siphoning the life force from any who walk through.",
+ "stats": [
+ { "stat": "Health", "value": -10 },
+ { "stat": "Crime", "value": 7 },
+ { "stat": "Happiness", "value": 7 },
+ { "stat": "Population", "value": -14 }
+ ],
+ "duration": { "Duration": 8 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 80
+ },
+ {
+ "name": "city_corruption_scandal",
+ "description": "A high-ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.",
+ "stats": [
+ { "stat": "Food", "value": -4 },
+ { "stat": "Industry", "value": -3 },
+ { "stat": "Science", "value": -3 },
+ { "stat": "Trade", "value": -8 },
+ { "stat": "Bureaucracy", "value": -7 },
+ { "stat": "Crime", "value": 7 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 22, "max": 86 },
+ "strength": 78
+ },
+ {
+ "name": "city_tax_reform",
+ "description": "The council implements a sweeping tax overhaul that raises revenue but triggers protests among merchants.",
+ "stats": [
+ { "stat": "Food", "value": 9 },
+ { "stat": "Industry", "value": 10 },
+ { "stat": "Science", "value": 7 },
+ { "stat": "Trade", "value": 13 },
+ { "stat": "Happiness", "value": -4 },
+ { "stat": "Crime", "value": 5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 25, "max": 92 },
+ "strength": 94
+ },
+ {
+ "name": "city_watch_mutiny",
+ "description": "The city guard, disgruntled by unpaid wages, mutinies turns bandits.",
+ "stats": [
+ { "stat": "Strength", "value": -6 },
+ { "stat": "Crime", "value": 8 },
+ { "stat": "Population", "value": -2 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 18, "max": 80 },
+ "strength": 66
+ },
+ {
+ "name": "city_water_contamination",
+ "description": "Tainted water leaks into the municipal supply, causing a sudden spike in illnesses.",
+ "stats": [
+ { "stat": "Health", "value": -14 },
+ { "stat": "Population", "value": -5 },
+ { "stat": "Bureaucracy", "value": -3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 21, "max": 88 },
+ "strength": 87
+ },
+ {
+ "name": "city_bureaucratic_bureaucracy",
+ "description": "A new procedural reform overhauls city administration, halting projects for months and stalling economic growth.",
+ "stats": [
+ { "stat": "Bureaucracy", "value": 14 },
+ { "stat": "Sprawl", "value": -9 },
+ { "stat": "Health", "value": -7 },
+ { "stat": "Food", "value": 3 },
+ { "stat": "Industry", "value": 2 },
+ { "stat": "Science", "value": 3 },
+ { "stat": "Trade", "value": 4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 90 },
+ "strength": 82
+ },
+ {
+ "name": "city_guild_suppression",
+ "description": "The council cracks down on the city's merchant guilds, confiscating goods and driving merchants underground.",
+ "stats": [
+ { "stat": "Trade", "value": -11 },
+ { "stat": "Crime", "value": 6 },
+ { "stat": "Population", "value": -3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 19, "max": 83 },
+ "strength": 68
+ },
+ {
+ "name": "city_civic_riot",
+ "description": "An assembly of disgruntled workers erupts into a violent riot, tearing through market stalls and public buildings.",
+ "stats": [
+ { "stat": "Trade", "value": -12 },
+ { "stat": "Happiness", "value": -9 },
+ { "stat": "Crime", "value": 10 }
+ ],
+ "duration": { "Duration": 2 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 25, "max": 95 },
+ "strength": 78
+ },
+ {
+ "name": "city_public_health_crisis",
+ "description": "A mysterious disease spreads through the city's crowded streets, overwhelming the local infirmaries.",
+ "stats": [
+ { "stat": "Health", "value": -3 },
+ { "stat": "Population", "value": -3 },
+ { "stat": "Happiness", "value": -2 }
+ ],
+ "duration": { "Duration": 6 },
+ "application": "Recurring",
+ "effect_bounds": { "min": 20, "max": 95 },
+ "strength": 71
+ },
+ {
+ "name": "city_transport_infrastructure_fail",
+ "description": "The city's main aqueduct collapses, cutting off water supply to half the districts.",
+ "stats": [
+ { "stat": "Transportation", "value": -15 },
+ { "stat": "Population", "value": -4 },
+ { "stat": "Bureaucracy", "value": -2 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "city_festival_corruption",
+ "description": "During a grand city festival, officials accept bribes to award contracts, compromising civic integrity.",
+ "stats": [
+ { "stat": "Bureaucracy", "value": -8 },
+ { "stat": "Crime", "value": 4 },
+ { "stat": "Happiness", "value": -3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "city_gold_exodus",
+ "description": "A sudden discovery of gold in the hinterlands draws merchants away, leaving local markets starved of currency.",
+ "stats": [
+ { "stat": "Food", "value": -4 },
+ { "stat": "Industry", "value": -4 },
+ { "stat": "Trade", "value": -8 },
+ { "stat": "Population", "value": -2 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "regional_drought",
+ "description": "An extended dry spell cripples crop yields, driving up food prices and crippling the agrarian economy.",
+ "stats": [
+ { "stat": "Food", "value": -15 },
+ { "stat": "Trade", "value": -13 },
+ { "stat": "Happiness", "value": -5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "city_tariff_levy",
+ "description": "The city council imposes a high tariff on imported goods to boost local industry, sparking backlash from merchants.",
+ "stats": [
+ { "stat": "Trade", "value": -10 },
+ { "stat": "Food", "value": -4 },
+ { "stat": "Industry", "value": -6 },
+ { "stat": "Science", "value": -3 },
+ { "stat": "Crime", "value": 15 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "market_hoarding",
+ "description": "A powerful merchant cartel hoards staple goods, manipulating prices to inflate profits at the cost of ordinary citizens.",
+ "stats": [
+ { "stat": "Food", "value": -7 },
+ { "stat": "Industry", "value": -6 },
+ { "stat": "Trade", "value": -7 },
+ { "stat": "Population", "value": -3 }
+ ],
+ "duration": { "Duration": 7 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+
+ {
+ "name": "industrial_explosion",
+ "description": "A catastrophic blast at the main ironworks destroys equipment and halts production for months.",
+ "stats": [
+ { "stat": "Industry", "value": -19 },
+ { "stat": "Food", "value": -3 },
+ { "stat": "Trade", "value": -7 },
+ { "stat": "Population", "value": -4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "foreign_investment_boom",
+ "description": "A foreign dynasty invests heavily in local mining, sparking a surge in jobs and wealth but also widening inequality.",
+ "stats": [
+ { "stat": "Industry", "value": 12 },
+ { "stat": "Science", "value": 3 },
+ { "stat": "Trade", "value": 8 },
+ { "stat": "Crime", "value": 5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 20, "max": 90 },
+ "strength": 70
+ },
+ {
+ "name": "tax_evasion_scheme",
+ "description": "A sophisticated tax evasion network siphons off a large portion of city revenue, forcing austerity measures.",
+ "stats": [
+ { "stat": "Food", "value": -8 },
+ { "stat": "Industry", "value": -7 },
+ { "stat": "Trade", "value": -9 },
+ { "stat": "Crime", "value": 15 },
+ { "stat": "Bureaucracy", "value": -6 },
+ { "stat": "Population", "value": -2 }
+ ],
+ "duration": { "Duration": 6 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 25, "max": 95 },
+ "strength": 81
+ },
+ {
+ "name": "currency_devaluation",
+ "description": "The city's coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.",
+ "stats": [
+ { "stat": "Food", "value": -8 },
+ { "stat": "Industry", "value": -3 },
+ { "stat": "Trade", "value": -9 },
+ { "stat": "Health", "value": -4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 76
+ },
+ {
+ "name": "artisan_fair_success",
+ "description": "A grand artisan fair attracts wealthy patrons, boosting local crafts and increasing export revenues.",
+ "stats": [
+ { "stat": "Industry", "value": 8 },
+ { "stat": "Industry", "value": 9 },
+ { "stat": "Trade", "value": 9 },
+ { "stat": "Population", "value": 2 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "resource_piracy",
+ "description": "Sea-borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.",
+ "stats": [
+ { "stat": "Trade", "value": -12 },
+ { "stat": "Food", "value": -7 },
+ { "stat": "Industry", "value": -6 },
+ { "stat": "Threat", "value": 3 },
+ { "stat": "Crime", "value": 14 }
+ ],
+ "duration": { "Duration": 4 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 25, "max": 95 },
+ "strength": 80
+ },
+ {
+ "name": "steel_furnace_overheat",
+ "description": "A critical failure in the city's primary steel furnace sparks an uncontrollable fire, destroying production lines.",
+ "stats": [
+ { "stat": "Industry", "value": -17 },
+ { "stat": "Trade", "value": -9 },
+ { "stat": "Happiness", "value": -2 },
+ { "stat": "Population", "value": -3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 24, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "artisan_tech_innovation",
+ "description": "A guild of master craftsmen invents a new forging technique that doubles output and lowers raw material usage.",
+ "stats": [
+ { "stat": "Industry", "value": 14 },
+ { "stat": "Industry", "value": 13 },
+ { "stat": "Science", "value": 15 },
+ { "stat": "Trade", "value": 9 },
+ { "stat": "Crime", "value": 3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 26, "max": 95 },
+ "strength": 83
+ },
+ {
+ "name": "coal_mine_sabotage",
+ "description": "Covert saboteurs collapse a major coal shaft, halting fuel supply to all local factories for weeks.",
+ "stats": [
+ { "stat": "Industry", "value": -15 },
+ { "stat": "Crime", "value": 6 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "foreign_factory_purchase",
+ "description": "A foreign conglomerate purchases the city's largest textile mill, imposing new quotas that reduce local employment.",
+ "stats": [
+ { "stat": "Industry", "value": -9 },
+ { "stat": "Population", "value": -4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 22, "max": 95 },
+ "strength": 73
+ },
+ {
+ "name": "blacksmiths_rebel",
+ "description": "Skilled blacksmiths organize a strike demanding better wages, halting the production of critical weapons.",
+ "stats": [
+ { "stat": "Industry", "value": -10 },
+ { "stat": "Strength", "value": -5 },
+ { "stat": "Crime", "value": 4 }
+ ],
+ "duration": { "Duration": 6 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 22, "max": 95 },
+ "strength": 74
+ },
+ {
+ "name": "machine_revolution",
+ "description": "The introduction of automated presses in the leather works cuts labor costs but renders many artisans obsolete.",
+ "stats": [
+ { "stat": "Industry", "value": 11 },
+ { "stat": "Population", "value": -5 },
+ { "stat": "Crime", "value": 3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 22, "max": 95 },
+ "strength": 74
+ },
+ {
+ "name": "bottleneck_transportation",
+ "description": "The city's main mean of transportation is seized by gangsters, disrupting the flow of raw materials to factories.",
+ "stats": [
+ { "stat": "Transportation", "value": -8 },
+ { "stat": "Industry", "value": -6 },
+ { "stat": "Crime", "value": 7 }
+ ],
+ "duration": { "Duration": 3 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "export_tariff_relief",
+ "description": "An unexpected removal of export tariffs on metal goods opens new markets, boosting production rates.",
+ "stats": [
+ { "stat": "Industry", "value": 12 },
+ { "stat": "Trade", "value": 9 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "smelter_piracy",
+ "description": "A band of raiders captures a shipment of precious ores destined for the city, flooding the market with cheap counterfeit.",
+ "stats": [
+ { "stat": "Industry", "value": -11 },
+ { "stat": "Trade", "value": -7 },
+ { "stat": "Crime", "value": 10 }
+ ],
+ "duration": { "Duration": 4 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "frontline_betrayal",
+ "description": "A key vanguard commander secretly defects, scattering a significant portion of the army and boosting enemy threat.",
+ "stats": [
+ { "stat": "Strength", "value": -6 },
+ { "stat": "Threat", "value": 11 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 22, "max": 95 },
+ "strength": 74
+ },
+ {
+ "name": "naval_battle_victory",
+ "description": "The city's navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy's threat level.",
+ "stats": [
+ { "stat": "Strength", "value": 12 },
+ { "stat": "Threat", "value": -9 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "disease_in_soldiers",
+ "description": "A virulent pestilence breaks out among the ranks, lowering army numbers and damaging overall health.",
+ "stats": [
+ { "stat": "Army", "value": -14 },
+ { "stat": "Health", "value": -10 },
+ { "stat": "Strength", "value": -5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "recruitment_panic",
+ "description": "A surge of conscripts floods the army, but poor training causes a sharp drop in combat effectiveness.",
+ "stats": [
+ { "stat": "Army", "value": 8 },
+ { "stat": "Strength", "value": -9 },
+ { "stat": "Threat", "value": 3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "training_expedition",
+ "description": "A focused military academy expedition hones the troops' skills, raising overall strength at the cost of a temporary manpower drain.",
+ "stats": [
+ { "stat": "Strength", "value": 11 },
+ { "stat": "Army", "value": -6 },
+ { "stat": "Threat", "value": -5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "spy_operation_success",
+ "description": "A covert spy network uncovers threats around, reducing the threat level and providing a tactical advantage.",
+ "stats": [
+ { "stat": "Threat", "value": -10 },
+ { "stat": "Influence", "value": 3 },
+ { "stat": "Strength", "value": 4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "war_taxes_harsh",
+ "description": "The council imposes severe war taxes to fund the army, inflating military budgets but cracking public happiness.",
+ "stats": [
+ { "stat": "Strength", "value": 9 },
+ { "stat": "Happiness", "value": -8 },
+ { "stat": "Food", "value": -3 },
+ { "stat": "Industry", "value": -3 },
+ { "stat": "Science", "value": -3 },
+ { "stat": "Trade", "value": -3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "battlefield_innovation",
+ "description": "A revolutionary tactic is adopted on the front lines, dramatically boosting army strength and lowering enemy threat.",
+ "stats": [
+ { "stat": "Strength", "value": 13 },
+ { "stat": "Threat", "value": -8 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "trade_agreement",
+ "description": "The city brokered a favorable trade pact with a neighboring realm, opening new markets for local goods.",
+ "stats": [
+ { "stat": "Trade", "value": 12 },
+ { "stat": "Food", "value": 3 },
+ { "stat": "Industry", "value": 3 },
+ { "stat": "Science", "value": 3 },
+ { "stat": "Trade", "value": 3 },
+ { "stat": "Population", "value": 3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 76
+ },
+ {
+ "name": "peace_council",
+ "description": "A diplomatic summit ends a long-standing border conflict, reducing threat levels and fostering cultural exchange.",
+ "stats": [
+ { "stat": "Trade", "value": 10 },
+ { "stat": "Culture", "value": 7 },
+ { "stat": "Happiness", "value": 5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 22, "max": 95 },
+ "strength": 76
+ },
+ {
+ "name": "bounty_hunt_success",
+ "description": "A coordinated hunt eliminates a notorious calamity, restoring safety to nearby villages.",
+ "stats": [
+ { "stat": "Crime", "value": -12 },
+ { "stat": "Threat", "value": -8 },
+ { "stat": "Happiness", "value": 4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 75
+ },
+ {
+ "name": "technological_breakthrough",
+ "description": "Inventors in the city unveiled new technologies with huge applications in the industrial field.",
+ "stats": [
+ { "stat": "Science", "value": 15 },
+ { "stat": "Industry", "value": 6 },
+ { "stat": "Food", "value": 3 },
+ { "stat": "Trade", "value": 3 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 21, "max": 95 },
+ "strength": 78
+ },
+ {
+ "name": "festival_of_luxury",
+ "description": "A grand festival draws wealthy merchants and foreign dignitaries, boosting tourism and local pride.",
+ "stats": [
+ { "stat": "Tourism", "value": 13 },
+ { "stat": "Science", "value": 3 },
+ { "stat": "Trade", "value": 3 },
+ { "stat": "Culture", "value": 3 },
+ { "stat": "Influence", "value": 3 },
+ { "stat": "Happiness", "value": 6 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 22, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "military_training_expedition",
+ "description": "An intensive training expedition sharpens the army's tactics, increasing overall strength without cost.",
+ "stats": [
+ { "stat": "Strength", "value": 12 },
+ { "stat": "Army", "value": 3 },
+ { "stat": "Threat", "value": -5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 21, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "health_initiative",
+ "description": "A citywide vaccination campaign eradicates a deadly plague, dramatically improving public health.",
+ "stats": [
+ { "stat": "Health", "value": 16 },
+ { "stat": "Population", "value": 4 },
+ { "stat": "Happiness", "value": 5 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 79
+ },
+ {
+ "name": "artisan_summit",
+ "description": "A gathering of master artisans leads to the sharing of techniques that double production efficiency.",
+ "stats": [
+ { "stat": "Industry", "value": 14 },
+ { "stat": "Science", "value": 8 },
+ { "stat": "Trade", "value": 3 },
+ { "stat": "Population", "value": 2 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 21, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "infrastructure_repair",
+ "description": "A massive repair drive restores crumbling roads and bridges, slashing travel time and boosting trade.",
+ "stats": [
+ { "stat": "Sprawl", "value": 10 },
+ { "stat": "Transportation", "value": 9 },
+ { "stat": "Health", "value": 7 },
+ { "stat": "Industry", "value": 7 },
+ { "stat": "Trade", "value": 7 },
+ { "stat": "Food", "value": 5 },
+ { "stat": "Trade", "value": 4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 24, "max": 95 },
+ "strength": 79
+ },
+ {
+ "name": "cultural_exposition",
+ "description": "The city hosts an international exposition, showcasing its heritage and attracting scholars and tourists alike.",
+ "stats": [
+ { "stat": "Culture", "value": 12 },
+ { "stat": "Tourism", "value": 10 },
+ { "stat": "Happiness", "value": 4 },
+ { "stat": "Influence", "value": 4 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 78
+ },
+ {
+ "name": "great_earthquake",
+ "description": "A massive quake rips through the city, shattering buildings, collapsing bridges, and killing thousands.",
+ "stats": [
+ { "stat": "Health", "value": -19 },
+ { "stat": "Population", "value": -18 },
+ { "stat": "Happiness", "value": -15 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 26, "max": 95 },
+ "strength": 81
+ },
+ {
+ "name": "plague_of_scorpion",
+ "description": "A deadly disease spreads through the populace, turning citizens into venom-infused monsters.",
+ "stats": [
+ { "stat": "Health", "value": -14 },
+ { "stat": "Population", "value": -10 },
+ { "stat": "Crime", "value": 8 }
+ ],
+ "duration": { "Duration": 14 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 79
+ },
+ {
+ "name": "oil_fire_in_barnyard",
+ "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army's morale and strength.",
+ "stats": [
+ { "stat": "Industry", "value": -9 },
+ { "stat": "Happiness", "value": -4 },
+ { "stat": "Threat", "value": 10 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 22, "max": 95 },
+ "strength": 73
+ },
+ {
+ "name": "fire_of_sacred_temple",
+ "description": "The city's most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.",
+ "stats": [
+ { "stat": "Culture", "value": -15 },
+ { "stat": "Threat", "value": 12 },
+ { "stat": "Happiness", "value": -6 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 24, "max": 95 },
+ "strength": 77
+ },
+ {
+ "name": "cursed_great_flood",
+ "description": "An unseasonal deluge swallows the city, flooding every district, destroying crops, and causing widespread disease.",
+ "stats": [
+ { "stat": "Food", "value": -13 },
+ { "stat": "Industry", "value": -6 },
+ { "stat": "Trade", "value": -8 },
+ { "stat": "Threat", "value": 13 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 25, "max": 95 },
+ "strength": 81
+ },
+ {
+ "name": "massive_barricade_breach",
+ "description": "A minor calamity overpowers the city's fortifications, unleashing a wave of slaughter and chaos.",
+ "stats": [
+ { "stat": "Fortification", "value": -19 },
+ { "stat": "Threat", "value": 19 },
+ { "stat": "Happiness", "value": -12 }
+ ],
+ "duration": { "Duration": 1 },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": { "min": 24, "max": 95 },
+ "strength": 81
+ },
+ {
+ "name": "invasion_of_the_undead",
+ "description": "A horde of reanimated civilians under the influence of a calamity attack citizens and military alike.",
+ "stats": [
+ { "stat": "Threat", "value": 14 },
+ { "stat": "Crime", "value": -10 },
+ { "stat": "Population", "value": -12 }
+ ],
+ "duration": { "Duration": 5 },
+ "application": "WhenPresent",
+ "effect_bounds": { "min": 23, "max": 95 },
+ "strength": 78
+ }
+ ]
+}
diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs
new file mode 100644
index 0000000..6b46781
--- /dev/null
+++ b/lib_efo/src/entity.rs
@@ -0,0 +1,119 @@
+//! # Entity System
+//!
+//! The `Entity` type represents any object that can participate in the game world.
+//! It encapsulates runtime statistics, temporary bonuses, and metadata,
+//! along with information about its lifetime and the nature of its effects.
+//!
+//! The design intentionally groups behaviour into two primary components,
+//! `OverallStats` and `MetaStats`. The `entity_type` field is a placeholder
+//! for future trait-based dispatch - the enum will eventually be replaced
+//! by a type-safe system. For the moment it provides a quick lookup for
+//! logic that distinguishes creatures, items, terrain, etc.
+//!
+use serde::{Deserialize, Serialize};
+
+use crate::stats::{EntityType, MetaStats, OverallStats};
+pub mod implementations;
+
+/// An entity that can be present in the game world.
+///
+/// Entities are mutable only through the entity system's public API.
+/// Their fields are private to prevent accidental state corruption.
+#[derive(Serialize, Deserialize, Debug, Clone, Default)]
+pub struct Entity {
+ /// The name of the entity
+ pub name: String,
+ /// Runtime statistics that determine the entity's behaviour.
+ ///
+ /// These values are updated by the game loop and reflect the
+ /// entity's current state (e.g., health, speed, attack).
+ stats: OverallStats,
+
+ /// Temporary statistics that include bonuses from events,
+ /// leaders, or other temporary modifiers.
+ ///
+ /// `temp_stats` is recalculated each turn and does not persist
+ /// beyond the entity's lifetime.
+ temp_stats: OverallStats,
+
+ /// Non-statistical metadata such as name, rarity, and faction.
+ ///
+ /// This information is not directly part of the entity's combat
+ /// calculations but is useful for UI and logic.
+ metadata: MetaStats,
+
+ /// The categorical type of the entity.
+ ///
+ /// Currently an enum that distinguishes creatures, items,
+ /// terrain, etc. It will be phased out in favor of a trait-based
+ /// system for greater type safety.
+ entity_type: EntityType,
+
+ /// The lifetime of the entity within the game world.
+ ///
+ /// The game loop checks this value during each tick to decide
+ /// whether to keep or remove the entity.
+ duration: EntityDuration,
+
+ /// Describes the effect applied by the entity.
+ ///
+ /// This determines when the effect is applied and whether it
+ /// persists after the entity is removed.
+ effect_nature: EffectApplication,
+
+ /// Limits that clamp any stat changes caused by the entity's effect.
+ effect_bounds: EffectBounds,
+}
+
+/// Limits for the maximum and minimum value that an effect may
+/// modify a statistic. The bounds are applied after the effect has
+/// been calculated to keep stats within a sane range.
+///
+/// `min` and `max` are inclusive.
+#[derive(Debug, Serialize, Deserialize, Clone, Default)]
+#[allow(missing_docs)]
+pub struct EffectBounds {
+ pub min: usize,
+ pub max: usize,
+}
+/// How the entity's effect is applied over time.
+#[derive(Debug, Serialize, Deserialize, Clone, Default)]
+pub enum EffectApplication {
+ /// Repeatedly applied every turn while the entity is present.
+ /// Use with caution, as this can produce catastrophic results
+ /// (e.g., an ever-erupting terrain).
+ Recurring,
+
+ /// Modifies the attached entity's stats only while present.
+ /// Removed when the entity is removed. Common for leaders,
+ /// temporary events, or terrain.
+ WhenPresent,
+
+ /// Permanently modifies stats; the change persists after
+ /// the event ends.
+ #[default]
+ PermanentEffectToApply,
+
+ /// Indicates that a permanent effect has already been applied.
+ /// Useful for bookkeeping when a long-lasting event applies
+ /// its effect only once.
+ PermanentEffectApplied,
+}
+
+/// Represents how long an entity remains active in the world.
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
+pub enum EntityDuration {
+ /// The entity persists until it is explicitly destroyed.
+ Permanent,
+
+ /// The entity remains for a fixed number of turns.
+ /// The counter is decremented each tick and the entity becomes
+ /// `Done` once it reaches zero.
+ Duration(usize),
+
+ /// The entity's lifecycle has finished and it should no longer
+ /// be updated. This variant is typically used for one-off
+ /// events or buffs that expire after their final turn.
+ #[default]
+ Done,
+}
diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs
new file mode 100644
index 0000000..67f67d7
--- /dev/null
+++ b/lib_efo/src/entity/implementations.rs
@@ -0,0 +1,132 @@
+//! Implementation of all needed traits for the Entity struct
+use cli_table::{Style, WithTitle, print_stdout};
+use colored::*; // [3] - colored-rs examples
+
+use crate::Displayable;
+use crate::entity::Entity;
+use crate::stats::Symbols;
+
+// ---------- Implementation ----------
+impl Displayable for Entity {
+ // Detailed multi-line view (used e.g. in logs)
+ fn print_full(&self) {
+ println!(
+ "{:?}\n{}",
+ self.metadata.position, // Display
+ format!(
+ "{:?} | {:?} | {} | {:?} | {}",
+ self.metadata.capital,
+ self.metadata.governor,
+ self.metadata.faction,
+ self.metadata.links,
+ self.metadata.prestige
+ )
+ .blue() // colour the whole line (you can tweak colours per field)
+ );
+ let meta_ext = format!(
+ "{:?} | {:?} | {:?} | {:?}",
+ self.duration, self.effect_nature, self.effect_bounds, self.entity_type
+ )
+ .green(); // another colour
+ println!("{meta_ext}");
+ print_stdout(vec![&self.stats, &self.temp_stats].with_title().bold(true)).expect("");
+ }
+
+ // Short, single-line representation
+ fn print_short(&self) {
+ println!("{}", self.to_pretty_tree());
+ print_stdout(vec![&self.stats].with_title().bold(true)).expect("")
+ }
+
+ /// One-liner used for auto-generation of Vec displays
+ fn oneline_display(&self) -> String {
+ let capital = self
+ .metadata
+ .capital
+ .as_ref()
+ .map(|c| format!(" | 💰 {}", c))
+ .unwrap_or_default();
+
+ let governor = self
+ .metadata
+ .governor
+ .as_ref()
+ .map(|g| format!(" | 👑 {}", g))
+ .unwrap_or_default();
+
+ let prestige = if self.metadata.prestige > 0 {
+ format!(" | 📈 {}", self.metadata.prestige)
+ } else {
+ String::new()
+ };
+
+ // ---- build the two lines ----
+ let line1 = format!(
+ "├─ {} {} ──────> {} {}",
+ self.name,
+ self.entity_type.to_symbol(),
+ self.metadata.position.to_symbol(),
+ self.duration.to_symbol()
+ );
+
+ let line2 = format!(
+ "│ └─ Faction: {}{}{}{} │ Effect: {} {}, Stats: 👥 {} | 💰 {} | 🛡️ {} | 🏗️ {}{}",
+ self.metadata.faction,
+ capital,
+ governor,
+ prestige,
+ self.effect_nature.to_symbol(),
+ self.effect_bounds.to_symbol(),
+ self.stats.demographics,
+ self.stats.economy,
+ self.stats.military,
+ self.stats.infrastructure,
+ " "
+ );
+
+ format!("{}\n{}", line1, line2)
+ }
+}
+
+impl Entity {
+ /// Just show a pretty tree
+ pub fn to_pretty_tree(&self) -> String {
+ // Helper that indents a line
+ let indent = |level: usize, s: &str| -> String {
+ format!(" {}{}", "│ ".repeat(level.saturating_sub(1)), s)
+ };
+
+ let mut out = String::new();
+
+ // out.push_str(&indent(0, "self\n"));
+ out.push_str(&indent(0, &format!("name: {}\n", self.name)));
+ out.push_str(&indent(1, "├─ metadata\n"));
+ out.push_str(&indent(
+ 2,
+ &format!("├─ position: {:?}\n", self.metadata.position),
+ ));
+ out.push_str(&indent(
+ 2,
+ &format!("├─ capital: {:?}\n", self.metadata.capital),
+ ));
+ out.push_str(&indent(
+ 2,
+ &format!("└─ prestige: {:?}\n", self.metadata.prestige),
+ ));
+ out.push_str(&indent(1, &format!("├─ duration: {:?}\n", self.duration)));
+ out.push_str(&indent(
+ 1,
+ &format!("├─ effect_nature: {:?}\n", self.effect_nature),
+ ));
+ out.push_str(&indent(
+ 1,
+ &format!("├─ effect_bounds: {:?}\n", self.effect_bounds),
+ ));
+ out.push_str(&indent(
+ 1,
+ &format!("└─ entity_type: {:?}\n", self.entity_type),
+ ));
+
+ out
+ }
+}
diff --git a/lib_efo/src/epoch.rs b/lib_efo/src/epoch.rs
new file mode 100644
index 0000000..ad61733
--- /dev/null
+++ b/lib_efo/src/epoch.rs
@@ -0,0 +1,160 @@
+//! # Epoch configuration and state
+//!
+//! The *epoch* system is deliberately split into two tiny, serialisable
+//! structures so that the binary can quickly read/write its “current
+//! position” without pulling the whole world into memory.
+//!
+//! * `EpochConfig` - lives in `.epochconfig`. It only remembers
+//! which epoch folder should be considered “current” and a few
+//! convenience fields (tags, path). It never holds any event or
+//! world data.
+//!
+//! * `EpochInfo` - stored inside `epoch//.epochinfo`.
+//! This file contains the *metadata* for that particular epoch
+//! (seed, selected events, parent link, etc.). Again, it does **not**
+//! hold the full world; that is handled elsewhere in the engine.
+//!
+//! Keeping these two structs tiny means that switching epochs, logging,
+//! or resetting can be done by reading/writing a handful of JSON/YAML
+//! files, just like a git repository tracks its commits and
+//! `HEAD` pointer.
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+use clap::error::ErrorKind;
+use derive_more::Display;
+use serde::{Deserialize, Serialize};
+use std::{
+ ops::{Deref, DerefMut},
+ str::FromStr,
+};
+
+use crate::error::EpochError;
+pub mod epoch_config;
+pub use epoch_config::EpochConfig;
+
+pub mod epoch_info;
+pub use epoch_info::EpochInfo;
+pub mod epoch_traits;
+
+// TODO[5]: Try to load from a config and have it inserted as a backup
+/// The subfolder naming convention
+static SUBFOLDER_NAMING: &str = "epoch";
+/// The main name of the epoch
+static MAIN_NAME: &str = ".epoch";
+/// The subname of the epochinfo
+static SUB_NAME: &str = ".epochinfo";
+
+/// A lightweight wrapper around a list of tags.
+///
+/// The wrapper exists mainly to give the collection a semantic type
+/// and to hide the internal representation.
+#[derive(Debug, Clone, Serialize, Deserialize, Display)]
+#[display("{inner:?}")]
+pub struct TagList {
+ /// The inner vector of tags
+ inner: Vec,
+}
+
+impl TagList {
+ /// Create a new empty tag list
+ fn new() -> Self {
+ Self { inner: Vec::new() }
+ }
+}
+
+impl Deref for TagList {
+ type Target = Vec;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}
+impl DerefMut for TagList {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.inner
+ }
+}
+
+/// Which save mode to use
+#[allow(missing_docs)]
+pub enum SaveMode {
+ DoNotErase,
+ Erase,
+}
+
+/// Thin type to handle EpochIds
+#[derive(
+ Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display,
+)]
+#[display("{id}")]
+pub struct EpochId {
+ /// The underlying numeric value.
+ pub id: u64,
+}
+
+impl FromStr for EpochId {
+ type Err = EpochError;
+
+ fn from_str(s: &str) -> Result {
+ Ok(EpochId { id: s.parse()? })
+ }
+}
+
+impl EpochId {
+ /// Creates a new `EpochId` from a numeric value.
+ pub fn new(id: u64) -> Self {
+ Self { id }
+ }
+
+ /// Return the next epochId
+ pub fn next(&self) -> Self {
+ Self { id: self.id + 1 }
+ }
+}
+
+impl std::ops::Deref for EpochId {
+ type Target = u64;
+
+ fn deref(&self) -> &Self::Target {
+ &self.id
+ }
+}
+
+/// A flexible identifier for *any* epoch - the world may be
+/// addressed by a numeric ID or by a friendly tag (e.g. `"winter-b"`).
+///
+/// The enum is `untagged` so that serialising/deserialising does
+/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`.
+/// Instead the JSON representation is exactly the inner value:
+/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))`
+/// * `"foo"` → `EpochIdentifier::Tag("foo".into())`
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
+#[serde(untagged)] // <-- no “type” wrapper is written to JSON
+pub enum EpochIdentifier {
+ /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`.
+ Tag(String),
+
+ /// The raw numeric identifier of the epoch.
+ Id(EpochId),
+}
+
+impl FromStr for EpochIdentifier {
+ type Err = clap::Error; // any `std::error::Error` works
+
+ /// Try to parse either a decimal number (-> `Id`) or any non-empty
+ /// string (-> `Tag`).
+ ///
+ /// Errors are converted to a Clap error so that the CLI shows a
+ /// nice message.
+ fn from_str(s: &str) -> Result {
+ if let Ok(num) = s.parse::() {
+ Ok(EpochIdentifier::Id(EpochId::new(num)))
+ } else if !s.is_empty() {
+ Ok(EpochIdentifier::Tag(s.to_owned()))
+ } else {
+ Err(clap::Error::raw(
+ ErrorKind::InvalidValue,
+ format!("{} is not a valid epoch id or tag", s),
+ ))
+ }
+ }
+}
diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs
new file mode 100644
index 0000000..9987432
--- /dev/null
+++ b/lib_efo/src/epoch/epoch_config.rs
@@ -0,0 +1,281 @@
+//! Management of the *current-epoch* configuration.
+//!
+//! The configuration is stored in a file named `.epoch` and contains only
+//! the lightweight information needed for the CLI to switch between epochs
+//! quickly:
+//! * the numeric ID of the current epoch,
+//! * a map of human-friendly tags to epoch IDs,
+//! * a map of known epoch IDs to unloaded metadata (`EpochInfo`).
+//!
+//! The world data and all event logs belong to the individual epoch
+//! directories and are **not** part of this file.
+
+use crate::epoch::{
+ EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode,
+ epoch_traits::ConfigWritable,
+};
+use std::{
+ collections::HashMap,
+ fs::{read_to_string, remove_dir_all},
+ path::Path,
+};
+
+use log::{info, warn};
+use serde::{Deserialize, Serialize};
+
+use crate::{epoch::epoch_traits::Prettiable, error::EpochError, io_err_with_help};
+
+/// The file written to *.epochconfig* that tells the CLI which
+/// epoch folder is the “current” one.
+///
+/// Only the minimal information needed for fast switches is stored:
+/// * the numeric identifier of the selected epoch,
+/// * a list of human-readable tags,
+/// * the absolute path to the epoch's directory.
+///
+/// No world or event data lives here - it is purely a lightweight pointer.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EpochConfig {
+ /// The epoch ID that the binary should consider “current”.
+ pub epoch_id: EpochId,
+
+ /// Optional human-friendly tags (e.g. `"winter-B"`, `"post-war"`).
+ pub tags: HashMap,
+ // TODO[6]: Can become important
+ // #[serde(skip)]
+ // /// Absolute path to `epoch//`.
+ // pub path: PathBuf,
+ /// A hashmap containing the name of all existing epochs, only loaded in memory if used
+ #[serde(skip)]
+ pub list_existing_epochs: HashMap>,
+}
+
+impl Default for EpochConfig {
+ /// Create an empty config, mainly for initialisation
+ fn default() -> Self {
+ EpochConfig {
+ epoch_id: EpochId::new(0),
+ tags: HashMap::new(),
+ list_existing_epochs: HashMap::new(),
+ }
+ }
+}
+
+impl EpochConfig {
+ /// Create a new config from an existig path
+ pub fn new_from_path(_path: Option<&Path>) -> Result {
+ let path = Path::new(MAIN_NAME);
+
+ if path.is_file() {
+ // TODO[6]: write a trait for this
+ let config: EpochConfig = serde_json::from_str(&io_err_with_help!(
+ read_to_string(path),
+ "Reading config from path {:?}",
+ path
+ )?)
+ .map_err(|e| EpochError::Serde {
+ source: e,
+ file_name: path.to_string_lossy().to_string(),
+ help: None,
+ })?;
+ Ok(config.initialize()?)
+ } else {
+ Err(EpochError::MainFolderInvalid(
+ EpochConfig::default().save_folder(),
+ ))
+ }
+ }
+
+ /// Initialize the epoch more in depth
+ pub(crate) fn initialize(mut self) -> Result {
+ let path = EpochConfig::default().save_subfolder();
+ let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?;
+ // let mut valid_folders = HashMap::new();
+ for elt in path {
+ let elt = io_err_with_help!(elt, "Opening file in main config folder")?;
+ if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() {
+ let id = elt.file_name().to_string_lossy().parse::()?;
+ info!("Initialized {:?}", id);
+ self.list_existing_epochs.insert(id, None);
+ }
+ }
+ Ok(self)
+ }
+
+ /// Loads the metadata for an epoch from disk into the in-memory cache.
+ ///
+ /// The epoch identified by `epoch_id` must exist in `list_existing_epochs`.
+ /// The JSON file on disk is read, deserialized into an `EpochInfo`, and
+ /// stored in the map. Any existing value for that epoch is overwritten.
+ ///
+ /// # Returns
+ /// * `Ok(())` when the epoch was successfully read and cached.
+ /// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the
+ /// internal map.
+ /// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed.
+ /// * `Err(EpochError::Io { .. })` if the file could not be read.
+ pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> {
+ // Preload the epoch
+ let value = self
+ .list_existing_epochs
+ .get_mut(epoch_id)
+ .ok_or(EpochError::EpochNotFound(format!("{epoch_id}")))?;
+
+ // Create a mock epoch
+ let path = EpochInfo::with_id(epoch_id).save_path();
+ let read_to_string = io_err_with_help!(read_to_string(&path), "Reading {:?}", path);
+
+ // Try to load
+ let maybe_epoch: EpochInfo =
+ serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde {
+ source: e,
+ file_name: path.to_string(),
+ help: None,
+ })?;
+
+ // Overwrite the value
+ *value = Some(maybe_epoch);
+ Ok(())
+ }
+
+ /// Retrieves the internal epoch ID for a given identifier.
+ ///
+ /// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an
+ /// explicit epoch ID (`EpochIdentifier::Id`).
+ /// * When a tag is supplied the function looks up the corresponding epoch ID in
+ /// the `tags` map.
+ /// * When an ID is supplied it verifies that an epoch with that ID exists in
+ /// `list_existing_epochs` and returns it.
+ ///
+ /// # Returns
+ /// * `Ok(epoch_id)` when the identifier is successfully resolved.
+ /// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist.
+ /// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an
+ /// associated epoch folder.
+ pub fn get(&self, id: &EpochIdentifier) -> Result {
+ match id {
+ EpochIdentifier::Tag(s) => self
+ .tags
+ .get(s)
+ .copied()
+ .ok_or(EpochError::AmbiguousTag(s.to_string())),
+ EpochIdentifier::Id(epoch_id) => self
+ .list_existing_epochs
+ .contains_key(epoch_id)
+ .then_some(epoch_id)
+ .ok_or(EpochError::EpochFolderMissing(
+ *epoch_id,
+ EpochConfig::default().save_folder().into(),
+ ))
+ .copied(),
+ }
+ }
+
+ /// Return the name of the subfolder used to save this structure
+ pub(crate) fn save_subfolder(&self) -> String {
+ format!("{}/", SUBFOLDER_NAMING)
+ }
+
+ /// Delete an entire epoch folder by its ID.
+ ///
+ /// The function removes the directory, deletes all references to the
+ /// epoch from `list_existing_epochs` and `tags`, and then writes the
+ /// updated configuration to disk.
+ // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions
+ pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> {
+ if !self.list_existing_epochs.contains_key(&id) {
+ warn!(
+ "The given epoch {} doesn't exists and it's deletion was skipped",
+ id
+ )
+ } else {
+ io_err_with_help!(
+ remove_dir_all(EpochInfo::with_id(&id).save_folder()),
+ "Removing the epoch {}",
+ id
+ )?;
+ self.list_existing_epochs.remove(&id);
+ self.tags.retain(|_k, v| *v != id);
+ self.save_with_context("Saving after delete_id", &SaveMode::Erase)?;
+ }
+ Ok(())
+ }
+
+ /// Compute the next epoch.
+ ///
+ /// Currently this function is a placeholder that creates a new epoch
+ /// with the ID immediately following the current one. The actual logic
+ /// is deferred to the `EpochInfo -> World` subsystem.
+ pub fn compute_next(&mut self) -> Result {
+ // unimplemented!()
+ // TODO[1]: Implement this
+ warn!("DEBUG LINE: COMPUTING NEXT EPOCH");
+ // New fake epoch
+ Ok(EpochInfo::with_id(&self.epoch_id.next()))
+ }
+
+ /// Insert a new epoch into the configuration and persist it.
+ ///
+ /// The function creates the epoch's directory, writes its metadata,
+ /// updates the internal maps, and finally writes the updated
+ /// configuration to disk.
+ ///
+ /// # Returns
+ /// * `Ok(())` - the epoch was added and the configuration was saved.
+ /// * `Err(EpochError::EpochAlreadyExists(..))` if an epoch with the same ID already exists.
+ pub fn insert_and_save(
+ &mut self,
+ new_epoch: EpochInfo,
+ save_mode: &SaveMode,
+ ) -> Result<(), EpochError> {
+ if self.list_existing_epochs.contains_key(&new_epoch.epoch_id) {
+ return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id));
+ }
+
+ new_epoch.create_subfolders()?;
+ new_epoch.save_with_context("Saving new epoch", save_mode)?;
+
+ // Add the epoch to the list of epochs, not doing so will still have it added
+ // at the next iteration since the command always parse the files to determine it's state rater that the list
+ // not doing so would likely create errors if insert is used before another command
+ let new_id = new_epoch.epoch_id;
+ self.list_existing_epochs.insert(new_id, Some(new_epoch));
+ self.epoch_id = new_id;
+ self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?;
+ Ok(())
+ }
+
+ /// Load and display the metadata for a list of epoch IDs.
+ ///
+ /// The function first ensures that each requested epoch's metadata is
+ /// loaded into memory, then displays a formatted log for each one.
+ pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> {
+ let mut items_to_log = Vec::with_capacity(list_ids.len());
+ // Tries to load all ids into memory
+ for id in list_ids {
+ self.try_load(id)?;
+ }
+ // Makes a vector with all elements from the list of ids
+ for id in list_ids {
+ if let Some(info) = self
+ .list_existing_epochs
+ .get(id)
+ .ok_or(EpochError::EpochNotFound(id.to_string()))?
+ {
+ items_to_log.push(info);
+ }
+ }
+ EpochInfo::show_as_table(items_to_log);
+ Ok(())
+ }
+}
+
+impl ConfigWritable for EpochConfig {
+ fn save_path(&self) -> String {
+ MAIN_NAME.to_string()
+ }
+
+ fn save_folder(&self) -> String {
+ ".".to_string()
+ }
+}
diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs
new file mode 100644
index 0000000..1dceeec
--- /dev/null
+++ b/lib_efo/src/epoch/epoch_info.rs
@@ -0,0 +1,96 @@
+//! Metadata management for individual epochs.
+//!
+//! The `EpochInfo` struct holds all information that the engine needs to
+//! reconstruct a particular epoch.
+//! It is persisted to `epoch//.epochinfo`. The file contains the epoch ID, the RNG
+//! seed that produced the world, any optional tags, and a human-readable
+//! summary. World data itself is stored separately (e.g. in `world.json`).
+
+use cli_table::Table;
+use derive_more::Display;
+use serde::{Deserialize, Serialize};
+use std::fs::create_dir_all;
+
+use crate::{
+ epoch::{
+ EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList,
+ epoch_traits::{ConfigWritable, Prettiable},
+ },
+ error::EpochError,
+ io_err_with_help,
+};
+
+/// The metadata file stored inside each epoch directory
+/// (`epoch//.epochinfo`).
+///
+/// It contains only the information that is needed for the engine to
+/// reconstruct the state *of that particular epoch* (seed, selected
+/// events, parent link, etc.). The full world data is kept in
+/// separate storage (e.g. `world.json`).
+#[derive(Debug, Clone, Serialize, Deserialize, Display, Table)]
+#[display(
+ "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})"
+)]
+pub struct EpochInfo {
+ /// The ID of this epoch - should match the directory name.
+ #[table(title = "ID")]
+ pub epoch_id: EpochId,
+
+ /// RNG seed that was used to generate randomised data for
+ /// this epoch. Keeping it in the file guarantees repeatable
+ /// behaviour when replaying the same epoch.
+ #[table(title = "Seed")]
+ pub rng_seed: u64,
+
+ // /// List of event IDs that were accepted for this epoch.
+ // /// The engine uses this to replay the world from the
+ // /// parent epoch to the current one.
+ // pub selected_events: Vec,
+ /// Optional tags that help identify the epoch (e.g. `"Winter-B"`).
+ #[table(title = "Tags")]
+ pub tags: TagList,
+
+ /// Human-readable description or summary, useful for the `log` command.
+ #[table(title = "Summary")]
+ pub summary: String,
+}
+
+impl Prettiable for EpochInfo {}
+
+impl Default for EpochInfo {
+ fn default() -> Self {
+ Self {
+ epoch_id: EpochId::new(0),
+ rng_seed: 0,
+ tags: TagList::new(),
+ summary: String::new(),
+ }
+ }
+}
+
+impl EpochInfo {
+ /// Create all subfolders as needed
+ ///
+ /// This command can be safely used even if the folder already exists
+ pub fn create_subfolders(&self) -> Result<(), EpochError> {
+ io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders")
+ }
+
+ /// Create an epoch with only an Id, please note that this function doesn't load the epoch at all
+ pub(crate) fn with_id(epoch_id: &EpochId) -> Self {
+ Self {
+ epoch_id: *epoch_id,
+ ..Default::default()
+ }
+ }
+}
+
+impl ConfigWritable for EpochInfo {
+ fn save_path(&self) -> String {
+ format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME)
+ }
+
+ fn save_folder(&self) -> String {
+ format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id)
+ }
+}
diff --git a/lib_efo/src/epoch/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs
new file mode 100644
index 0000000..55a25bf
--- /dev/null
+++ b/lib_efo/src/epoch/epoch_traits.rs
@@ -0,0 +1,109 @@
+//! epoch_traits.rs
+//!
+//! All traits used by the `lib_efo` library.
+//! These traits are marker traits that describe behaviour
+//! common to many of the library's element types.
+#![warn(clippy::missing_docs_in_private_items)]
+
+use cli_table::{Style, Table, WithTitle};
+use serde::Serialize;
+use std::{fmt::Display, fs::File, io::Write};
+
+use crate::{epoch::SaveMode, error::EpochError};
+
+/// Elements that can be compared with another instance to produce a diff.
+pub trait Diffable {}
+
+/// Elements that can be applied to the current world state.
+pub trait Applyable {}
+
+/// Elements that can advance to a next state over time.
+///
+/// Implementors usually provide a `.next()` method that returns the
+/// element's state after a time step (e.g., fading or diminishing).
+pub trait Nextable {}
+
+/// Elements that can be rendered into a pretty, human-readable form.
+pub trait Prettiable: Display {
+ /// Shows many items as a table.
+ ///
+ /// The table is printed to `stdout` using the `cli_table` crate.
+ ///
+ /// # Panics
+ /// Panics if printing the table to stdout fails.
+ fn show_as_table(list: Vec<&Self>)
+ where
+ for<'a> Vec<&'a Self>: Table + WithTitle,
+ {
+ #[allow(clippy::unwrap_used)] // There is no recovery of not being able to print a table
+ cli_table::print_stdout(list.with_title().bold(true)).unwrap();
+ }
+
+ /// Displays the struct as a log entry by printing the output of
+ /// `as_log()` to stdout.
+ fn show_as_log(&self) {
+ println!("{}", self.as_log())
+ }
+
+ /// Converts the struct into a pretty log string.
+ fn as_log(&self) -> String {
+ format!("{}", self)
+ }
+}
+
+/// Trait representing a serialisable / writable config
+pub trait ConfigWritable: Serialize {
+ /// The full path indicating where to save the config
+ fn save_path(&self) -> String;
+
+ /// The folder where to save the file to save the config
+ fn save_folder(&self) -> String;
+
+ /// Serialises the config into a pretty JSON string.
+ ///
+ /// # Arguments
+ /// * `action` - A description of the action for error reporting.
+ ///
+ /// # Returns
+ /// * `Ok(String)` containing the pretty-printed JSON.
+ /// * `Err(EpochError::Serde)` if serialisation fails.
+ fn as_json(&self, action: String) -> Result {
+ serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
+ source: e,
+ file_name: action,
+ help: None,
+ })
+ }
+
+ /// Saves the config into its nominal path.
+ ///
+ /// Existing subdirectories are not created.
+ /// If `do_not_erase` is `SaveMode::Erase`, an existing file is overwritten.
+ /// If `do_not_erase` is `SaveMode::DoNotErase`, an error is returned when the
+ /// file already exists.
+ ///
+ /// # Arguments
+ /// * `action_description` - A human-readable description used in error messages.
+ /// * `do_not_erase` - Determines whether to overwrite an existing file.
+ ///
+ /// # Returns
+ /// * `Ok(())` on success.
+ /// * `Err(EpochError::ConfigWrite)` on any serialization error.
+ /// * `Err(EpochError::ConfigCreation)` on any I/O error.
+ fn save_with_context(
+ &self,
+ // Very unsure about this versus a macro
+ action_description: &str,
+ do_not_erase: &SaveMode,
+ // advice: Option,
+ ) -> Result<(), EpochError> {
+ let mut f = match *do_not_erase {
+ SaveMode::Erase => File::create(self.save_path()),
+ SaveMode::DoNotErase => File::create_new(self.save_path()),
+ }
+ .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
+ write!(f, "{}", self.as_json(action_description.to_owned())?)
+ .map_err(EpochError::ConfigWrite)?;
+ Ok(())
+ }
+}
diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs
deleted file mode 100644
index 131dd3a..0000000
--- a/lib_efo/src/epoch_struct.rs
+++ /dev/null
@@ -1,378 +0,0 @@
-//! # Epoch configuration and state
-//!
-//! The *epoch* system is deliberately split into two tiny, serialisable
-//! structures so that the binary can quickly read/write its “current
-//! position” without pulling the whole world into memory.
-//!
-//! * `EpochConfig` – lives in `.epochconfig`. It only remembers
-//! which epoch folder should be considered “current” and a few
-//! convenience fields (tags, path). It never holds any event or
-//! world data.
-//!
-//! * `EpochInfo` – stored inside `epoch//.epochinfo`.
-//! This file contains the *metadata* for that particular epoch
-//! (seed, selected events, parent link, etc.). Again, it does **not**
-//! hold the full world; that is handled elsewhere in the engine.
-//!
-//! Keeping these two structs tiny means that switching epochs, logging,
-//! or resetting can be done by reading/writing a handful of JSON/YAML
-//! files, just like a git repository tracks its commits and
-//! `HEAD` pointer.
-
-use clap::error::ErrorKind;
-use serde::{Deserialize, Serialize};
-use std::{
- collections::HashMap,
- fmt,
- fs::{File, create_dir_all, read_to_string, remove_dir_all},
- io::Write,
- path::Path,
- str::FromStr,
-};
-
-use crate::{epoch_struct, error::EpochError, io_err_with_help};
-
-static SUBFOLDER_NAMING: &str = "epoch";
-static MAIN_NAME: &str = ".epoch";
-static SUB_NAME: &str = ".epochinfo";
-
-/// The file written to *.epochconfig* that tells the CLI which
-/// epoch folder is the “current” one.
-///
-/// Only the minimal information needed for fast switches is stored:
-/// * the numeric identifier of the selected epoch,
-/// * a list of human‑readable tags,
-/// * the absolute path to the epoch’s directory.
-///
-/// No world or event data lives here – it is purely a lightweight pointer.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct EpochConfig {
- /// The epoch ID that the binary should consider “current”.
- pub epoch_id: EpochId,
-
- /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`).
- pub tags: HashMap,
- // TODO: Can become important
- // #[serde(skip)]
- // /// Absolute path to `epoch//`.
- // pub path: PathBuf,
- /// A hashmap containing the name of all existing epochs, only loaded in memory if used
- #[serde(skip)]
- pub list_existing_epochs: HashMap>,
-}
-
-impl Default for EpochConfig {
- /// Create an empty config, mainly for initialisation
- fn default() -> Self {
- EpochConfig {
- epoch_id: EpochId::new(0),
- tags: HashMap::new(),
- list_existing_epochs: HashMap::new(),
- }
- }
-}
-
-impl EpochConfig {
- /// Create a new config from an existig path
- pub fn new_from_path(_path: Option<&Path>) -> Result {
- let path = Path::new(MAIN_NAME);
-
- if path.is_file() {
- // TODO: write a trait for this
- let config: EpochConfig = serde_json::from_str(&io_err_with_help!(
- read_to_string(path),
- format!("Reading config from path {:?}", path)
- )?)
- .map_err(|e| EpochError::Serde {
- source: e,
- file_name: path.to_string_lossy().to_string(),
- help: None,
- })?;
- Ok(config.initialize()?)
- } else {
- Err(EpochError::MainFolderInvalid(
- EpochConfig::default().save_folder(),
- ))
- }
- }
-
- /// Initialize the epoch more in depth
- fn initialize(mut self) -> Result {
- let path = EpochConfig::default().save_subfolder();
- let path = io_err_with_help!(
- Path::new(&path).read_dir(),
- format!("Reading initial folder {path}")
- )?;
- // let mut valid_folders = HashMap::new();
- for elt in path {
- let elt = io_err_with_help!(elt, "Opening file in main config folder")?;
- if io_err_with_help!(
- elt.file_type(),
- format!("Determining file type of {:?}", elt)
- )?
- .is_dir()
- {
- let id = elt.file_name().to_string_lossy().parse::();
- println!("{:?}", id);
- self.list_existing_epochs.insert(id.unwrap(), None);
- }
- }
- Ok(self)
- }
-
- /// Try to load into memory the given epoch id
- pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> {
- // Preload the epoch
- let value = self.list_existing_epochs.get_mut(epoch_id).unwrap();
-
- // Create a mock epoch
- let path = EpochInfo::with_id(epoch_id).save_path();
- let read_to_string =
- io_err_with_help!(read_to_string(&path), format!("Reading {:?}", path));
-
- // Try to load
- let maybe_epoch: EpochInfo =
- serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde {
- source: e,
- file_name: path.to_string(),
- help: None,
- })?;
-
- // Overwrite the value
- *value = Some(maybe_epoch);
- Ok(())
- }
-
- /// Get an identifier or returns None
- pub fn get(&self, id: &EpochIdentifier) -> Result {
- match id {
- EpochIdentifier::Tag(s) => self
- .tags
- .get(s)
- .copied()
- .ok_or(EpochError::AmbiguousTag(s.to_string())),
- EpochIdentifier::Id(epoch_id) => self
- .list_existing_epochs
- .contains_key(epoch_id)
- .then_some(epoch_id)
- .ok_or(EpochError::EpochFolderMissing(
- *epoch_id,
- EpochConfig::default().save_folder().into(),
- ))
- .copied(),
- }
- }
-
- fn save_subfolder(&self) -> String {
- format!("{}/", SUBFOLDER_NAMING)
- }
-
- /// Tries to delete an entire epoch folder by Id
- pub fn delete_id(&self, id: EpochId) -> Result<(), EpochError> {
- if !self.list_existing_epochs.contains_key(&id) {
- println!(
- "The given epoch {} doesn't exists and it's deletion was skipped",
- id
- )
- }
- io_err_with_help!(
- remove_dir_all(EpochInfo::with_id(&id).save_folder()),
- format!("Removing the epoch {}", id)
- )?;
- Ok(())
- }
-}
-
-/// Trait representing a serialisable / writable config
-pub trait ConfigWritable: Serialize {
- /// The full path indicating where to save the config
- fn save_path(&self) -> String;
-
- /// The folder where to save the file to save the config
- fn save_folder(&self) -> String;
-
- /// Have the config as JSON
- fn as_json(&self, action: String) -> Result {
- serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
- source: e,
- file_name: action,
- help: None,
- })
- }
-
- /// Save the config into it's nominal path
- fn save(
- &self,
- // Very unsure about this versus a macro
- action_description: String,
- do_not_erase: SaveMode,
- // advice: Option,
- ) -> Result<(), EpochError> {
- let mut f = match do_not_erase {
- SaveMode::Erase => File::create(self.save_path()),
- SaveMode::DoNotErase => File::create_new(self.save_path()),
- }
- .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
- write!(f, "{}", self.as_json(action_description)?).map_err(EpochError::ConfigWrite)?;
- Ok(())
- }
-}
-
-/// The metadata file stored inside each epoch directory
-/// (`epoch//.epochinfo`).
-///
-/// It contains only the information that is needed for the engine to
-/// reconstruct the state *of that particular epoch* (seed, selected
-/// events, parent link, etc.). The full world data is kept in
-/// separate storage (e.g. `world.json`).
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct EpochInfo {
- /// The ID of this epoch – should match the directory name.
- pub epoch_id: EpochId,
-
- /// The ID of the parent (previous) epoch, if not a root.
- pub parent_id: Option,
-
- /// RNG seed that was used to generate randomised data for
- /// this epoch. Keeping it in the file guarantees repeatable
- /// behaviour when replaying the same epoch.
- pub rng_seed: u64,
-
- // /// List of event IDs that were accepted for this epoch.
- // /// The engine uses this to replay the world from the
- // /// parent epoch to the current one.
- // pub selected_events: Vec,
- /// Optional tags that help identify the epoch (e.g. `"Winter‑B"`).
- pub tags: Vec,
-
- /// Human‑readable description or summary, useful for the `log` command.
- pub summary: Option,
-}
-
-impl Default for EpochInfo {
- fn default() -> Self {
- Self {
- epoch_id: epoch_struct::EpochId::new(0),
- parent_id: None,
- rng_seed: 0,
- tags: Vec::new(),
- summary: None,
- }
- }
-}
-
-pub enum SaveMode {
- DoNotErase,
- Erase,
-}
-
-impl EpochInfo {
- /// Create all subfolders as needed
- pub fn create_subfolders(&self) -> Result<(), EpochError> {
- io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders")
- }
-
- /// Create an epoch with only an Id, please note that this function doesn't load the epoch at all
- fn with_id(epoch_id: &EpochId) -> Self {
- Self {
- epoch_id: *epoch_id,
- ..Default::default()
- }
- }
-}
-
-/// Thin type to handle EpochIds
-#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct EpochId {
- /// The underlying numeric value. A value of `0` is never used –
- /// epoch IDs start at 1.
- pub id: u64,
-}
-
-impl FromStr for EpochId {
- type Err = EpochError;
-
- fn from_str(s: &str) -> Result {
- Ok(EpochId { id: s.parse()? })
- }
-}
-
-impl std::fmt::Display for EpochId {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "{}", self.id)
- }
-}
-
-impl EpochId {
- /// Creates a new `EpochId` from a numeric value.
- pub fn new(id: u64) -> Self {
- Self { id }
- }
-}
-
-impl std::ops::Deref for EpochId {
- type Target = u64;
-
- fn deref(&self) -> &Self::Target {
- &self.id
- }
-}
-
-impl ConfigWritable for EpochConfig {
- fn save_path(&self) -> String {
- MAIN_NAME.to_string()
- }
-
- fn save_folder(&self) -> String {
- ".".to_string()
- }
-}
-impl ConfigWritable for EpochInfo {
- fn save_path(&self) -> String {
- format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME)
- }
-
- fn save_folder(&self) -> String {
- format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id)
- }
-}
-
-/// A flexible identifier for *any* epoch – the world may be
-/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`).
-///
-/// The enum is `untagged` so that serialising/deserialising does
-/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`.
-/// Instead the JSON representation is exactly the inner value:
-/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))`
-/// * `"foo"` → `EpochIdentifier::Tag("foo".into())`
-#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
-#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON
-pub enum EpochIdentifier {
- /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`.
- Tag(String),
-
- /// The raw numeric identifier of the epoch.
- Id(EpochId),
-}
-
-impl FromStr for EpochIdentifier {
- type Err = clap::Error; // any `std::error::Error` works
-
- /// Try to parse either a decimal number (-> `Id`) or any non‑empty
- /// string (-> `Tag`).
- ///
- /// Errors are converted to a Clap error so that the CLI shows a
- /// nice message.
- fn from_str(s: &str) -> Result {
- if let Ok(num) = s.parse::() {
- Ok(EpochIdentifier::Id(EpochId::new(num)))
- } else if !s.is_empty() {
- Ok(EpochIdentifier::Tag(s.to_owned()))
- } else {
- Err(clap::Error::raw(
- ErrorKind::InvalidValue,
- format!("{} is not a valid epoch id or tag", s),
- ))
- }
- }
-}
diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs
index 99914d7..b97ce4c 100644
--- a/lib_efo/src/error.rs
+++ b/lib_efo/src/error.rs
@@ -1,17 +1,27 @@
//! Error types that arise when interacting with the storage layer.
//!
-//! These are the only errors emitted by the `Storage` abstraction.
-//! They are lightweight, strongly‑typed and can be converted to the
-//! top‑level `AppError` via `thiserror`.
+//! These are the only errors emitted by the `Storage` abstraction. They are
+//! lightweight, strongly-typed, and can be converted to the top-level
+//! `AppError` via `thiserror`.
+//!
+//! The public items below are all lightweight error types that can be
+//! produced by the storage layer or the epoch handling subsystem.
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+
+use derive_more::Display;
use std::{num::ParseIntError, path::PathBuf};
use thiserror::Error;
-use crate::epoch_struct::EpochId;
+use crate::epoch::EpochId;
use miette::Diagnostic;
/// Errors that can be returned by the storage layer.
+///
+/// The variants are intentionally small - each one carries all the
+/// information required to surface a helpful message to the user.
+// TODO[2]: Remove or rethink these errors
#[derive(Debug, Error, Diagnostic)]
pub enum StorageError {
/// Problems with serialisation / deserialisation.
@@ -32,153 +42,222 @@ pub enum StorageError {
}
/// All errors that can occur while working with epochs.
-/// The enum is deliberately *small* – each variant is self‑contained
-/// and carries the information you need to surface a friendly message
-/// to the user (and to the test‑suite).
+///
+/// The enum is deliberately _small_ - each variant is self-contained and
+/// carries the information you need to surface a friendly message
+/// to the user (and to the test-suite).
+// TODO[2]: Split effectively user errors to avoid the usage of advice and such
#[derive(Error, Debug, Diagnostic)]
pub enum EpochError {
- /// Problems with the `.epochconfig` file
+ /// Problems with the `.epochconfig` file.
#[error("Failed to read epoch configuration")]
+ #[diagnostic(code(EpochError::ConfigRead))]
ConfigRead(#[source] std::io::Error),
+ /// Failed to write the epoch configuration.
#[error("Failed to write epoch configuration")]
+ #[diagnostic(code(EpochError::ConfigWrite))]
ConfigWrite(#[source] std::io::Error),
+ /// Failed to create the epoch configuration.
#[error("Failed to create the epoch configuration")]
#[help("Make sure the path is writable")]
+ #[diagnostic(code(EpochError::ConfigCreation))]
ConfigCreation(String, #[source] std::io::Error),
+ /// This directory is already an epoch folder and thus cannot be initialized.
#[error("This directory is already an epoch folder and thus cannot be initialized")]
#[diagnostic(code(EpochError::AlreadyInitialized))]
AlreadyInitialized {
#[help]
+ /// User given advice
advice: Option,
},
+ /// This directory isn't empty and thus cannot be initialized.
#[error("This directory isn't empty and thus cannot be initialized")]
#[diagnostic(code(EpochError::FolderNotEmpty))]
#[diagnostic(help("Empty the folder or remove its content first"))]
- // #[diagnostic(label((1,1)))]
FolderNotEmpty {
#[source_code]
+ /// Name of the file causing problem
name: Option,
-
+ /// Trick used to have a cute line showing the following error message
#[label("This file is present and forbid the command to execute properly")]
show_label: Option<(usize, usize)>,
},
- /// Problems while serialising / deserialising an `EpochInfo`
+ /// Problems while serialising / deserialising an `EpochInfo`.
#[error("Failed to parse `.epochinfo` in epoch {0} ({1}): {2}")]
+ #[diagnostic(code(EpochError::EpochInfoParse))]
EpochInfoParse(EpochId, PathBuf, #[source] serde_json::Error),
+ /// Failed to write `.epochinfo` in epoch {id} ({path}).
#[error("Failed to write `.epochinfo` in epoch {id} ({path})")]
#[diagnostic(code(EpochError::EpochInfoWrite))]
EpochInfoWrite {
+ /// The id of the epoch
id: EpochId,
+ /// The path of the epoch
path: PathBuf,
-
+ /// An optionnal help message
#[help]
help: Option,
-
+ /// The source error
#[source]
src: Option,
},
- /// The user supplied an epoch id or tag that does not exist
- #[error("No epoch found for id/tag `{}`", .0)]
+ /// The user supplied an epoch id or tag that does not exist.
+ #[error("No epoch found for id/tag `{0}`")]
+ #[diagnostic(code(EpochError::EpochNotFound))]
EpochNotFound(String),
- /// The user attempted to resolve an epoch that is *ambiguous* – e.g. two
- /// tags with the same name or a tag that points to a non‑existent id
- #[error("Tag `{}` resolves to either multiple epochs or invalid epoch", .0)]
+ /// The user attempted to resolve an epoch that is ambiguous.
+ #[error("Tag `{0}` resolves to either multiple epochs or invalid epoch")]
+ #[diagnostic(code(EpochError::AmbiguousTag))]
AmbiguousTag(String),
- /// The epoch folder for the target id is missing
- #[error("Missing directory for epoch {} at `{}`", .0, .1.display())]
+ /// The epoch folder for the target id is missing.
+ #[error("Missing directory for epoch {0} at `{1}`")]
+ #[diagnostic(code(EpochError::EpochFolderMissing))]
EpochFolderMissing(EpochId, PathBuf),
- /// There are *future* events left in the current epoch, so you cannot compute `next`
- #[error("Cannot compute `next` because there are pending future events")]
- FutureEventsExist,
+ /// A future epoch exists, forbidding you to compute `next` and overriding them.
+ #[diagnostic(help("Use epoch reset if you want to erase all future epochs first"))]
+ #[error("Cannot compute `next` because future epoch exists")]
+ #[diagnostic(code(EpochError::FutureEpochExist))]
+ FutureEpochExist,
- /// Attempt to switch to an epoch that has already been *advanced* past
- /// the current world state (e.g. you are at epoch 5 but try to switch
- /// to epoch 7 while epoch 6 is still in the past)
- #[error("Cannot switch to epoch `{}` – the world has already advanced beyond it", .0)]
+ /// A specific epoch exists, forbidding the further execution of the command.
+ #[diagnostic(help("Use epoch reset or manually delete the epoch {0}"))]
+ #[error("The epoch {0} exists forbidding the execution of the command")]
+ #[diagnostic(code(EpochError::EpochAlreadyExists))]
+ EpochAlreadyExists(EpochId),
+
+ /// Attempt to switch to an epoch that has already been advanced past.
+ #[error("Cannot switch to epoch `{0}` - the world has already advanced beyond it")]
+ #[diagnostic(code(EpochError::SwitchPastEpoch))]
SwitchPastEpoch(EpochId),
- /// The supplied epoch id is out of bounds (negative, zero or too large)
- #[error("Invalid epoch id `{}` – must be a positive, non‑overflowing integer", .0)]
+ /// The supplied epoch id is out of bounds (negative, zero or too large).
+ #[error("Invalid epoch id `{0}` - must be a positive, non-overflowing integer")]
+ #[diagnostic(code(EpochError::InvalidEpochId))]
InvalidEpochId(EpochId),
- /// A tag that the user tried to assign already exists
- #[error("Tag `{}` already exists for epoch {}", .1, .0)]
+ /// A tag that the user tried to assign already exists.
+ #[error("Tag `{1}` already exists for epoch {0}")]
+ #[diagnostic(code(EpochError::InvalidEpochId))]
TagAlreadyExists(EpochId, String),
- // /// An attempt to delete or reset events failed because the world
- // /// was in an inconsistent state (e.g. `reset` called before any `switch`)
- // #[error("Reset failed: no epoch has been switched to yet")]
- // ResetBeforeSwitch,
- /// The parent epoch referenced in an `EpochInfo` cannot be found
+ /// The parent epoch referenced in an `EpochInfo` cannot be found.
#[error("Parent epoch {} referenced by epoch {} does not exist", .0, .1)]
+ #[diagnostic(code(EpochError::ParentEpochMissing))]
ParentEpochMissing(EpochId, EpochId),
- /// Generic I/O errors that bubble up from other sub‑tasks
+ /// Generic I/O errors that bubble up from other sub-tasks.
#[error("I/O error")]
#[diagnostic(code(EpochError::GenericIO))]
Io {
+ /// The source error
#[source]
source: std::io::Error,
-
+ /// An optionnal help message
#[help]
help: Option,
+ /// Where the error originated from
+ error_line: u32,
},
- /// Serialization / deserialization errors that are not caught above
+ /// Serialization / deserialization errors that are not caught above.
#[error("Serialization error from {file_name}")]
#[diagnostic(code(EpochError::SerdeError))]
Serde {
+ /// The source error
#[source]
source: serde_json::Error,
-
+ /// The file that was being written
file_name: String,
-
+ /// An optionnal help message
#[help]
help: Option,
},
- /// The epoch tree is in an incorrect state
+ /// The epoch tree is in an incorrect state.
#[error("Invalid epoch tree at {0}")]
+ #[diagnostic(code(EpochError::TreeInvalid))]
TreeInvalid(EpochId, String),
- /// The main folder is not an epoch folder
+ /// The main folder is not an epoch folder.
#[error("The given directory ({0:?}) is not an epoch folder")]
+ #[diagnostic(code(EpochError::MainFolderInvalid))]
MainFolderInvalid(String),
- /// Couldn't parse an EpochId
+ /// Couldn't parse an `EpochId`.
#[error("The id ({0}) couldn't be converted to a valid EpochId")]
- #[diagnostic(code(EpochError::ConversionIdImpossible))]
+ #[diagnostic(code(EpochError::ParsingEpochId))]
ParsingEpochId(#[from] ParseIntError),
- /// Any other error that didn't fit into the above categories
+ /// Any other error that didn't fit into the above categories.
#[error("An unknown error occurred: {0}")]
+ #[diagnostic(code(EpochError::Unknown))]
Unknown(String),
+
+ /// The user tried to parse an acronim that doen't match any stats known to the system.
+ #[error("Unknown stat acronym: {0}")]
+ #[diagnostic(code(EpochError::UnknownStatAcronim))]
+ UnknownStatAcronim(String),
+
+ /// The user gave a stat:identifier pair that was incorrect
+ #[error("Expected a stat and a number, got: {0}")]
+ #[diagnostic(code(EpochError::IllFormedStatQualifier))]
+ IllFormedStatQualifier(String),
+
+ /// User error, meant to be very explicit over what happened and what to do.
+ #[error("An user facing error")]
+ #[diagnostic(code(EpochError::UserError))]
+ UserError(#[help] UserErrors),
+
+ /// An error happened when picking a rng event
+ #[error("An error happened when trying to pick a rng event for {cause}")]
+ #[diagnostic(code(EpochError::RNGPickError))]
+ RNGPickError {
+ /// The root cause originating the error
+ cause: String,
+ #[help]
+ /// Optionnal help
+ help: Option,
+ },
}
+/// A small enum of explicit user-facing error messages.
+///
+/// The variants are deliberately simple; each one is rendered with a
+/// clear message via `derive_more::Display`.
+#[derive(Debug, Display, Diagnostic, Error)]
+pub enum UserErrors {
+ /// The classic mistake
+ #[display("The user did a very bad thing")]
+ #[diagnostic(code(UserErrors::DSItF))]
+ DSItF,
+}
// macro_rules! err_with {
// ($expr:expr, $err_ty:ty {$($field:ident : $value:expr),* $(,)?}) => {{
// $expr.map_err(|e| { $err_ty { $($field: $value),* } })
// }};
// }
+/// Helper macro to convert a `std::io::Error` into an `EpochError::Io`
+/// with an attached help message.
+///
+/// The macro captures the current line number for debugging purposes.
#[macro_export]
macro_rules! io_err_with_help {
- // $expr: the expression that produces the Result
- // $help: string literal with the help message
- ($expr:expr, $help:expr) => {{
+ ($expr:expr, $($help:expr),*) => {{
$expr.map_err(|e| EpochError::Io {
source: e,
- help: Some($help.to_owned()),
+ help: Some(format!($($help),*)),
+ error_line: line!(),
})
}};
}
diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs
index 8a5d8e0..ce4cbdc 100644
--- a/lib_efo/src/lib.rs
+++ b/lib_efo/src/lib.rs
@@ -3,23 +3,29 @@
//! The **engine** that drives *Epoch Forge*. It contains a pure, representation of a fantasy world and all the logic needed to manipulate it.
//!
//! The crate is split into the following domains, each exposed as a public module:
-//! - TODO: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`).
-//! - TODO: `epoch` – manages the passage of time and epoch switching.
-//! - TODO: `event` – CRUD and evaluation of events that affect the world.
-//! - TODO: `org` – organisations, guilds, factions and their history.
-//! - TODO: `character` – individual characters, traits and lineage.
-//! - TODO: `town` – towns, cities, trade hubs and their populations.
-//! - TODO: `link` – relations such as wars, alliances, roads, commerce.
-//! - TODO: `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends.
-//! - TODO: `util` – small helpers, ID generation, error types, etc.
+//! - TODO[1]: `world` - holds the global state (`World`) and a lightweight snapshot (`Context`).
+//! - TODO[0]: `epoch` - manages the passage of time and epoch switching.
+//! - TODO[1]: `event` - CRUD and evaluation of events that affect the world.
+//! - TODO[4]: `org` - organisations, guilds, factions and their history.
+//! - TODO[2]: `character` - individual characters, traits and lineage.
+//! - TODO[1]: `town` - towns, cities, trade hubs and their populations.
+//! - TODO[2]: `link` - relations such as wars, alliances, roads, commerce.
+//! - TODO[3]: `storage` - generic persistence layer (`Store`) with JSON/YAML back-ends.
+//! - TODO[4]: `util` - small helpers, ID generation, error types, etc.
//!
//! All public types implement `serde::Serialize / Deserialize` so that they can
//! be persisted easily. The `World` struct also offers a convenient
//! `World::load()` / `World::save()` API that uses the default JSON file
-pub mod epoch_struct;
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+#![deny(clippy::unwrap_used)]
+
#[macro_use]
pub mod error;
+pub mod entity;
+pub mod epoch;
+pub mod naming;
+pub mod stats;
pub mod utils;
use std::io::Result as IoResult;
@@ -49,3 +55,57 @@ where
/// List all ids known to this store.
fn list_ids(&self) -> IoResult>;
}
+/// A trait for types that can be displayed in a command-line tool.
+///
+/// Implementors should provide three levels of representation:
+/// 1. **Full** - a detailed view suitable for a long-running command.
+/// 2. **Short** - a concise, user-friendly view that fits on a single line.
+/// 3. **Oneline** - a compact, machine-friendly string that can be embedded
+/// inside a `Vec` representation.
+///
+/// ## `Vec` support
+///
+/// The trait is implemented generically for `Vec` as long as `T: Displayable`.
+/// This allows you to call `full_display`, `short_display` or `oneline_display`
+/// directly on a vector of displayable items.
+pub trait Displayable {
+ /// Return a fully-described string representation.
+ fn print_full(&self);
+
+ /// Return a short, user-friendly string.
+ fn print_short(&self);
+
+ /// Return a one-liner string, suitable for embedding in a collection
+ /// representation (e.g. a `Vec`). Implementations should avoid
+ /// new-lines to keep the output usable in a single line context.
+ fn oneline_display(&self) -> String;
+
+ /// Print oneline
+ fn print_oneline(&self) {
+ println!("{}", self.oneline_display())
+ }
+}
+
+/// Implement `Displayable` for vectors of displayable items.
+///
+/// The implementation simply delegates to the underlying `T::oneline_display`
+/// method and joins the results with a comma. It works for any `T` that
+/// already implements `Displayable`. This is a **blanket implementation**,
+/// so you do not need to write a manual impl for each concrete type
+impl Displayable for Vec {
+ fn print_full(&self) {
+ self.iter().for_each(|e| e.print_full());
+ }
+
+ fn print_short(&self) {
+ self.iter().for_each(|e| e.print_short());
+ }
+
+ fn oneline_display(&self) -> String {
+ // No brackets - just a flat, comma-separated list.
+ self.iter()
+ .map(|x| x.oneline_display())
+ .collect::>()
+ .join(",")
+ }
+}
diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs
new file mode 100644
index 0000000..6ff4d3b
--- /dev/null
+++ b/lib_efo/src/naming.rs
@@ -0,0 +1,223 @@
+//! Autonaming generator
+//! Supposed to be loaded with the world if needed
+use once_cell::sync::Lazy;
+use rand::prelude::*;
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::io;
+use std::path::{Path, PathBuf};
+
+use crate::entity::EffectApplication;
+use crate::entity::EffectBounds;
+use crate::entity::EntityDuration;
+use crate::error::EpochError;
+use crate::stats::StatPair;
+
+/// The structure that holds everything we need for name generation.
+#[derive(Debug, Serialize, Deserialize, Default)]
+pub struct NamingData {
+ /// First name for characters
+ pub first_names: Vec,
+ /// Last names for characters
+ pub last_names: Vec,
+ /// Good prefixes for towns
+ pub town_prefixes: Vec,
+ /// Good suffixes for town names
+ pub town_suffixes: Vec,
+
+ /// Character adjectives
+ pub character_adjectives: Vec,
+ /// Name prefixes
+ pub character_prefixes: Vec,
+
+ /// A list of event ideas and characteristic associated to it
+ pub event_ideas: Vec,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+/// An event with a description
+pub struct EventDescription {
+ /// A short and meaninful name (an id of a sort)
+ pub name: String,
+
+ /// A short description of the event
+ pub description: String,
+
+ /// The stats affected by the event, and how much (-20 to +20)
+ /// (100 being the maximum of a stat, event a change of -10 is meaningful)
+ pub stats: Vec,
+
+ /// The nature of the event duration
+ pub duration: EntityDuration,
+
+ /// How the event will be (re)applied
+ pub application: EffectApplication,
+
+ /// The maximum bounds of the event
+ pub effect_bounds: EffectBounds,
+}
+
+impl NamingData {
+ /// Load the data from the supplied path.
+ /// If the file does **not** exist, a default (embedded) version is written
+ /// to that path and returned.
+ pub fn load_or_create>(path: P) -> io::Result {
+ let path = path.as_ref();
+
+ if path.exists() {
+ // File exists → read & parse
+ let contents = fs::read_to_string(path)?;
+ let data: Self = serde_json::from_str(&contents)?;
+ Ok(data)
+ } else {
+ // File does *not* exist → create from embedded default
+ let default =
+ serde_json::from_str(DEFAULT_JSON_STR).expect("Default JSON is malformed");
+ // Ensure parent dirs exist
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ let json = serde_json::to_string_pretty(&default)?;
+ fs::write(path, json)?;
+ Ok(default)
+ }
+ }
+
+ /// Generate a random **character** name.
+ pub fn generate_character_name(&self) -> String {
+ let mut rng = rand::rng();
+
+ let binding = "Bobman".into();
+ let first = self.first_names.choose(&mut rng).unwrap_or(&binding);
+ let binding = "McBobintown".into();
+ let last = self.last_names.choose(&mut rng).unwrap_or(&binding);
+ format!("{} {}", first, last).trim().to_string()
+ }
+
+ /// Generate a random **town** name.
+ pub fn generate_town_name(&self) -> String {
+ let mut rng = rand::rng();
+ let binding = "Bobtown".into();
+ let prefix = self.town_prefixes.choose(&mut rng).unwrap_or(&binding);
+ let suffix = self.town_suffixes.choose(&mut rng).unwrap_or(&binding);
+ format!("{}{}", prefix, suffix).trim().to_string()
+ }
+
+ /// Pick a random event idea
+ #[allow(clippy::unwrap_used)]
+ pub fn random_event_idea(&self) -> Result<&EventDescription, EpochError> {
+ let mut rng = rand::rng();
+ self.event_ideas
+ .choose(&mut rng)
+ .ok_or(EpochError::RNGPickError {
+ cause: "Picking a random event".into(),
+ help: None,
+ })
+ }
+
+ /// Generates something like:
+ /// “The Magnificent Sir Aurelius Blackthorn the Swift”
+ /// Random adjective, prefix, base name and suffix are all optional.
+ /// If a list is empty, that part is omitted.
+ pub fn generate_long_character_name(&self) -> String {
+ let mut rng = rand::rng();
+
+ // Helper: get a random element or None
+ let adjective = self.character_adjectives.choose(&mut rng).cloned();
+ let prefix = self.character_prefixes.choose(&mut rng).cloned();
+
+ // Base name (first + last)
+ let base = self.generate_character_name();
+
+ // Assemble pieces
+ let mut parts = Vec::new();
+
+ if let Some(pre) = prefix
+ && rand::random_bool(0.3)
+ {
+ parts.push(pre);
+ }
+
+ parts.push(base);
+
+ if let Some(adj) = adjective
+ && rand::random_bool(0.3)
+ {
+ parts.push(adj);
+ }
+
+ parts.join(" ")
+ }
+}
+
+/// The JSON that ships with the binary.
+/// `include_str!` pulls the file at compile time.
+const DEFAULT_JSON_STR: &str = include_str!("../naming.json");
+
+/// Helper that determines the *runtime* location of the `naming.json` file.
+fn naming_file_path() -> PathBuf {
+ PathBuf::from("naming.json")
+}
+
+/// Global instance that is lazily initialised on first use.
+pub static NAMING: Lazy = Lazy::new(|| {
+ let path = naming_file_path();
+ NamingData::load_or_create(path).expect("Failed to load naming data")
+});
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::stats::ListStats;
+ use std::collections::HashMap;
+
+ #[test]
+ fn try_load() {}
+ #[test]
+ fn basic_testing() {
+ // 1. Generate a character name
+ let character = NAMING.generate_character_name();
+ println!("Character: {}", character);
+
+ // 2. Generate a town name
+ let town = NAMING.generate_town_name();
+ println!("Town: {}", town);
+
+ // 3. Pick an event idea
+ let character = NAMING.generate_long_character_name();
+ println!("Event idea: {}", character);
+
+ let _ = NAMING.random_event_idea();
+ }
+
+ #[test]
+ // TODO[Work]: Add this to a recap function
+ fn test_all_events() {
+ let mut values: HashMap = HashMap::new();
+ for event in &NAMING.event_ideas {
+ println!("Testing event: {:?}", event);
+ assert!(event.stats.len() > 1);
+
+ for stat in &event.stats {
+ if let s @ (ListStats::Demographics
+ | ListStats::Military
+ | ListStats::Economy
+ | ListStats::Social
+ | ListStats::Infrastructure) = stat.stat
+ {
+ panic!("Bad stat used {s:?}")
+ };
+ match stat.value.abs() {
+ 0..5 => (),
+ 5..10 => (),
+ 10..20 => println!("Big stat"),
+ s => panic!("The event has a stat that is way too big {s}"),
+ }
+ let base_value = values.get(&stat.stat).unwrap_or(&0);
+ values.insert(stat.stat, base_value + 1);
+ }
+ }
+ println!("{values:#?}");
+ // panic!()
+ }
+}
diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs
new file mode 100644
index 0000000..124c159
--- /dev/null
+++ b/lib_efo/src/stats.rs
@@ -0,0 +1,488 @@
+//! Module that holds all statistics for an entity and the helper methods that operate on them.
+//!
+//! The statistics are grouped into thematic sections (Demographics, Economy, Social, Military,
+//! Infrastructure). Each field is a `GenericStat`, an internal wrapper around a numeric value
+//! that provides convenience methods such as `max()`, `clamp()`, and arithmetic ops.
+//!
+//! The documentation for each field follows the same three-part template:
+//! * **Purpose** - What the stat represents.
+//! * **Effect** - Gameplay consequence of the stat.
+//! * **Source** - Formula or function that generates the stat value.
+
+#![allow(dead_code)]
+#![deny(clippy::missing_docs_in_private_items)]
+
+use crate::thin_newtype;
+use cli_table::Color;
+use cli_table::Table;
+use colored::Colorize;
+use derive_more::Display;
+use serde::{Deserialize, Serialize};
+mod implementations;
+
+/// Aggregated statistics for a single entity.
+///
+/// The struct is intentionally flat to keep access fast; the fields are logically grouped
+/// by comment blocks that describe each thematic section.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+// Derive more
+#[derive(Table)]
+// #[derive(Add, Sub)]
+pub struct OverallStats {
+ // ──────────────────────── Demographics ────────────────────────
+ /// Total economic health of the entity.
+ ///
+ /// **Purpose** - A single value summarizing all economic indicators.
+ /// **Effect** - Drives tax revenue, spending power, and overall economic influence.
+ /// **Source** - Sum of `industry`, `science`, `trade`, and other economic contributors.
+ #[table(title = "DEM", color = "Color::Blue", bold)]
+ pub demographics: GenericStat,
+ /// Population count.
+ ///
+ /// **Purpose** - The number of citizens living in the entity.
+ /// **Effect** - Determines resource consumption, tax base, and potential unrest.
+ /// **Source** - Updated by the growth/decay formulas each turn.
+ #[table(title = "POP")]
+ pub population: GenericStat,
+
+ /// Per-turn change in population.
+ ///
+ /// **Purpose** - The growth rate of the population.
+ /// **Effect** - Predicts future needs and signals potential social unrest.
+ /// **Source** - Derived from `population`, `happiness`, and `stability`.
+ #[table(title = "GRW")]
+ pub growth_rate: GenericStat,
+
+ /// Crime level (0-1 scale).
+ ///
+ /// **Purpose** - How frequently crimes occur.
+ /// **Effect** - Can trigger riots and reduce stability.
+ /// **Source** - Result of the crime function (influenced by class disparity and law enforcement).
+ #[table(title = "CRM")]
+ pub crime: GenericStat,
+
+ /// Base happiness of the population (0-1 scale).
+ ///
+ /// **Purpose** - A measure of citizen contentment.
+ /// **Effect** - Influences productivity, tax compliance, and unrest.
+ /// **Source** - Output of the happiness function (affected by class, war, infrastructure).
+ #[table(title = "HPY")]
+ pub happiness: GenericStat,
+
+ // ──────────────────────── Economy ────────────────────────
+ /// Aggregate economic health of the entity.
+ ///
+ /// **Purpose** - A single value summarizing all economic metrics.
+ /// **Effect** - Drives revenue, spending, and empire-wide economic influence.
+ /// **Source** - Sum of `food`, `industry`, `science`, `trade`, etc.
+ #[table(title = "ECO", color = "Color::Blue", bold)]
+ pub economy: GenericStat,
+
+ /// Food produced by the entity.
+ ///
+ /// **Purpose** - Amount of consumable resources available.
+ /// **Effect** - Keeps the population alive and productive.
+ /// **Source** - `food = farm_yield + tech_level`.
+ #[table(title = "FOD")]
+ pub food: GenericStat,
+
+ /// Strength of the industry.
+ ///
+ /// **Purpose** - Industrial production capacity.
+ /// **Effect** - Drives tax revenue and unit production.
+ /// **Source** - `industry = factory_output + tech_level`.
+ #[table(title = "IND")]
+ pub industry: GenericStat,
+
+ /// Scientific output.
+ ///
+ /// **Purpose** - Rate of research progress.
+ /// **Effect** - Determines how quickly new technologies are unlocked.
+ /// **Source** - `science = research_center_output + tech_level`.
+ #[table(title = "SCI")]
+ pub science: GenericStat,
+
+ /// Trade volume / exports.
+ ///
+ /// **Purpose** - Measure of export activity.
+ /// **Effect** - Influences influence and wealth.
+ /// **Source** - `trade = trade_network_output`.
+ #[table(title = "TRD")]
+ pub trade: GenericStat,
+ // // ──────────────────────── Social ────────────────────────
+ // /// Overall social prestige.
+ // ///
+ // /// **Purpose** - Reflects the cultural standing of the entity.
+ // /// **Effect** - Affects diplomacy and citizen morale.
+ // /// **Source** - Sum of `culture`, `education`, `tourism`, etc.
+ // #[table(title = "SOC", color = "Color::Blue", bold)]
+ // pub social: GenericStat,
+
+ // /// Cultural output from arts, theatres, museums, etc.
+ // ///
+ // /// **Purpose** - Measure of cultural production.
+ // /// **Effect** - Drives tourism, prestige, and happiness.
+ // /// **Source** - `culture = Σ(cultural_building_output)`.
+ // #[table(title = "CLU")]
+ // pub culture: GenericStat,
+
+ // /// Level of education/literacy.
+ // ///
+ // /// **Purpose** - Measure of the citizenry's knowledge.
+ // /// **Effect** - Improves productivity, science output, and reduces unrest.
+ // /// **Source** - `education = Σ(education_building_output)`.
+ // #[table(title = "EDU")]
+ // pub education: GenericStat,
+
+ // /// Tourism revenue.
+ // ///
+ // /// **Purpose** - Income generated by visitors.
+ // /// **Effect** - Provides an additional income stream.
+ // /// **Source** - `tourism = number_of_tourists x price_per_tourist`.
+ // #[table(title = "TOR")]
+ // pub tourism: GenericStat,
+
+ // /// Cultural influence over the region.
+ // ///
+ // /// **Purpose** - Measure of soft power.
+ // /// **Effect** - Grants diplomatic bonuses and increases sway in the empire.
+ // /// **Source** - `influence = culture x population`.
+ // #[table(title = "INF")]
+ // pub influence: GenericStat,
+
+ // ──────────────────────── Military ────────────────────────
+ /// Overall military power.
+ ///
+ /// **Purpose** - Composite measure of combat capability.
+ /// **Effect** - Determines defensive and offensive strength.
+ /// **Source** - Sum of `army`, `strength`, `fortification`, etc.
+ #[table(title = "MIL", color = "Color::Blue", bold)]
+ pub military: GenericStat,
+
+ /// Number of battle-ready units.
+ ///
+ /// **Purpose** - Size of the active army.
+ /// **Effect** - Directly dictates defense and attack potential.
+ /// **Source** - Sum of all trained and equipped units.
+ #[table(title = "ARM")]
+ pub army: GenericStat,
+
+ /// Composite strength of the army.
+ ///
+ /// **Purpose** - Tech, training, and equipment bonuses aggregated.
+ /// **Effect** - Determines combat effectiveness and required force to defeat an enemy.
+ /// **Source** - `strength = Σ(unit_strength) x tech_bonus x training_bonus`.
+ #[table(title = "STR")]
+ pub strength: GenericStat,
+
+ /// Defensive bonus from fortifications.
+ ///
+ /// **Purpose** - Wall and tower defenses.
+ /// **Effect** - Adds a multiplier to overall defense.
+ /// **Source** - `fortification = Σ(fortification_building_bonus)`.
+ #[table(title = "FRT")]
+ pub fortification: GenericStat,
+
+ /// Threat level facing the entity.
+ ///
+ /// **Purpose** - Likelihood of being attacked.
+ /// **Effect** - Triggers early warning alerts and strategic decisions.
+ /// **Source** - `threat = (enemy_proximity + enemy_strength) / defense`.
+ #[table(title = "THR")]
+ pub threat: GenericStat,
+
+ // ──────────────────────── Infrastructure ────────────────────────
+ /// Total infrastructure power.
+ ///
+ /// **Purpose** - Overall built-environment capacity.
+ /// **Effect** - Supports population size and efficiency.
+ /// **Source** - Sum of all infrastructure components.
+ #[table(title = "IFR", color = "Color::Blue", bold)]
+ pub infrastructure: GenericStat,
+
+ /// Bureaucratic power.
+ ///
+ /// **Purpose** - Efficiency of the city's administrative machinery.
+ /// **Effect** - Improves resource management and policy implementation.
+ /// **Source** - `bureaucracy = Σ(bureaucracy_building_output)`.
+ #[table(title = "BUR")]
+ pub bureaucracy: GenericStat,
+
+ /// Transportation level.
+ ///
+ /// **Purpose** - Availability and quality of transport infrastructure.
+ /// **Effect** - Impacts logistics, mobility, and trade.
+ /// **Source** - `transportation = Σ(transport_building_output)`.
+ #[table(title = "TRP")]
+ pub transportation: GenericStat,
+
+ /// Sprawl / urban density.
+ ///
+ /// **Purpose** - Measure of city sprawl and clutter.
+ /// **Effect** - Affects health, happiness, and infrastructure efficiency.
+ /// **Source** - `sprawl = Σ(sprawl_factor)`.
+ #[table(title = "SPR")]
+ pub sprawl: GenericStat,
+
+ /// Health infrastructure quality.
+ ///
+ /// **Purpose** - Public health capacity.
+ /// **Effect** - Affects population health and can generate unrest.
+ /// **Source** - `health = output_of_health_function` (influenced by sanitation, disease spread, etc.).
+ #[table(title = "HLT")]
+ pub health: GenericStat,
+}
+
+/// Strategic context and meta-data for an entity.
+///
+/// All fields are intentionally simple - the logic that interprets them
+/// lives in separate modules (e.g. `map`, `network`, `governance`).
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct MetaStats {
+ // ──── Location & Spatial Data (hidden) ───────────────────────────────
+ /// Cartesian coordinates of the entity on the world map.
+ ///
+ /// **Purpose** - Position of the entity in the simulation grid.
+ /// **Effect** - Used for distance calculations, visibility, and
+ /// map-based event logic.
+ /// **Source** - Supplied by the map generator.
+ pub position: Position,
+
+ /// Identifier for the capital
+ pub capital: Option,
+
+ // /// List of nearby resource nodes (mines, forests, farms, etc.).
+ // ///
+ // /// **Purpose** - Resource map around the entity.
+ // /// **Effect** - Drives the entity's specialization and determines
+ // /// the default output mix.
+ // /// **Source** - `resources = filter(resource_list, distance ≤ detection_radius)`.
+ // pub resources: Vec,
+
+ // /// The entity's chosen specialization tag
+ // /// (e.g., “Agricultural Hub”, “Industrial Center”).
+ // ///
+ // /// **Purpose** - Identity that dictates default production multipliers.
+ // /// **Effect** - Alters output curves and trade attractiveness.
+ // /// **Source** - `specialization = tag_assigned_by_player_or_ai`.
+ // pub specialization: String,
+
+ // ──── Strategic Positioning (hidden + public) ─────────────────────
+ /// Current governor or leader assigned to the entity.
+ ///
+ /// **Purpose** - Leadership identity.
+ /// **Effect** - Adds personal bonuses and may modify policies
+ /// or diplomatic stance.
+ /// **Source** - `governor = selected_leader_uuid`.
+ pub governor: Option,
+
+ // /// The entity's classification (capital, trade hub, frontier post, etc.).
+ // ///
+ // /// **Purpose** - Functional role within the empire.
+ // /// **Effect** - Alters base production, tax rates, and
+ // /// certain event probabilities.
+ // /// **Source** - `role = tag_assigned_by_player_or_ai`.
+ // pub role: String,
+ /// The faction or empire to which the entity currently belongs.
+ ///
+ /// **Purpose** - Political affiliation.
+ /// **Effect** - Determines diplomatic relations, war status,
+ /// and access to empire-wide bonuses.
+ /// **Source** - `faction = current_faction_uuid`.
+ pub faction: FactionId,
+
+ /// UIDs of all entities the entity is linked to (roads, trade routes,
+ /// alliances, war declarations, etc.).
+ ///
+ /// **Purpose** - Connectivity network.
+ /// **Effect** - Influences economic, military, and diplomatic
+ /// interactions.
+ /// **Source** - `links = Vec` collected from the entity's
+ /// network manager.
+ pub links: Vec,
+
+ /// Prestige / reputation of the entity in the eyes of the empire
+ /// and foreign powers.
+ ///
+ /// **Purpose** - Social standing metric.
+ /// **Effect** - Affects diplomatic influence, trade bonuses,
+ /// and event outcomes.
+ /// **Source** - `prestige = calculate_prestige(...)`.
+ pub prestige: usize,
+}
+
+/// A generic stat pair with (ListStats, GenericStat), used mainly for clap
+/// Accepts two forms
+/// 1. "cri 10" (two separate tokens)
+/// 2. "cri:10" (one token with a separator)
+#[derive(Debug, Serialize, Deserialize)]
+pub struct StatPair {
+ /// The stat selected
+ pub stat: ListStats,
+ /// The value of the modifier
+ pub value: GenericStat,
+}
+
+/// Structure used to indicate position, possess nice helper methods to use as is in the program
+#[derive(Debug, Default, Serialize, Deserialize, Clone)]
+pub struct Position(isize, isize);
+
+impl Position {
+ /// The euclidian distance between two points
+ fn distance(&self, other: &Self) -> isize {
+ ((self.0 - other.0).pow(2) + (self.1 * other.1).pow(2)).isqrt()
+ }
+
+ /// The position in grid coordinates
+ fn to_grid_distance(&self) -> (isize, isize) {
+ (self.0 / 200, self.1 / 200)
+ }
+}
+/// A summary of the stats, only for display purposes
+#[allow(clippy::missing_docs_in_private_items)]
+#[derive(Table)]
+pub struct SummaryStats {
+ #[table(title = "Demo")]
+ demographics: GenericStat,
+ #[table(title = "Eco")]
+ economy: GenericStat,
+ // #[table(title = "Social")]
+ // social: GenericStat,
+ #[table(title = "Milit")]
+ military: GenericStat,
+ #[table(title = "Infra")]
+ infrastructure: GenericStat,
+}
+
+impl From for SummaryStats {
+ fn from(value: OverallStats) -> Self {
+ Self {
+ demographics: value.demographics,
+ economy: value.economy,
+ military: value.military,
+ infrastructure: value.infrastructure,
+ }
+ }
+}
+
+/// Bridge between the CLI and the statistics logic.
+///
+/// Helps convert clap arguments to OverallStats
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[allow(missing_docs)]
+pub enum ListStats {
+ Demographics,
+ Population,
+ Growthrate,
+ Crime,
+ Happiness,
+ Economy,
+ Food,
+ Industry,
+ Science,
+ Trade,
+ Social,
+ Culture,
+ Education,
+ Tourism,
+ Influence,
+ Military,
+ Army,
+ Strength,
+ Fortification,
+ Threat,
+ Infrastructure,
+ Bureaucracy,
+ Transportation,
+ Sprawl,
+ Health,
+}
+
+/// The list of all types of entities
+#[allow(missing_docs)]
+#[derive(Serialize, Deserialize, Debug, Clone, Default)]
+pub enum EntityType {
+ Character,
+ Player,
+ Town,
+ Monster,
+ Blocker,
+ #[default]
+ Event,
+}
+
+/// Trait to implement some symbol representations
+pub trait Symbols {
+ /// Have a small Symbol to resume it
+ fn to_symbol(&self) -> String;
+ /// Have the shortest display possible
+ fn to_shortest(&self) -> String {
+ self.to_symbol()
+ }
+}
+
+// impl Display for T {
+// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+// write!(f, "{}", self.to_symbol())
+// }
+// }
+
+// A stat that is shown to the player *and* can be modified manually.
+thin_newtype!(GenericStat, isize);
+thin_newtype!(TownId, usize);
+thin_newtype!(CharacterId, usize);
+thin_newtype!(FactionId, usize);
+
+// --- TRAITS ---------------------------------------------------------------
+/// A stat is a *game value* that can be converted to two different
+/// normalised ranges - a 100-point range for “gaming” logic and a
+/// 10-point range for “roll & UI” logic. The trait also exposes the
+/// underlying raw value and its visibility.
+///
+// TODO[7]: Change this with Deref+From
+pub trait GameStat {
+ /// Convert the raw integer to a 50-point scale.
+ fn to_100(&self) -> isize {
+ (self.get_value().clamp(0, 120) - 10).min(100)
+ }
+
+ /// Convert the raw integer to a 10-point scale.
+ fn to_10(&self) -> isize {
+ self.to_100() / 10
+ }
+
+ /// As a colored delta (when the stat is used as a delta)
+ fn to_delta(&self) -> String {
+ let get_value = self.get_value();
+ if get_value < 0 {
+ format!("{}", get_value.to_string().red())
+ } else {
+ format!("{}", get_value.to_string().green())
+ }
+ }
+
+ /// Return the raw integer value, always bound to 0-70
+ fn get_value(&self) -> isize;
+
+ /// Return the raw integer value, always bound to 0-70
+ fn change_value(&mut self, value: isize);
+
+ /// Create a Gamestat from it's underlying value
+ fn from_value(value: isize) -> Self
+ where
+ Self: Sized;
+}
+
+/// Trait for objects that can expose a stat via a string key.
+/// The trait returns a *boxed* trait object so callers do not need to know
+/// the concrete type that was stored.
+pub trait Accessible {
+ /// Return the requested stat as a `Box`.
+ /// `None` if the key does not exist.
+ fn get_val(&self, key: &str) -> Option>;
+}
+
+// pub trait Displayable {
+// fn summary(&self) -> String;
+// fn full_description(&self) -> String;
+// }
diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs
new file mode 100644
index 0000000..d0e022c
--- /dev/null
+++ b/lib_efo/src/stats/implementations.rs
@@ -0,0 +1,292 @@
+//! All traits implementatition for the main structs are deffered here
+
+use std::str::FromStr;
+
+use crate::entity::EffectApplication;
+use crate::entity::EffectBounds;
+use crate::entity::EntityDuration;
+use crate::error::EpochError;
+use crate::stats;
+use crate::stats::EntityType;
+use crate::stats::GameStat;
+use crate::stats::GenericStat;
+use crate::stats::ListStats;
+use crate::stats::OverallStats;
+use crate::stats::Position;
+use crate::stats::StatPair;
+use crate::stats::Symbols;
+
+/// Creates a thin, deref-able wrapper around an inner type.
+#[macro_export]
+macro_rules! thin_newtype {
+ ($name:ident, $inner:ty) => {
+ /// Thin wrapper that derefs to the inner type.
+ /// Ideal for zero-overhead new-type patterns.
+ #[repr(transparent)]
+ #[derive(
+ Debug,
+ Clone,
+ Default,
+ PartialEq,
+ Eq,
+ PartialOrd,
+ Ord,
+ Hash,
+ Serialize,
+ Deserialize,
+ Display,
+ )]
+ pub struct $name(pub $inner);
+
+ impl std::ops::Deref for $name {
+ type Target = $inner;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+ }
+
+ impl std::ops::DerefMut for $name {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0
+ }
+ }
+
+ impl From<$inner> for $name {
+ fn from(v: $inner) -> Self {
+ $name(v)
+ }
+ }
+
+ impl From<$name> for $inner {
+ fn from(v: $name) -> Self {
+ v.0
+ }
+ }
+ };
+}
+
+/// Generates an `impl GameStat for ` where the only difference between
+/// multiple implementations is the visibility level.
+///
+/// # Parameters
+/// * `$type`: the concrete type that implements `GameStat`
+/// * `$vis`: the enum variant of `VisibilityLevel` to return
+macro_rules! impl_game_stat {
+ ($type:ident) => {
+ impl GameStat for $type {
+ fn get_value(&self) -> isize {
+ self.0
+ }
+
+ fn change_value(&mut self, value: isize) {
+ self.0 = value;
+ }
+
+ fn from_value(value: isize) -> Self
+ where
+ Self: Sized,
+ {
+ Self(value)
+ }
+ }
+ };
+}
+
+/// A field accessor to be able to modify fields on the fly
+macro_rules! field_accessor {
+ ($name:ident { $($field:ident),* }) => {
+ impl $name {
+ fn get_field(&self, key: &str) -> Option<&dyn GameStat> {
+ match key {
+ $(
+ stringify!($field) => Some(&self.$field),
+ )*
+ _ => None,
+ }
+ }
+
+ fn get_field_mut(&mut self, key: &str) -> Option<&mut dyn GameStat> {
+ match key {
+ $(
+ stringify!($field) => Some(&mut self.$field),
+ )*
+ _ => None,
+ }
+ }
+ }
+ };
+}
+
+impl_game_stat!(GenericStat);
+field_accessor!(OverallStats {
+ demographics,
+ population,
+ growth_rate,
+ crime,
+ happiness,
+ economy,
+ food,
+ industry,
+ science,
+ trade,
+ // social,
+ // culture,
+ // education,
+ // tourism,
+ // influence,
+ military,
+ army,
+ strength,
+ fortification,
+ threat,
+ infrastructure,
+ bureaucracy,
+ transportation,
+ sprawl,
+ health
+});
+
+impl FromStr for ListStats {
+ type Err = EpochError;
+
+ /// Convert an acronym (e.g. `"cri"`) into the corresponding enum variant.
+ fn from_str(s: &str) -> Result {
+ match s.to_ascii_lowercase().as_str() {
+ "dem" | "demog" | "demographics" | "demo" => Ok(ListStats::Demographics),
+ "pop" | "popul" | "populations" => Ok(ListStats::Population),
+ "grow" | "grw" | "growth" => Ok(ListStats::Growthrate),
+ "cri" | "crim" | "crimes" => Ok(ListStats::Crime),
+ "hapn" | "happines" | "hap" => Ok(ListStats::Happiness),
+ "eco" | "economy" | "econ" => Ok(ListStats::Economy),
+ "food" | "fo" | "agr" | "agri" => Ok(ListStats::Food),
+ "industry" | "indus" | "ind" => Ok(ListStats::Industry),
+ "science" | "sci" | "sc" => Ok(ListStats::Science),
+ "trade" | "trd" | "tr" => Ok(ListStats::Trade),
+ "social" | "soc" | "sl" => Ok(ListStats::Social),
+ "culture" | "cul" | "cl" => Ok(ListStats::Culture),
+ "education" | "edu" | "ed" => Ok(ListStats::Education),
+ "tourism" | "tour" | "tm" => Ok(ListStats::Tourism),
+ "influence" | "infl" | "influ" => Ok(ListStats::Influence),
+ "military" | "mil" | "mt" => Ok(ListStats::Military),
+ "army" | "arm" | "ar" => Ok(ListStats::Army),
+ "strength" | "str" | "st" => Ok(ListStats::Strength),
+ "fortification" | "fort" | "ft" => Ok(ListStats::Fortification),
+ "threat" | "thr" | "th" => Ok(ListStats::Threat),
+ "infrastructure" | "infra" | "infr" => Ok(ListStats::Infrastructure),
+ "bureaucracy" | "bureau" | "bur" => Ok(ListStats::Bureaucracy),
+ "transportation" | "trans" | "trns" => Ok(ListStats::Transportation),
+ "sprawl" | "spr" | "spra" => Ok(ListStats::Sprawl),
+ "health" | "hlth" | "hlt" => Ok(ListStats::Health),
+ _ => Err(EpochError::UnknownStatAcronim(s.to_owned())),
+ }
+ }
+}
+
+impl From for &str {
+ fn from(value: ListStats) -> Self {
+ match value {
+ ListStats::Demographics => "demographics",
+ ListStats::Population => "population",
+ ListStats::Growthrate => "growthrate",
+ ListStats::Crime => "crime",
+ ListStats::Happiness => "happiness",
+ ListStats::Economy => "economy",
+ ListStats::Food => "food",
+ ListStats::Industry => "industry",
+ ListStats::Science => "science",
+ ListStats::Trade => "trade",
+ ListStats::Social => "social",
+ ListStats::Culture => "culture",
+ ListStats::Education => "education",
+ ListStats::Tourism => "tourism",
+ ListStats::Influence => "influence",
+ ListStats::Military => "military",
+ ListStats::Army => "army",
+ ListStats::Strength => "strength",
+ ListStats::Fortification => "fortification",
+ ListStats::Threat => "threat",
+ ListStats::Infrastructure => "infrastructure",
+ ListStats::Bureaucracy => "bureaucracy",
+ ListStats::Transportation => "transportation",
+ ListStats::Sprawl => "sprawl",
+ ListStats::Health => "health",
+ }
+ }
+}
+
+impl FromStr for StatPair {
+ type Err = EpochError;
+
+ fn from_str(s: &str) -> Result {
+ let (stat_str, val_str) = if let Some(idx) = s.find(':') {
+ (&s[..idx], &s[idx + 1..])
+ } else {
+ let parts: Vec<&str> = s.split_whitespace().collect();
+ if parts.len() != 2 {
+ return Err(EpochError::IllFormedStatQualifier(s.to_owned()));
+ }
+ (parts[0], parts[1])
+ };
+
+ let stat: ListStats = stat_str.parse()?;
+ let value: isize = val_str
+ .parse()
+ .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?;
+ Ok(StatPair {
+ stat,
+ value: stats::GenericStat(value),
+ })
+ }
+}
+
+impl Symbols for EntityType {
+ fn to_symbol(&self) -> String {
+ match self {
+ EntityType::Character => "[C]".to_string(),
+ EntityType::Player => "[P]".to_string(),
+ EntityType::Town => "[T]".to_string(),
+ EntityType::Monster => "[M]".to_string(),
+ EntityType::Blocker => "[B]".to_string(),
+ EntityType::Event => "[E]".to_string(),
+ }
+ }
+}
+
+impl Symbols for EffectApplication {
+ fn to_symbol(&self) -> String {
+ match self {
+ EffectApplication::Recurring => "⟳".to_string(),
+ EffectApplication::WhenPresent => "⥯".to_string(),
+ EffectApplication::PermanentEffectToApply => "☈".to_string(),
+ EffectApplication::PermanentEffectApplied => "✓".to_string(),
+ }
+ }
+}
+
+impl Symbols for Position {
+ fn to_symbol(&self) -> String {
+ format!("⚓({},{})", self.0, self.1)
+ }
+ fn to_shortest(&self) -> String {
+ format!("{},{}", self.0, self.1)
+ }
+}
+
+impl Symbols for EntityDuration {
+ fn to_symbol(&self) -> String {
+ match self {
+ EntityDuration::Permanent => "∞".to_string(),
+ EntityDuration::Duration(t) => format!("⧗{}", t),
+ EntityDuration::Done => "✔".to_string(),
+ }
+ }
+}
+
+impl Symbols for EffectBounds {
+ fn to_symbol(&self) -> String {
+ format!("({}⭾{})", self.min, self.max)
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod test;
diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs
new file mode 100644
index 0000000..abc882e
--- /dev/null
+++ b/lib_efo/src/stats/implementations/test.rs
@@ -0,0 +1,209 @@
+#![allow(clippy::unwrap_used)]
+use super::*;
+use crate::stats::GameStat;
+use crate::stats::GenericStat;
+use std::str::FromStr;
+
+struct Person {
+ name: GenericStat,
+ age: GenericStat,
+ email: GenericStat,
+}
+
+/// Helper that asserts that a string parses to the expected ListStats variant.
+fn assert_stat_ok(input: &str, expected: ListStats) {
+ let parsed = ListStats::from_str(input).expect("should parse");
+ assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input);
+}
+
+field_accessor!(Person { name, age, email });
+
+#[test]
+fn test_field_accessors() {
+ let person = Person {
+ name: GenericStat(10),
+ age: GenericStat(20),
+ email: GenericStat(120),
+ };
+ let name = person.get_field("name").unwrap();
+ let email = person.get_field("email").unwrap();
+ let age = person.get_field("age").unwrap();
+ assert_eq!(name.to_100(), 0);
+ assert_eq!(age.to_100(), 10);
+ assert_eq!(email.to_100(), 100);
+}
+
+#[test]
+fn test_clap_serialisation() {}
+/// Helper that asserts that a stat pair string parses to the expected `StatPair`.
+fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) {
+ let pair = StatPair::from_str(input).expect("should parse");
+ assert_eq!(pair.stat, expected_stat, "stat mismatch");
+ assert_eq!(pair.value.0, expected_val, "value mismatch");
+}
+#[test]
+fn test_stat_pair_parsing() {
+ // Colon syntax
+ assert_pair_ok("cri:10", ListStats::Crime, 10);
+ assert_pair_ok("POP:-5", ListStats::Population, -5);
+ assert_pair_ok("growth:0", ListStats::Growthrate, 0);
+
+ // Space syntax (clap concatenates two separate args into one string)
+ assert_pair_ok("cri 10", ListStats::Crime, 10);
+ assert_pair_ok("Pop -5", ListStats::Population, -5);
+ assert_pair_ok("grow 0", ListStats::Growthrate, 0);
+}
+#[test]
+fn test_list_stats_all_aliases() {
+ let stats = OverallStats::default();
+ // Demographics
+ assert_stat_ok("dem", ListStats::Demographics);
+ assert_stat_ok("Demog", ListStats::Demographics);
+ assert_stat_ok("DEMOGRAPHICS", ListStats::Demographics);
+ assert_stat_ok("Demo", ListStats::Demographics);
+ stats.get_field(ListStats::Demographics.into());
+ // Population
+ assert_stat_ok("pop", ListStats::Population);
+ assert_stat_ok("Popul", ListStats::Population);
+ assert_stat_ok("POPULATIONS", ListStats::Population);
+ stats.get_field(ListStats::Population.into());
+
+ // Growthrate
+ assert_stat_ok("grow", ListStats::Growthrate);
+ assert_stat_ok("GRW", ListStats::Growthrate);
+ assert_stat_ok("Growth", ListStats::Growthrate);
+ stats.get_field(ListStats::Growthrate.into());
+
+ // Crime
+ assert_stat_ok("cri", ListStats::Crime);
+ assert_stat_ok("CRIM", ListStats::Crime);
+ assert_stat_ok("Crimes", ListStats::Crime);
+ stats.get_field(ListStats::Crime.into());
+
+ // Happiness
+ assert_stat_ok("hapn", ListStats::Happiness);
+ assert_stat_ok("HAPPINES", ListStats::Happiness);
+ assert_stat_ok("hap", ListStats::Happiness);
+ stats.get_field(ListStats::Happiness.into());
+
+ // Economy
+ assert_stat_ok("eco", ListStats::Economy);
+ assert_stat_ok("Economy", ListStats::Economy);
+ assert_stat_ok("econ", ListStats::Economy);
+ stats.get_field(ListStats::Economy.into());
+
+ // Food
+ assert_stat_ok("food", ListStats::Food);
+ assert_stat_ok("fo", ListStats::Food);
+ assert_stat_ok("agr", ListStats::Food);
+ assert_stat_ok("agri", ListStats::Food);
+ stats.get_field(ListStats::Food.into());
+
+ // Industry
+ assert_stat_ok("industry", ListStats::Industry);
+ assert_stat_ok("Indus", ListStats::Industry);
+ assert_stat_ok("ind", ListStats::Industry);
+ stats.get_field(ListStats::Industry.into());
+
+ // Science
+ assert_stat_ok("science", ListStats::Science);
+ assert_stat_ok("sci", ListStats::Science);
+ assert_stat_ok("sc", ListStats::Science);
+ stats.get_field(ListStats::Science.into());
+
+ // Trade
+ assert_stat_ok("trade", ListStats::Trade);
+ assert_stat_ok("trd", ListStats::Trade);
+ assert_stat_ok("tr", ListStats::Trade);
+ stats.get_field(ListStats::Trade.into());
+
+ // Social
+ assert_stat_ok("social", ListStats::Social);
+ assert_stat_ok("soc", ListStats::Social);
+ assert_stat_ok("sl", ListStats::Social);
+ stats.get_field(ListStats::Social.into());
+
+ // Culture
+ assert_stat_ok("culture", ListStats::Culture);
+ assert_stat_ok("cul", ListStats::Culture);
+ assert_stat_ok("cl", ListStats::Culture);
+ stats.get_field(ListStats::Culture.into());
+
+ // Education
+ assert_stat_ok("education", ListStats::Education);
+ assert_stat_ok("edu", ListStats::Education);
+ assert_stat_ok("ed", ListStats::Education);
+ stats.get_field(ListStats::Education.into());
+
+ // Tourism
+ assert_stat_ok("tourism", ListStats::Tourism);
+ assert_stat_ok("tour", ListStats::Tourism);
+ assert_stat_ok("tm", ListStats::Tourism);
+ stats.get_field(ListStats::Tourism.into());
+
+ // Influence
+ assert_stat_ok("influence", ListStats::Influence);
+ assert_stat_ok("infl", ListStats::Influence);
+ assert_stat_ok("influ", ListStats::Influence);
+ stats.get_field(ListStats::Influence.into());
+
+ // Military
+ assert_stat_ok("military", ListStats::Military);
+ assert_stat_ok("mil", ListStats::Military);
+ assert_stat_ok("mt", ListStats::Military);
+ stats.get_field(ListStats::Military.into());
+
+ // Army
+ assert_stat_ok("army", ListStats::Army);
+ assert_stat_ok("arm", ListStats::Army);
+ assert_stat_ok("ar", ListStats::Army);
+ stats.get_field(ListStats::Army.into());
+
+ // Strength
+ assert_stat_ok("strength", ListStats::Strength);
+ assert_stat_ok("str", ListStats::Strength);
+ assert_stat_ok("st", ListStats::Strength);
+ stats.get_field(ListStats::Strength.into());
+
+ // Fortification
+ assert_stat_ok("fortification", ListStats::Fortification);
+ assert_stat_ok("fort", ListStats::Fortification);
+ assert_stat_ok("ft", ListStats::Fortification);
+ stats.get_field(ListStats::Fortification.into());
+
+ // Threat
+ assert_stat_ok("threat", ListStats::Threat);
+ assert_stat_ok("thr", ListStats::Threat);
+ assert_stat_ok("th", ListStats::Threat);
+ stats.get_field(ListStats::Threat.into());
+
+ // Infrastructure
+ assert_stat_ok("infrastructure", ListStats::Infrastructure);
+ assert_stat_ok("infra", ListStats::Infrastructure);
+ assert_stat_ok("infr", ListStats::Infrastructure);
+ stats.get_field(ListStats::Infrastructure.into());
+
+ // Bureaucracy
+ assert_stat_ok("bureaucracy", ListStats::Bureaucracy);
+ assert_stat_ok("bureau", ListStats::Bureaucracy);
+ assert_stat_ok("bur", ListStats::Bureaucracy);
+ stats.get_field(ListStats::Bureaucracy.into());
+
+ // Transportation
+ assert_stat_ok("transportation", ListStats::Transportation);
+ assert_stat_ok("trans", ListStats::Transportation);
+ assert_stat_ok("trns", ListStats::Transportation);
+ stats.get_field(ListStats::Transportation.into());
+
+ // Sprawl
+ assert_stat_ok("sprawl", ListStats::Sprawl);
+ assert_stat_ok("spr", ListStats::Sprawl);
+ assert_stat_ok("spra", ListStats::Sprawl);
+ stats.get_field(ListStats::Sprawl.into());
+
+ // Health
+ assert_stat_ok("health", ListStats::Health);
+ assert_stat_ok("hlth", ListStats::Health);
+ assert_stat_ok("hlt", ListStats::Health);
+ stats.get_field(ListStats::Health.into());
+}
diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs
index c7963dd..0f0ecbc 100644
--- a/lib_efo/src/utils.rs
+++ b/lib_efo/src/utils.rs
@@ -4,6 +4,8 @@
//!
//!
+#![warn(missing_docs, clippy::missing_docs_in_private_items)]
+
use std::path::Path;
use crate::error::EpochError;
@@ -11,20 +13,13 @@ use crate::error::EpochError;
/// Check whether `path` points to a valid Epoch directory.
///
/// A *valid* directory is one that satisfies the expectations of the `epoch` format.
-#[deprecated]
-pub fn is_a_epoch_directory(path: &Path) -> Result<(), EpochError> {
- let dir = path.read_dir().map_err(|_e| {
- EpochError::MainFolderInvalid(path.to_str().unwrap_or_default().to_owned())
- })?;
- for e in dir.flatten() {
- println!("{:?}", e.file_name());
- }
- Ok(())
+pub fn is_a_epoch_directory(_path: &Path) -> Result<(), EpochError> {
+ todo!()
}
-/// Validate that the configuration file at `path` is well‑formed.
+/// Validate that the configuration file at `path` is well-formed.
pub fn is_config_well_formated(_path: &Path) -> Result<(), EpochError> {
- Ok(())
+ todo!()
}
#[cfg(test)]
diff --git a/naming.json b/naming.json
new file mode 100644
index 0000000..a52eba0
--- /dev/null
+++ b/naming.json
@@ -0,0 +1,2360 @@
+{
+ "first_names": [
+ "Aeron",
+ "Brienne",
+ "Cedric",
+ "Darya",
+ "Eldon",
+ "Fiora",
+ "Galen",
+ "Hela",
+ "Ivor",
+ "Juno",
+ "Aldric",
+ "Briar",
+ "Caelum",
+ "Dorin",
+ "Elysia",
+ "Fendrel",
+ "Gryphon",
+ "Hector",
+ "Iseult",
+ "Kael",
+ "Lysander",
+ "Morgath",
+ "Nyx",
+ "Odin",
+ "Riven",
+ "Sylvan",
+ "Thorne",
+ "Valen",
+ "Wraith",
+ "Xander",
+ "Yara",
+ "Zarek",
+ "Artemis",
+ "Baldric",
+ "Corvin",
+ "Draven",
+ "Eira",
+ "Fenris",
+ "Gale",
+ "Helios",
+ "Ivy",
+ "Jasper",
+ "Kara",
+ "Luna",
+ "Mira",
+ "Nimrod",
+ "Onyx",
+ "Peregrine",
+ "Quinn",
+ "Aegon",
+ "Brek",
+ "Calandra",
+ "Darrion",
+ "Eryndor",
+ "Fenn",
+ "Galax",
+ "Hestia",
+ "Ilarion",
+ "Jareth",
+ "Kassandra",
+ "Lyris",
+ "Maelor",
+ "Nyssa",
+ "Oren",
+ "Phaedra",
+ "Quillon",
+ "Rhea",
+ "Soren",
+ "Thalia",
+ "Uther",
+ "Vesper",
+ "Wulfric",
+ "Xara",
+ "Yoren",
+ "Zorath",
+ "Aerith",
+ "Baldrick",
+ "Cress",
+ "Dazai",
+ "Elara",
+ "Fira"
+ ],
+ "last_names": [
+ "Ashwood",
+ "Blackthorn",
+ "Cinderglow",
+ "Dunwynn",
+ "Everfield",
+ "Frosthelm",
+ "Goldleaf",
+ "Holloway",
+ "Iverson",
+ "Jasper",
+ "Ravencrest",
+ "Stormblade",
+ "Nightshade",
+ "Wraithborne",
+ "Dreadmoor",
+ "Ironhart",
+ "Bloodstone",
+ "Stonegate",
+ "Gloomreach",
+ "Sablewick",
+ "Rookhaven",
+ "Ironcrest",
+ "Bleakmoor",
+ "Thornshield",
+ "Wyrmwood",
+ "Darkwater",
+ "Stormbreaker",
+ "Ebonhart",
+ "Bloodbane",
+ "Eclipseborne",
+ "Firethorn",
+ "Silvershade",
+ "Blackfrost",
+ "Sorrowblade",
+ "Stonehelm",
+ "Gravelock",
+ "Voidwalker",
+ "Nightfall",
+ "Ashenfall",
+ "Ashenridge",
+ "Duskfall",
+ "Thornhaven",
+ "Gloombreaker",
+ "Riftwalker",
+ "Althmar",
+ "Brimstone",
+ "Cinderfall",
+ "Duskbane",
+ "Emberforge",
+ "Frostbane",
+ "Grimsbane",
+ "Ironbark",
+ "Jaggedspire",
+ "Keldrith",
+ "Lament",
+ "Mistveil",
+ "Nightglow",
+ "Oathbreaker",
+ "Palegrave",
+ "Quicksilver",
+ "Riftshard",
+ "Shadowforge",
+ "Thornbane",
+ "Umbral",
+ "Vengeance",
+ "Wraithbane",
+ "Xylander",
+ "Yester",
+ "Zephyr",
+ "Blackfire",
+ "Bloodthorn",
+ "Crimsonveil",
+ "Dreadspire",
+ "Eboncrest",
+ "Firebrand",
+ "Grimshard",
+ "Ironheart",
+ "Javelin",
+ "Krait",
+ "Luminous",
+ "Marrowbone",
+ "Nocturne",
+ "Obsidian",
+ "Pyre",
+ "Quagmire",
+ "Reaver",
+ "Sableheart",
+ "Tidebreaker"
+ ],
+ "town_prefixes": [
+ "Ash",
+ "Bright",
+ "Cedar",
+ "Deep",
+ "Elder",
+ "Frost",
+ "Glen",
+ "High",
+ "Iron",
+ "Jade",
+ "Ashen",
+ "Blood",
+ "Cobalt",
+ "Dusk",
+ "Ebon",
+ "Gloom",
+ "Ironforge",
+ "Keen",
+ "Mourn",
+ "Raven",
+ "Storm",
+ "Void",
+ "Wraith",
+ "Night",
+ "Silvers",
+ "Black",
+ "Crimson",
+ "Fire",
+ "Grim",
+ "Briar",
+ "Obsidian",
+ "Shade",
+ "Thorn",
+ "Sable",
+ "Rift",
+ "Dread",
+ "Sorrow",
+ "Bleak",
+ "Eclipse",
+ "Eternity",
+ "Glint",
+ "Gleam",
+ "Hollow",
+ "Lament",
+ "Mire",
+ "Molt",
+ "Nocturne",
+ "Onyx",
+ "Pale",
+ "Rook",
+ "Shimmer",
+ "Stonem",
+ "Stone",
+ "Stonehold",
+ "Stonekeep",
+ "Stoneforge",
+ "Stormfall",
+ "Stormgate",
+ "Stormhold",
+ "Stormreach",
+ "Stormspire",
+ "Stormwind",
+ "Throne",
+ "Twilight",
+ "Valiant",
+ "Valest",
+ "Valer",
+ "Vex",
+ "Vile",
+ "Warden"
+ ],
+ "town_suffixes": [
+ "brook",
+ "dale",
+ "field",
+ "haven",
+ "keep",
+ "moor",
+ "port",
+ "reach",
+ "stone",
+ "vale",
+ "forge",
+ "shard",
+ "hollow",
+ "cove",
+ "hall",
+ "watch",
+ "spire",
+ "glade",
+ "cliff",
+ "glen",
+ "tower",
+ "fort",
+ "hold",
+ "bastion",
+ "crypt",
+ "crossing",
+ "crown",
+ "ridge",
+ "fell",
+ "breach",
+ "briar",
+ "bloom",
+ "field",
+ "river",
+ "canyon",
+ "fen",
+ "crag",
+ "gate",
+ "bridge",
+ "watchtower",
+ "watcher",
+ "mire",
+ "waste",
+ "breach",
+ "fall",
+ "crone",
+ "shadow",
+ "veil",
+ "blight",
+ "soul",
+ "night",
+ "storm",
+ "fire",
+ "ice",
+ "iron",
+ "dark",
+ "glimmer",
+ "glare",
+ "scar",
+ "scarred",
+ "spire",
+ "peak",
+ "ridge",
+ "hall",
+ "hold",
+ "spire",
+ "vale",
+ "vale",
+ "haven",
+ "hollow",
+ "breach",
+ "crust"
+ ],
+ "character_adjectives": [
+ "the Blind",
+ "the Magnificent",
+ "the Cunning",
+ "the Swift",
+ "the Stoic",
+ "the Fearless",
+ "the Enigmatic",
+ "the Shadow",
+ "the Light",
+ "the Wanderer",
+ "the Unbroken",
+ "the Relentless",
+ "the Ruthless",
+ "the Merciless",
+ "the Devourer",
+ "the Ancient",
+ "the Fallen",
+ "the Immortal",
+ "the Vengeful",
+ "the Stormborn",
+ "the Silent",
+ "the Bloodied",
+ "the Corrupt",
+ "the Darkened",
+ "the Ember",
+ "the Crimson",
+ "the Iron",
+ "the Sable",
+ "the Radiant",
+ "the Tempest",
+ "the Gloom",
+ "the Warlord",
+ "the Titan",
+ "the Behemoth",
+ "the Leviathan",
+ "the Doombringer",
+ "the Wraith",
+ "the Sundered",
+ "the Gloomstalker",
+ "the Blight",
+ "the Harbinger",
+ "the Abyssal",
+ "the Scourge",
+ "the Dread",
+ "the Fury",
+ "the Specter",
+ "the Maw",
+ "the Protector",
+ "the Guardian",
+ "the Champion",
+ "the Savior",
+ "the Reaper",
+ "the Harvester",
+ "the Seeker",
+ "the Whisperer",
+ "the Tempest-born",
+ "the Iron-clad",
+ "the Moonlit",
+ "the Sun-scarred",
+ "the Bone-choked",
+ "the Frost-kissed",
+ "the Ashen",
+ "the Shattered",
+ "the Echo-bound",
+ "the Vile",
+ "the Harsh",
+ "the Unseen",
+ "the Unyielding",
+ "of the North",
+ "of the South",
+ "of the East",
+ "of the West",
+ "of the Dark",
+ "of the Light",
+ "of the Forgotten",
+ "of the Broken",
+ "of the Eternal",
+ "of the Shadowlands",
+ "of the Burning",
+ "of the Frozen",
+ "of the Storm",
+ "of the Depths",
+ "of the Maw",
+ "of the Ashen Sea",
+ "of the Crimson Dawn"
+ ],
+ "character_prefixes": [
+ "Sir",
+ "Lady",
+ "Mighty",
+ "Elder",
+ "Grand",
+ "Humble",
+ "Radiant",
+ "Lord",
+ "High",
+ "Royal",
+ "Ancient",
+ "Warden",
+ "Seer",
+ "Master"
+ ],
+ "event_ideas": [
+ {
+ "name": "storm_flood",
+ "description": "A sudden storm floods the river, threatening the local farms.",
+ "stats": [
+ {
+ "stat": "Population",
+ "value": -5
+ },
+ {
+ "stat": "Food",
+ "value": -12
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 10,
+ "max": 70
+ }
+ },
+ {
+ "name": "earthquake",
+ "description": "A massive quake ripples across the region.",
+ "stats": [
+ {
+ "stat": "Transportation",
+ "value": -9
+ },
+ {
+ "stat": "Sprawl",
+ "value": -5
+ },
+ {
+ "stat": "Health",
+ "value": -3
+ },
+ {
+ "stat": "Industry",
+ "value": -2
+ },
+ {
+ "stat": "Population",
+ "value": -10
+ },
+ {
+ "stat": "Happiness",
+ "value": -8
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 10,
+ "max": 110
+ }
+ },
+ {
+ "name": "region_blood_monsoon",
+ "description": "A crimson rain falls over the region, poisoning crops and water sources.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -18
+ },
+ {
+ "stat": "Health",
+ "value": -12
+ },
+ {
+ "stat": "Population",
+ "value": -7
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 10,
+ "max": 110
+ }
+ },
+ {
+ "name": "town_haunted_market",
+ "description": "Spectral merchants appear, selling cryptic ware from a bygone era.",
+ "stats": [
+ {
+ "stat": "Trade",
+ "value": 9
+ },
+ {
+ "stat": "Science",
+ "value": 9
+ },
+ {
+ "stat": "Food",
+ "value": 13
+ },
+ {
+ "stat": "Crime",
+ "value": 7
+ },
+ {
+ "stat": "Threat",
+ "value": 11
+ }
+ ],
+ "duration": {
+ "Duration": 3
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 10,
+ "max": 80
+ }
+ },
+ {
+ "name": "region_darkening_sun",
+ "description": "The sky is shrouded in an unnatural pallid dusk, lowering morale and crop yields.",
+ "stats": [
+ {
+ "stat": "Happiness",
+ "value": -14
+ },
+ {
+ "stat": "Food",
+ "value": -10
+ },
+ {
+ "stat": "Culture",
+ "value": -5
+ }
+ ],
+ "duration": {
+ "Duration": 6
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "town_giant_earthworm",
+ "description": "A colossal earthworm burrows beneath the town, destabilizing foundations and causing tremors.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -5
+ },
+ {
+ "stat": "Industry",
+ "value": -2
+ },
+ {
+ "stat": "Happiness",
+ "value": -12
+ },
+ {
+ "stat": "Fortification",
+ "value": -8
+ },
+ {
+ "stat": "Population",
+ "value": -4
+ }
+ ],
+ "duration": {
+ "Duration": 4
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 30,
+ "max": 70
+ }
+ },
+ {
+ "name": "region_arcane_surge",
+ "description": "An uncontrollable surge of raw sangressence tears through reality, causing unpredictable effects.",
+ "stats": [
+ {
+ "stat": "Science",
+ "value": 12
+ },
+ {
+ "stat": "Education",
+ "value": 8
+ },
+ {
+ "stat": "Population",
+ "value": -6
+ }
+ ],
+ "duration": {
+ "Duration": 6
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 30,
+ "max": 70
+ }
+ },
+ {
+ "name": "town_mushroom_meteor",
+ "description": "A meteor of colossal fungi explodes over a town, releasing spores that induce vivid hallucinations.",
+ "stats": [
+ {
+ "stat": "Health",
+ "value": -10
+ },
+ {
+ "stat": "Crime",
+ "value": 6
+ },
+ {
+ "stat": "Population",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "region_infernal_flood",
+ "description": "Molten rivers run through the region, boiling over cities and devouring forests.",
+ "stats": [
+ {
+ "stat": "Transportation",
+ "value": -4
+ },
+ {
+ "stat": "Sprawl",
+ "value": -5
+ },
+ {
+ "stat": "Happiness",
+ "value": -19
+ },
+ {
+ "stat": "Food",
+ "value": -15
+ },
+ {
+ "stat": "Population",
+ "value": -12
+ }
+ ],
+ "duration": {
+ "Duration": 5
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "region_sand_vortex",
+ "description": "A vortex of shifting sands sweeps the region, burying entire nations under dunes.",
+ "stats": [
+ {
+ "stat": "Bureaucracy",
+ "value": -14
+ },
+ {
+ "stat": "Transportation",
+ "value": -14
+ },
+ {
+ "stat": "Sprawl",
+ "value": -14
+ },
+ {
+ "stat": "Population",
+ "value": -16
+ },
+ {
+ "stat": "Trade",
+ "value": -10
+ }
+ ],
+ "duration": {
+ "Duration": 5
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "region_wind_of_gods",
+ "description": "A relentless gale from the gods tears through the region, scattering armies and wrecking supply lines.",
+ "stats": [
+ {
+ "stat": "Transportation",
+ "value": -12
+ },
+ {
+ "stat": "Army",
+ "value": -9
+ },
+ {
+ "stat": "Population",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 8
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "region_ancient_sunrise",
+ "description": "The sun rises in a crimson glow, amplifying the power of all dark cults and spreading fear.",
+ "stats": [
+ {
+ "stat": "Crime",
+ "value": 9
+ },
+ {
+ "stat": "Happiness",
+ "value": -8
+ },
+ {
+ "stat": "Influence",
+ "value": -5
+ }
+ ],
+ "duration": {
+ "Duration": 7
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "town_forest_of_eyes",
+ "description": "A forest that watches every step, slowly siphoning the life force from any who walk through.",
+ "stats": [
+ {
+ "stat": "Health",
+ "value": -10
+ },
+ {
+ "stat": "Crime",
+ "value": 7
+ },
+ {
+ "stat": "Happiness",
+ "value": 7
+ },
+ {
+ "stat": "Population",
+ "value": -14
+ }
+ ],
+ "duration": {
+ "Duration": 8
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "city_corruption_scandal",
+ "description": "A high‑ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -4
+ },
+ {
+ "stat": "Industry",
+ "value": -3
+ },
+ {
+ "stat": "Science",
+ "value": -3
+ },
+ {
+ "stat": "Trade",
+ "value": -8
+ },
+ {
+ "stat": "Bureaucracy",
+ "value": -7
+ },
+ {
+ "stat": "Crime",
+ "value": 7
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 22,
+ "max": 86
+ }
+ },
+ {
+ "name": "city_tax_reform",
+ "description": "The council implements a sweeping tax overhaul that raises revenue but triggers protests among merchants.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": 9
+ },
+ {
+ "stat": "Industry",
+ "value": 10
+ },
+ {
+ "stat": "Science",
+ "value": 7
+ },
+ {
+ "stat": "Trade",
+ "value": 13
+ },
+ {
+ "stat": "Happiness",
+ "value": -4
+ },
+ {
+ "stat": "Crime",
+ "value": 5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 25,
+ "max": 92
+ }
+ },
+ {
+ "name": "city_watch_mutiny",
+ "description": "The city guard, disgruntled by unpaid wages, mutinies turns bandits.",
+ "stats": [
+ {
+ "stat": "Strength",
+ "value": -6
+ },
+ {
+ "stat": "Crime",
+ "value": 8
+ },
+ {
+ "stat": "Population",
+ "value": -2
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 18,
+ "max": 80
+ }
+ },
+ {
+ "name": "city_water_contamination",
+ "description": "Tainted water leaks into the municipal supply, causing a sudden spike in illnesses.",
+ "stats": [
+ {
+ "stat": "Health",
+ "value": -14
+ },
+ {
+ "stat": "Population",
+ "value": -5
+ },
+ {
+ "stat": "Bureaucracy",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 21,
+ "max": 88
+ }
+ },
+ {
+ "name": "city_bureaucratic_bureaucracy",
+ "description": "A new procedural reform overhauls city administration, halting projects for months and stalling economic growth.",
+ "stats": [
+ {
+ "stat": "Bureaucracy",
+ "value": 14
+ },
+ {
+ "stat": "Sprawl",
+ "value": -9
+ },
+ {
+ "stat": "Health",
+ "value": -7
+ },
+ {
+ "stat": "Food",
+ "value": 3
+ },
+ {
+ "stat": "Industry",
+ "value": 2
+ },
+ {
+ "stat": "Science",
+ "value": 3
+ },
+ {
+ "stat": "Trade",
+ "value": 4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 90
+ }
+ },
+ {
+ "name": "city_guild_suppression",
+ "description": "The council cracks down on the city's merchant guilds, confiscating goods and driving merchants underground.",
+ "stats": [
+ {
+ "stat": "Trade",
+ "value": -11
+ },
+ {
+ "stat": "Crime",
+ "value": 6
+ },
+ {
+ "stat": "Population",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 19,
+ "max": 83
+ }
+ },
+ {
+ "name": "city_civic_riot",
+ "description": "An assembly of disgruntled workers erupts into a violent riot, tearing through market stalls and public buildings.",
+ "stats": [
+ {
+ "stat": "Trade",
+ "value": -12
+ },
+ {
+ "stat": "Happiness",
+ "value": -9
+ },
+ {
+ "stat": "Crime",
+ "value": 10
+ }
+ ],
+ "duration": {
+ "Duration": 2
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 25,
+ "max": 95
+ }
+ },
+ {
+ "name": "city_public_health_crisis",
+ "description": "A mysterious disease spreads through the city's crowded streets, overwhelming the local infirmaries.",
+ "stats": [
+ {
+ "stat": "Health",
+ "value": -3
+ },
+ {
+ "stat": "Population",
+ "value": -3
+ },
+ {
+ "stat": "Happiness",
+ "value": -2
+ }
+ ],
+ "duration": {
+ "Duration": 6
+ },
+ "application": "Recurring",
+ "effect_bounds": {
+ "min": 20,
+ "max": 95
+ }
+ },
+ {
+ "name": "city_transport_infrastructure_fail",
+ "description": "The city's main aqueduct collapses, cutting off water supply to half the districts.",
+ "stats": [
+ {
+ "stat": "Transportation",
+ "value": -15
+ },
+ {
+ "stat": "Population",
+ "value": -4
+ },
+ {
+ "stat": "Bureaucracy",
+ "value": -2
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "city_festival_corruption",
+ "description": "During a grand city festival, officials accept bribes to award contracts, compromising civic integrity.",
+ "stats": [
+ {
+ "stat": "Bureaucracy",
+ "value": -8
+ },
+ {
+ "stat": "Crime",
+ "value": 4
+ },
+ {
+ "stat": "Happiness",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "city_gold_exodus",
+ "description": "A sudden discovery of gold in the hinterlands draws merchants away, leaving local markets starved of currency.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -4
+ },
+ {
+ "stat": "Industry",
+ "value": -4
+ },
+ {
+ "stat": "Trade",
+ "value": -8
+ },
+ {
+ "stat": "Population",
+ "value": -2
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "regional_drought",
+ "description": "An extended dry spell cripples crop yields, driving up food prices and crippling the agrarian economy.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -15
+ },
+ {
+ "stat": "Trade",
+ "value": -13
+ },
+ {
+ "stat": "Happiness",
+ "value": -5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "city_tariff_levy",
+ "description": "The city council imposes a high tariff on imported goods to boost local industry, sparking backlash from merchants.",
+ "stats": [
+ {
+ "stat": "Trade",
+ "value": -10
+ },
+ {
+ "stat": "Food",
+ "value": -4
+ },
+ {
+ "stat": "Industry",
+ "value": -6
+ },
+ {
+ "stat": "Science",
+ "value": -3
+ },
+ {
+ "stat": "Crime",
+ "value": 15
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "market_hoarding",
+ "description": "A powerful merchant cartel hoards staple goods, manipulating prices to inflate profits at the cost of ordinary citizens.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -7
+ },
+ {
+ "stat": "Industry",
+ "value": -6
+ },
+ {
+ "stat": "Trade",
+ "value": -7
+ },
+ {
+ "stat": "Population",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 7
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "industrial_explosion",
+ "description": "A catastrophic blast at the main ironworks destroys equipment and halts production for months.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": -19
+ },
+ {
+ "stat": "Food",
+ "value": -3
+ },
+ {
+ "stat": "Trade",
+ "value": -7
+ },
+ {
+ "stat": "Population",
+ "value": -4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "foreign_investment_boom",
+ "description": "A foreign dynasty invests heavily in local mining, sparking a surge in jobs and wealth but also widening inequality.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": 12
+ },
+ {
+ "stat": "Science",
+ "value": 3
+ },
+ {
+ "stat": "Trade",
+ "value": 8
+ },
+ {
+ "stat": "Crime",
+ "value": 5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 20,
+ "max": 90
+ }
+ },
+ {
+ "name": "tax_evasion_scheme",
+ "description": "A sophisticated tax evasion network siphons off a large portion of city revenue, forcing austerity measures.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -8
+ },
+ {
+ "stat": "Industry",
+ "value": -7
+ },
+ {
+ "stat": "Trade",
+ "value": -9
+ },
+ {
+ "stat": "Crime",
+ "value": 15
+ },
+ {
+ "stat": "Bureaucracy",
+ "value": -6
+ },
+ {
+ "stat": "Population",
+ "value": -2
+ }
+ ],
+ "duration": {
+ "Duration": 6
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 25,
+ "max": 95
+ }
+ },
+ {
+ "name": "currency_devaluation",
+ "description": "The city's coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -8
+ },
+ {
+ "stat": "Industry",
+ "value": -3
+ },
+ {
+ "stat": "Trade",
+ "value": -9
+ },
+ {
+ "stat": "Health",
+ "value": -4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "artisan_fair_success",
+ "description": "A grand artisan fair attracts wealthy patrons, boosting local crafts and increasing export revenues.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": 8
+ },
+ {
+ "stat": "Industry",
+ "value": 9
+ },
+ {
+ "stat": "Trade",
+ "value": 9
+ },
+ {
+ "stat": "Population",
+ "value": 2
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "resource_piracy",
+ "description": "Sea‑borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.",
+ "stats": [
+ {
+ "stat": "Trade",
+ "value": -12
+ },
+ {
+ "stat": "Food",
+ "value": -7
+ },
+ {
+ "stat": "Industry",
+ "value": -6
+ },
+ {
+ "stat": "Threat",
+ "value": 3
+ },
+ {
+ "stat": "Crime",
+ "value": 14
+ }
+ ],
+ "duration": {
+ "Duration": 4
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 25,
+ "max": 95
+ }
+ },
+ {
+ "name": "steel_furnace_overheat",
+ "description": "A critical failure in the city's primary steel furnace sparks an uncontrollable fire, destroying production lines.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": -17
+ },
+ {
+ "stat": "Trade",
+ "value": -9
+ },
+ {
+ "stat": "Happiness",
+ "value": -2
+ },
+ {
+ "stat": "Population",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 24,
+ "max": 95
+ }
+ },
+ {
+ "name": "artisan_tech_innovation",
+ "description": "A guild of master craftsmen invents a new forging technique that doubles output and lowers raw material usage.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": 14
+ },
+ {
+ "stat": "Industry",
+ "value": 13
+ },
+ {
+ "stat": "Science",
+ "value": 15
+ },
+ {
+ "stat": "Trade",
+ "value": 9
+ },
+ {
+ "stat": "Crime",
+ "value": 3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 26,
+ "max": 95
+ }
+ },
+ {
+ "name": "coal_mine_sabotage",
+ "description": "Covert saboteurs collapse a major coal shaft, halting fuel supply to all local factories for weeks.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": -15
+ },
+ {
+ "stat": "Crime",
+ "value": 6
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "foreign_factory_purchase",
+ "description": "A foreign conglomerate purchases the city's largest textile mill, imposing new quotas that reduce local employment.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": -9
+ },
+ {
+ "stat": "Population",
+ "value": -4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 22,
+ "max": 95
+ }
+ },
+ {
+ "name": "blacksmiths_rebel",
+ "description": "Skilled blacksmiths organize a strike demanding better wages, halting the production of critical weapons.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": -10
+ },
+ {
+ "stat": "Strength",
+ "value": -5
+ },
+ {
+ "stat": "Crime",
+ "value": 4
+ }
+ ],
+ "duration": {
+ "Duration": 6
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 22,
+ "max": 95
+ }
+ },
+ {
+ "name": "machine_revolution",
+ "description": "The introduction of automated presses in the leather works cuts labor costs but renders many artisans obsolete.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": 11
+ },
+ {
+ "stat": "Population",
+ "value": -5
+ },
+ {
+ "stat": "Crime",
+ "value": 3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 22,
+ "max": 95
+ }
+ },
+ {
+ "name": "bottleneck_transportation",
+ "description": "The city's main mean of transportation is seized by gangsters, disrupting the flow of raw materials to factories.",
+ "stats": [
+ {
+ "stat": "Transportation",
+ "value": -8
+ },
+ {
+ "stat": "Industry",
+ "value": -6
+ },
+ {
+ "stat": "Crime",
+ "value": 7
+ }
+ ],
+ "duration": {
+ "Duration": 3
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "export_tariff_relief",
+ "description": "An unexpected removal of export tariffs on metal goods opens new markets, boosting production rates.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": 12
+ },
+ {
+ "stat": "Trade",
+ "value": 9
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "smelter_piracy",
+ "description": "A band of raiders captures a shipment of precious ores destined for the city, flooding the market with cheap counterfeit.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": -11
+ },
+ {
+ "stat": "Trade",
+ "value": -7
+ },
+ {
+ "stat": "Crime",
+ "value": 10
+ }
+ ],
+ "duration": {
+ "Duration": 4
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "frontline_betrayal",
+ "description": "A key vanguard commander secretly defects, scattering a significant portion of the army and boosting enemy threat.",
+ "stats": [
+ {
+ "stat": "Strength",
+ "value": -6
+ },
+ {
+ "stat": "Threat",
+ "value": 11
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 22,
+ "max": 95
+ }
+ },
+ {
+ "name": "naval_battle_victory",
+ "description": "The city's navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy's threat level.",
+ "stats": [
+ {
+ "stat": "Strength",
+ "value": 12
+ },
+ {
+ "stat": "Threat",
+ "value": -9
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "disease_in_soldiers",
+ "description": "A virulent pestilence breaks out among the ranks, lowering army numbers and damaging overall health.",
+ "stats": [
+ {
+ "stat": "Army",
+ "value": -14
+ },
+ {
+ "stat": "Health",
+ "value": -10
+ },
+ {
+ "stat": "Strength",
+ "value": -5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "recruitment_panic",
+ "description": "A surge of conscripts floods the army, but poor training causes a sharp drop in combat effectiveness.",
+ "stats": [
+ {
+ "stat": "Army",
+ "value": 8
+ },
+ {
+ "stat": "Strength",
+ "value": -9
+ },
+ {
+ "stat": "Threat",
+ "value": 3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "training_expedition",
+ "description": "A focused military academy expedition hones the troops' skills, raising overall strength at the cost of a temporary manpower drain.",
+ "stats": [
+ {
+ "stat": "Strength",
+ "value": 11
+ },
+ {
+ "stat": "Army",
+ "value": -6
+ },
+ {
+ "stat": "Threat",
+ "value": -5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "spy_operation_success",
+ "description": "A covert spy network uncovers threats around, reducing the threat level and providing a tactical advantage.",
+ "stats": [
+ {
+ "stat": "Threat",
+ "value": -10
+ },
+ {
+ "stat": "Influence",
+ "value": 3
+ },
+ {
+ "stat": "Strength",
+ "value": 4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "war_taxes_harsh",
+ "description": "The council imposes severe war taxes to fund the army, inflating military budgets but cracking public happiness.",
+ "stats": [
+ {
+ "stat": "Strength",
+ "value": 9
+ },
+ {
+ "stat": "Happiness",
+ "value": -8
+ },
+ {
+ "stat": "Food",
+ "value": -3
+ },
+ {
+ "stat": "Industry",
+ "value": -3
+ },
+ {
+ "stat": "Science",
+ "value": -3
+ },
+ {
+ "stat": "Trade",
+ "value": -3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "battlefield_innovation",
+ "description": "A revolutionary tactic is adopted on the front lines, dramatically boosting army strength and lowering enemy threat.",
+ "stats": [
+ {
+ "stat": "Strength",
+ "value": 13
+ },
+ {
+ "stat": "Threat",
+ "value": -8
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "trade_agreement",
+ "description": "The city brokered a favorable trade pact with a neighboring realm, opening new markets for local goods.",
+ "stats": [
+ {
+ "stat": "Trade",
+ "value": 12
+ },
+ {
+ "stat": "Food",
+ "value": 3
+ },
+ {
+ "stat": "Industry",
+ "value": 3
+ },
+ {
+ "stat": "Science",
+ "value": 3
+ },
+ {
+ "stat": "Trade",
+ "value": 3
+ },
+ {
+ "stat": "Population",
+ "value": 3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "peace_council",
+ "description": "A diplomatic summit ends a long-standing border conflict, reducing threat levels and fostering cultural exchange.",
+ "stats": [
+ {
+ "stat": "Trade",
+ "value": 10
+ },
+ {
+ "stat": "Culture",
+ "value": 7
+ },
+ {
+ "stat": "Happiness",
+ "value": 5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 22,
+ "max": 95
+ }
+ },
+ {
+ "name": "bounty_hunt_success",
+ "description": "A coordinated hunt eliminates a notorious calamity, restoring safety to nearby villages.",
+ "stats": [
+ {
+ "stat": "Crime",
+ "value": -12
+ },
+ {
+ "stat": "Threat",
+ "value": -8
+ },
+ {
+ "stat": "Happiness",
+ "value": 4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "technological_breakthrough",
+ "description": "Inventors in the city unveiled new technologies with huge applications in the industrial field.",
+ "stats": [
+ {
+ "stat": "Science",
+ "value": 15
+ },
+ {
+ "stat": "Industry",
+ "value": 6
+ },
+ {
+ "stat": "Food",
+ "value": 3
+ },
+ {
+ "stat": "Trade",
+ "value": 3
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 21,
+ "max": 95
+ }
+ },
+ {
+ "name": "festival_of_luxury",
+ "description": "A grand festival draws wealthy merchants and foreign dignitaries, boosting tourism and local pride.",
+ "stats": [
+ {
+ "stat": "Tourism",
+ "value": 13
+ },
+ {
+ "stat": "Science",
+ "value": 3
+ },
+ {
+ "stat": "Trade",
+ "value": 3
+ },
+ {
+ "stat": "Culture",
+ "value": 3
+ },
+ {
+ "stat": "Influence",
+ "value": 3
+ },
+ {
+ "stat": "Happiness",
+ "value": 6
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 22,
+ "max": 95
+ }
+ },
+ {
+ "name": "military_training_expedition",
+ "description": "An intensive training expedition sharpens the army's tactics, increasing overall strength without cost.",
+ "stats": [
+ {
+ "stat": "Strength",
+ "value": 12
+ },
+ {
+ "stat": "Army",
+ "value": 3
+ },
+ {
+ "stat": "Threat",
+ "value": -5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 21,
+ "max": 95
+ }
+ },
+ {
+ "name": "health_initiative",
+ "description": "A citywide vaccination campaign eradicates a deadly plague, dramatically improving public health.",
+ "stats": [
+ {
+ "stat": "Health",
+ "value": 16
+ },
+ {
+ "stat": "Population",
+ "value": 4
+ },
+ {
+ "stat": "Happiness",
+ "value": 5
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "artisan_summit",
+ "description": "A gathering of master artisans leads to the sharing of techniques that double production efficiency.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": 14
+ },
+ {
+ "stat": "Science",
+ "value": 8
+ },
+ {
+ "stat": "Trade",
+ "value": 3
+ },
+ {
+ "stat": "Population",
+ "value": 2
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 21,
+ "max": 95
+ }
+ },
+ {
+ "name": "infrastructure_repair",
+ "description": "A massive repair drive restores crumbling roads and bridges, slashing travel time and boosting trade.",
+ "stats": [
+ {
+ "stat": "Sprawl",
+ "value": 10
+ },
+ {
+ "stat": "Transportation",
+ "value": 9
+ },
+ {
+ "stat": "Health",
+ "value": 7
+ },
+ {
+ "stat": "Industry",
+ "value": 7
+ },
+ {
+ "stat": "Trade",
+ "value": 7
+ },
+ {
+ "stat": "Food",
+ "value": 5
+ },
+ {
+ "stat": "Trade",
+ "value": 4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 24,
+ "max": 95
+ }
+ },
+ {
+ "name": "cultural_exposition",
+ "description": "The city hosts an international exposition, showcasing its heritage and attracting scholars and tourists alike.",
+ "stats": [
+ {
+ "stat": "Culture",
+ "value": 12
+ },
+ {
+ "stat": "Tourism",
+ "value": 10
+ },
+ {
+ "stat": "Happiness",
+ "value": 4
+ },
+ {
+ "stat": "Influence",
+ "value": 4
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "great_earthquake",
+ "description": "A massive quake rips through the city, shattering buildings, collapsing bridges, and killing thousands.",
+ "stats": [
+ {
+ "stat": "Health",
+ "value": -19
+ },
+ {
+ "stat": "Population",
+ "value": -18
+ },
+ {
+ "stat": "Happiness",
+ "value": -15
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 26,
+ "max": 95
+ }
+ },
+ {
+ "name": "plague_of_scorpion",
+ "description": "A deadly disease spreads through the populace, turning citizens into venom‑infused monsters.",
+ "stats": [
+ {
+ "stat": "Health",
+ "value": -14
+ },
+ {
+ "stat": "Population",
+ "value": -10
+ },
+ {
+ "stat": "Crime",
+ "value": 8
+ }
+ ],
+ "duration": {
+ "Duration": 14
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ },
+ {
+ "name": "oil_fire_in_barnyard",
+ "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army's morale and strength.",
+ "stats": [
+ {
+ "stat": "Industry",
+ "value": -9
+ },
+ {
+ "stat": "Happiness",
+ "value": -4
+ },
+ {
+ "stat": "Threat",
+ "value": 10
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 22,
+ "max": 95
+ }
+ },
+ {
+ "name": "fire_of_sacred_temple",
+ "description": "The city's most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.",
+ "stats": [
+ {
+ "stat": "Culture",
+ "value": -15
+ },
+ {
+ "stat": "Threat",
+ "value": 12
+ },
+ {
+ "stat": "Happiness",
+ "value": -6
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 24,
+ "max": 95
+ }
+ },
+ {
+ "name": "cursed_great_flood",
+ "description": "An unseasonal deluge swallows the city, flooding every district, destroying crops, and causing widespread disease.",
+ "stats": [
+ {
+ "stat": "Food",
+ "value": -13
+ },
+ {
+ "stat": "Industry",
+ "value": -6
+ },
+ {
+ "stat": "Trade",
+ "value": -8
+ },
+ {
+ "stat": "Threat",
+ "value": 13
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 25,
+ "max": 95
+ }
+ },
+ {
+ "name": "massive_barricade_breach",
+ "description": "A minor calamity overpowers the city's fortifications, unleashing a wave of slaughter and chaos.",
+ "stats": [
+ {
+ "stat": "Fortification",
+ "value": -19
+ },
+ {
+ "stat": "Threat",
+ "value": 19
+ },
+ {
+ "stat": "Happiness",
+ "value": -12
+ }
+ ],
+ "duration": {
+ "Duration": 1
+ },
+ "application": "PermanentEffectToApply",
+ "effect_bounds": {
+ "min": 24,
+ "max": 95
+ }
+ },
+ {
+ "name": "invasion_of_the_undead",
+ "description": "A horde of reanimated civilians under the influence of a calamity attack citizens and military alike.",
+ "stats": [
+ {
+ "stat": "Threat",
+ "value": 14
+ },
+ {
+ "stat": "Crime",
+ "value": -10
+ },
+ {
+ "stat": "Population",
+ "value": -12
+ }
+ ],
+ "duration": {
+ "Duration": 5
+ },
+ "application": "WhenPresent",
+ "effect_bounds": {
+ "min": 23,
+ "max": 95
+ }
+ }
+ ]
+}
\ No newline at end of file