local Defs = {}

Defs.TUNING = {
    minState = 0,
    maxState = 3,

    lowRiskThreshold = 0.34,
    mediumRiskThreshold = 0.50,
    severeRiskThreshold = 0.68,
    recoveryRiskThreshold = 0.22,
    ambientRiskThreshold = 0.12,

    minDaysAfterEmergence = 1,
    exposureDaysLow = 2,
    exposureDaysMedium = 1,
    exposureDaysSevere = 1,
    exposureDaysAmbient = 4,
    treatmentProtectionDays = 3,
    seasonalThreatFrequency = "1-2",
    infectionChanceMultiplier = 0.35,
    ambientInfectionChanceMultiplier = 0.50,

    infectionChanceBaseDaily = 0.38,
    infectionChanceRiskScale = 0.65,
    ambientInfectionChanceBaseDaily = 0.08,
    ambientInfectionChanceRiskScale = 0.18,

    infectionSpotsLow = 2,
    infectionSpotsInitialMin = 3,
    infectionSpotsInitialMax = 5,
    infectionSpotsMedium = 4,
    infectionSpotsSevere = 6,
    infectionRadiusMin = 5.5,
    infectionRadiusMax = 12.0,
    infectionInitialRadiusMultiplier = 2.0,
    infectionRadiusSeverityBonus = 2.5,

    escalationSpreadSpotsBase = 4,
    escalationSpreadSpotsPerLevel = 4,
    escalationSpreadRadiusMin = 7.0,
    escalationSpreadRadiusMax = 11.0,
    escalationSpreadRadiusMultiplier = 2.6,
    escalationSpawnNewSpotsBase = 4,
    escalationSpawnNewSpotsPerLevel = 3,
    escalationSpawnOffsetMin = 6.0,
    escalationSpawnOffsetMax = 14.0,
    escalationSpawnRadiusMin = 4.0,
    escalationSpawnRadiusMax = 8.0,
    stageExpandDelayHoursMin = 5.0,
    stageExpandDelayHoursMax = 12.0,
    stage3RepeatExpandHoursMin = 3.0,
    stage3RepeatExpandHoursMax = 5.0,
    stage2DamageTickHours = 12.0,
    stage2DamageSpotsPerTick = 4,
    stage3DamageTickHours = 6.0,
    stage3DamageSpotsPerTick = 24,
    playerInfectionChanceMultiplier = 1.35,
    playerInfectionSpotsMultiplier = 1.50,
    playerInfectionRadiusMultiplier = 1.15,
    playerSpreadSeedsMultiplier = 2.35,
    playerSpreadSpawnMultiplier = 2.60,
    npcInfectionChanceMultiplier = 0.60,
    npcInfectionSpotsMultiplier = 0.75,
    npcInfectionRadiusMultiplier = 0.90,
    npcSpreadSeedsMultiplier = 0.75,
    npcSpreadSpawnMultiplier = 0.70,
    npcStageExpandDelayHoursMin = 7.0,
    npcStageExpandDelayHoursMax = 14.0,

    simpleNeglectPeriodDays = 2,
    simpleHealPeriodDays = 2,
    severeEscalationDays = 1,
    exposureDecay = 1,

    manualRebuildThreshold = 0.86,
    manualRebuildHighThreshold = 0.96,

    damageRiskThreshold = 0.58,
    damageEnableHardDestroy = true,
    damageDestroyMinStage = 2,
    damageStage2DestroyIslandsMin = 1,
    damageStage2DestroyIslandsMax = 1,
    damageStage2DestroyRadiusMinFactor = 0.10,
    damageStage2DestroyRadiusMaxFactor = 0.18,
    damageStage2DestroyIslandSizeMinFactor = 0.38,
    damageStage2DestroyIslandSizeMaxFactor = 0.62,
    damageStage2DestroyThresholdMin = 0.28,
    damageStage2DestroyThresholdMax = 0.52,
    damageDestroyIslandsMin = 1,
    damageDestroyIslandsMax = 3,
    damageDestroyIslandOffsetFactor = 0.55,
    damageDestroyBaseDisease = 0.03,
    damageDestroyBasePest = 0.08,
    damageDestroyStateBonus = 0.05,
    damageDestroyRiskBonus = 0.12,
    damageDestroyBiasMin = 0.02,
    damageDestroyBiasMax = 0.12,
    damageDestroyRadiusMinFactor = 0.24,
    damageDestroyRadiusMaxFactor = 0.45,
    damageDestroyIslandSizeMinFactor = 0.70,
    damageDestroyIslandSizeMaxFactor = 1.10,
    damageDestroyThresholdMin = 0.18,
    damageDestroyThresholdMax = 0.46,
    npcFieldsMaxDiseaseStage = 2,
    npcAutoHealBeforeStage3 = true,
    npcAutoHealSpotsMin = 2,
    npcAutoHealSpotsMax = 4,
    npcAutoHealRadiusMin = 5.0,
    npcAutoHealRadiusMax = 10.0,

    careActionHeal = {
        sprayer = 1,
        weeder = 1,
        cultivator = 1,
        plow = 1,
        roller = 1,
        mulcher = 1
    },

    targetedCareHeal = 2,

    defaultLowMultiplier = 0.96,
    defaultMediumMultiplier = 0.88,
    defaultHighMultiplier = 0.74
}

Defs.DEFAULT_THREAT_KEY = "bmp_dis_powdery"

Defs.THREATS = {
    bmp_dis_powdery = {
        category = "disease",
        fruits = {
            "GRAPE", "SUNFLOWER", "SOYBEAN", "COTTON", "OLIVE", "CANOLA",
            "GREENBEAN", "PEA", "SPINACH", "RICE", "RICELONGGRAIN", "MUSTARD",
            "ALFALFA", "CLOVER", "FLOWERINGCATCHCROP"
        },
        windows = {"early", "mid", "late", "harvest"},
        weights = {spray = 1.00, water = 0.75, weed = 0.40, stubble = 0.20},
        cures = {"sprayer", "fungicide"},
        lowMultiplier = 0.97,
        mediumMultiplier = 0.89,
        highMultiplier = 0.76
    },

    bmp_dis_rust = {
        category = "disease",
        fruits = {
            "WHEAT", "BARLEY", "RYE", "OAT", "MAIZE", "SORGHUM",
            "SUNFLOWER", "CANOLA", "WINTERWHEAT", "WINTERBARLEY", "TRITICALE", "SPELT",
            "MUSTARD", "VETCHRYE", "GREENRYE", "SILAGEMAIZE"
        },
        windows = {"early", "mid", "late", "harvest"},
        weights = {spray = 0.95, weed = 0.70, water = 0.45, stubble = 0.30},
        cures = {"sprayer"},
        lowMultiplier = 0.96,
        mediumMultiplier = 0.87,
        highMultiplier = 0.74
    },

    bmp_dis_septoria = {
        category = "disease",
        fruits = {
            "WHEAT", "BARLEY", "OAT", "RYE", "WINTERWHEAT", "WINTERBARLEY",
            "TRITICALE", "SPELT", "VETCHRYE", "GREENRYE"
        },
        windows = {"mid", "late"},
        weights = {stubble = 1.00, water = 0.80, spray = 0.70, weed = 0.35},
        cures = {"sprayer", "mulcher", "fungicide"},
        lowMultiplier = 0.95,
        mediumMultiplier = 0.86,
        highMultiplier = 0.72
    },

    bmp_dis_rootrot = {
        category = "disease",
        fruits = {
            "POTATO", "SUGARBEET", "SOYBEAN", "BEETROOT", "CARROT", "PARSNIP",
            "ALFALFA", "CLOVER"
        },
        windows = {"early", "mid", "late", "harvest"},
        weights = {water = 1.00, plow = 0.85, lime = 0.45, spray = 0.25},
        cures = {"sprayer", "fungicide", "plow", "cultivator"},
        lowMultiplier = 0.95,
        mediumMultiplier = 0.84,
        highMultiplier = 0.70
    },

    bmp_dis_snowmold = {
        category = "disease",
        fruits = {
            "WHEAT", "BARLEY", "RYE", "GRASS", "OAT", "WINTERWHEAT",
            "WINTERBARLEY", "TRITICALE", "SPELT", "VETCHRYE", "GREENRYE", "FIELDGRASS",
            "ALFALFA", "CLOVER"
        },
        windows = {"early", "mid"},
        weights = {water = 0.90, stubble = 0.75, spray = 0.55},
        cures = {"sprayer", "mulcher", "fungicide"},
        lowMultiplier = 0.97,
        mediumMultiplier = 0.90,
        highMultiplier = 0.80
    },

    bmp_dis_lateblight = {
        category = "disease",
        fruits = {"POTATO"},
        windows = {"mid", "late", "harvest"},
        weights = {water = 1.00, spray = 0.90, weed = 0.30},
        cures = {"sprayer", "fungicide"},
        lowMultiplier = 0.94,
        mediumMultiplier = 0.82,
        highMultiplier = 0.66
    },

    bmp_pest_aphids = {
        category = "pest",
        fruits = {
            "WHEAT", "BARLEY", "OAT", "RYE", "MAIZE", "SUNFLOWER",
            "SOYBEAN", "POTATO", "GREENBEAN", "PEA", "SPINACH", "CANOLA",
            "BEETROOT", "SUGARBEET", "CARROT", "PARSNIP", "WINTERWHEAT", "WINTERBARLEY",
            "TRITICALE", "SPELT", "MUSTARD", "SILAGEMAIZE", "VETCHRYE", "GREENRYE",
            "FIELDGRASS", "ALFALFA", "CLOVER", "FLOWERINGCATCHCROP"
        },
        windows = {"early", "mid", "late", "harvest"},
        weights = {weed = 1.00, spray = 0.80, stubble = 0.35, water = 0.20},
        cures = {"sprayer", "weeder"},
        lowMultiplier = 0.97,
        mediumMultiplier = 0.90,
        highMultiplier = 0.78
    },

    bmp_pest_caterpillars = {
        category = "pest",
        fruits = {
            "MAIZE", "SOYBEAN", "SUNFLOWER", "COTTON", "GREENBEAN", "PEA",
            "CANOLA", "MUSTARD", "SILAGEMAIZE", "ALFALFA", "CLOVER", "FLOWERINGCATCHCROP"
        },
        windows = {"early", "mid", "late", "harvest"},
        weights = {weed = 0.85, spray = 0.90, stubble = 0.40, roller = 0.15},
        cures = {"sprayer", "weeder"},
        lowMultiplier = 0.96,
        mediumMultiplier = 0.87,
        highMultiplier = 0.73
    },

    bmp_pest_wireworm = {
        category = "pest",
        fruits = {
            "POTATO", "SUGARBEET", "BEETROOT", "CARROT", "PARSNIP", "MAIZE",
            "SILAGEMAIZE"
        },
        windows = {"early", "mid", "late", "harvest"},
        weights = {plow = 1.00, stubble = 0.70, lime = 0.40, weed = 0.30},
        cures = {"cultivator", "plow"},
        lowMultiplier = 0.95,
        mediumMultiplier = 0.85,
        highMultiplier = 0.71
    }
}

Defs.DISEASES = Defs.THREATS

local threatKeys = {}
local threatKeyById = {}
for key, _ in pairs(Defs.THREATS) do
    table.insert(threatKeys, key)
end
table.sort(threatKeys)

for index, key in ipairs(threatKeys) do
    Defs.THREATS[key].id = index
    threatKeyById[index] = key
end

local function contains(list, value)
    if list == nil then
        return false
    end

    for _, item in ipairs(list) do
        if item == value then
            return true
        end
    end

    return false
end

function Defs:getThreat(key)
    return self.THREATS[key]
end

function Defs:getThreatKeys()
    return threatKeys
end

function Defs:getThreatCategory(key)
    local threat = self:getThreat(key)
    return threat and threat.category or nil
end

function Defs:getThreatId(key)
    local threat = self:getThreat(key)
    return threat and threat.id or 0
end

function Defs:getThreatKeyById(id)
    return threatKeyById[tonumber(id or 0) or 0]
end

function Defs:pickRandomThreatKey()
    if #threatKeys == 0 then
        return self.DEFAULT_THREAT_KEY
    end

    return threatKeys[math.random(1, #threatKeys)]
end

function Defs:getThreatMultiplier(key, state)
    local tuning = self.TUNING or {}
    local threat = self:getThreat(key) or {}
    local normalizedState = math.max(0, math.min(tonumber(state or 0) or 0, tuning.maxState or 3))

    if normalizedState <= 0 then
        return 1.0
    end

    if normalizedState == 1 then
        return threat.lowMultiplier or tuning.defaultLowMultiplier or 0.96
    end

    if normalizedState == 2 then
        return threat.mediumMultiplier or tuning.defaultMediumMultiplier or 0.88
    end

    return threat.highMultiplier or tuning.defaultHighMultiplier or 0.74
end

function Defs:isThreatCompatible(key, fruitName, growthWindow)
    local threat = self:getThreat(key)
    if threat == nil then
        return false
    end

    if not contains(threat.fruits, fruitName) then
        return false
    end

    if threat.windows == nil or #threat.windows == 0 then
        return true
    end

    return contains(threat.windows, growthWindow)
end

function Defs:getCompatibleThreatKeys(fruitName, growthWindow)
    local exact = {}
    local fruitOnly = {}

    for _, key in ipairs(threatKeys) do
        local threat = self:getThreat(key)
        if threat ~= nil and contains(threat.fruits, fruitName) then
            table.insert(fruitOnly, key)
            if threat.windows == nil or #threat.windows == 0 or contains(threat.windows, growthWindow) then
                table.insert(exact, key)
            end
        end
    end

    if #exact > 0 then
        return exact
    end

    return fruitOnly
end

_G.DiseaseDefs = Defs





