package rules

import "errors"

// RuleCategory defines the major categories of rules in EQ2
type RuleCategory int32

const (
	CategoryClient    RuleCategory = 0  // Client-related rules
	CategoryFaction   RuleCategory = 1  // Faction system rules
	CategoryGuild     RuleCategory = 2  // Guild system rules
	CategoryPlayer    RuleCategory = 3  // Player-related rules
	CategoryPVP       RuleCategory = 4  // Player vs Player rules
	CategoryCombat    RuleCategory = 5  // Combat system rules
	CategorySpawn     RuleCategory = 6  // Spawn/NPC rules
	CategoryUI        RuleCategory = 7  // User interface rules
	CategoryWorld     RuleCategory = 8  // World/server rules
	CategoryZone      RuleCategory = 9  // Zone-specific rules
	CategoryLoot      RuleCategory = 10 // Loot system rules
	CategorySpells    RuleCategory = 11 // Spell system rules
	CategoryExpansion RuleCategory = 12 // Expansion flags
	CategoryDiscord   RuleCategory = 13 // Discord integration
)

// RuleType defines specific rule types within categories
type RuleType int32

// CLIENT RULES
const (
	ClientShowWelcomeScreen RuleType = 0 // Show welcome screen to new players
	ClientGroupSpellsTimer  RuleType = 1 // Group spells update timer
	ClientQuestQueueTimer   RuleType = 2 // Quest queue processing timer
)

// FACTION RULES
const (
	FactionAllowBasedCombat RuleType = 0 // Allow faction-based combat
)

// GUILD RULES
const (
	GuildMaxLevel   RuleType = 0 // Maximum guild level
	GuildMaxPlayers RuleType = 1 // Maximum guild members
)

// PLAYER RULES
const (
	PlayerMaxLevel                         RuleType = 0  // Maximum player level
	PlayerMaxLevelOverrideStatus           RuleType = 1  // Status required to override max level
	PlayerMaxPlayers                       RuleType = 2  // Maximum players on server
	PlayerMaxPlayersOverrideStatus         RuleType = 3  // Status required to override max players
	PlayerVitalityAmount                   RuleType = 4  // Vitality bonus amount
	PlayerVitalityFrequency                RuleType = 5  // Vitality bonus frequency
	PlayerMaxAA                            RuleType = 6  // Maximum total AA points
	PlayerMaxClassAA                       RuleType = 7  // Maximum class AA points
	PlayerMaxSubclassAA                    RuleType = 8  // Maximum subclass AA points
	PlayerMaxShadowsAA                     RuleType = 9  // Maximum shadows AA points
	PlayerMaxHeroicAA                      RuleType = 10 // Maximum heroic AA points
	PlayerMaxTradeskillAA                  RuleType = 11 // Maximum tradeskill AA points
	PlayerMaxPrestigeAA                    RuleType = 12 // Maximum prestige AA points
	PlayerMaxTradeskillPrestigeAA          RuleType = 13 // Maximum tradeskill prestige AA points
	PlayerMaxDragonAA                      RuleType = 14 // Maximum dragon AA points
	PlayerMinLastNameLevel                 RuleType = 15 // Minimum level for last name
	PlayerMaxLastNameLength                RuleType = 16 // Maximum last name length
	PlayerMinLastNameLength                RuleType = 17 // Minimum last name length
	PlayerDisableHouseAlignmentRequirement RuleType = 18 // Disable house alignment requirement
	PlayerMentorItemDecayRate              RuleType = 19 // Item decay rate when mentoring
	PlayerTemporaryItemLogoutTime          RuleType = 20 // Time for temporary items to decay
	PlayerHeirloomItemShareExpiration      RuleType = 21 // Heirloom item sharing expiration
	PlayerSwimmingSkillMinSpeed            RuleType = 22 // Minimum swimming speed
	PlayerSwimmingSkillMaxSpeed            RuleType = 23 // Maximum swimming speed
	PlayerSwimmingSkillMinBreathLength     RuleType = 24 // Minimum breath length
	PlayerSwimmingSkillMaxBreathLength     RuleType = 25 // Maximum breath length
	PlayerAutoSkillUpBaseSkills            RuleType = 26 // Auto-skill base skills on level
	PlayerMaxWeightStrengthMultiplier      RuleType = 27 // Strength multiplier for max weight
	PlayerBaseWeight                       RuleType = 28 // Base weight for all classes
	PlayerWeightPercentImpact              RuleType = 29 // Speed impact per weight percent
	PlayerWeightPercentCap                 RuleType = 30 // Maximum weight impact cap
	PlayerCoinWeightPerStone               RuleType = 31 // Coin weight per stone
	PlayerWeightInflictsSpeed              RuleType = 32 // Whether weight affects speed
	PlayerLevelMasterySkillMultiplier      RuleType = 33 // Level mastery skill multiplier
	PlayerTraitTieringSelection            RuleType = 34 // Trait tiering selection rules
	PlayerClassicTraitLevelTable           RuleType = 35 // Use classic trait level table
	PlayerTraitFocusSelectLevel            RuleType = 36 // Trait focus selection level
	PlayerTraitTrainingSelectLevel         RuleType = 37 // Trait training selection level
	PlayerTraitRaceSelectLevel             RuleType = 38 // Trait race selection level
	PlayerTraitCharacterSelectLevel        RuleType = 39 // Trait character selection level
	PlayerStartHPBase                      RuleType = 40 // Starting HP base
	PlayerStartPowerBase                   RuleType = 41 // Starting power base
	PlayerStartHPLevelMod                  RuleType = 42 // HP level modifier
	PlayerStartPowerLevelMod               RuleType = 43 // Power level modifier
	PlayerAllowEquipCombat                 RuleType = 44 // Allow equipment changes in combat
	PlayerMaxTargetCommandDistance         RuleType = 45 // Max distance for target command
	PlayerMinSkillMultiplierValue          RuleType = 46 // Min skill multiplier value
	PlayerHarvestSkillUpMultiplier         RuleType = 47 // Harvest skill up multiplier
	PlayerMiniDingPercentage               RuleType = 48 // Mini ding percentage
)

// PVP RULES
const (
	PVPAllowPVP                  RuleType = 0 // Allow PVP combat
	PVPLevelRange                RuleType = 1 // PVP level range
	PVPInvisPlayerDiscoveryRange RuleType = 2 // Invisible player discovery range
	PVPMitigationModByLevel      RuleType = 3 // PVP mitigation modifier by level
	PVPType                      RuleType = 4 // PVP type (FFA, alignment, etc.)
)

// COMBAT RULES
const (
	CombatMaxRange                        RuleType = 0  // Maximum combat range
	CombatDeathExperienceDebt             RuleType = 1  // Experience debt on death
	CombatGroupExperienceDebt             RuleType = 2  // Share debt with group
	CombatPVPDeathExperienceDebt          RuleType = 3  // PVP death experience debt
	CombatExperienceToDebt                RuleType = 4  // Percentage of experience to debt
	CombatExperienceDebtRecoveryPercent   RuleType = 5  // Debt recovery percentage
	CombatExperienceDebtRecoveryPeriod    RuleType = 6  // Debt recovery period
	CombatEnableSpiritShards              RuleType = 7  // Enable spirit shards
	CombatSpiritShardSpawnScript          RuleType = 8  // Spirit shard spawn script
	CombatShardDebtRecoveryPercent        RuleType = 9  // Shard debt recovery percentage
	CombatShardRecoveryByRadius           RuleType = 10 // Shard recovery by radius
	CombatShardLifetime                   RuleType = 11 // Shard lifetime
	CombatEffectiveMitigationCapLevel     RuleType = 12 // Effective mitigation cap level
	CombatCalculatedMitigationCapLevel    RuleType = 13 // Calculated mitigation cap level
	CombatMitigationLevelEffectivenessMax RuleType = 14 // Max mitigation effectiveness
	CombatMitigationLevelEffectivenessMin RuleType = 15 // Min mitigation effectiveness
	CombatMaxMitigationAllowed            RuleType = 16 // Max mitigation allowed PVE
	CombatMaxMitigationAllowedPVP         RuleType = 17 // Max mitigation allowed PVP
	CombatStrengthNPC                     RuleType = 18 // NPC strength multiplier
	CombatStrengthOther                   RuleType = 19 // Other strength multiplier
	CombatMaxSkillBonusByLevel            RuleType = 20 // Max skill bonus by level
	CombatLockedEncounterNoAttack         RuleType = 21 // Locked encounter no attack
	CombatMaxChaseDistance                RuleType = 22 // Maximum chase distance
)

// SPAWN RULES
const (
	SpawnSpeedMultiplier            RuleType = 0 // Speed multiplier
	SpawnClassicRegen               RuleType = 1 // Use classic regeneration
	SpawnHailMovementPause          RuleType = 2 // Hail movement pause time
	SpawnHailDistance               RuleType = 3 // Hail distance
	SpawnUseHardCodeWaterModelType  RuleType = 4 // Use hardcoded water model type
	SpawnUseHardCodeFlyingModelType RuleType = 5 // Use hardcoded flying model type
)

// UI RULES
const (
	UIMaxWhoResults        RuleType = 0 // Maximum /who results
	UIMaxWhoOverrideStatus RuleType = 1 // Status to override max /who results
)

// WORLD RULES
const (
	WorldDefaultStartingZoneID          RuleType = 0  // Default starting zone ID
	WorldEnablePOIDiscovery             RuleType = 1  // Enable POI discovery
	WorldGamblingTokenItemID            RuleType = 2  // Gambling token item ID
	WorldGuildAutoJoin                  RuleType = 3  // Auto join guild
	WorldGuildAutoJoinID                RuleType = 4  // Auto join guild ID
	WorldGuildAutoJoinDefaultRankID     RuleType = 5  // Auto join default rank ID
	WorldServerLocked                   RuleType = 6  // Server locked
	WorldServerLockedOverrideStatus     RuleType = 7  // Server locked override status
	WorldSyncZonesWithLogin             RuleType = 8  // Sync zones with login
	WorldSyncEquipWithLogin             RuleType = 9  // Sync equipment with login
	WorldUseBannedIPsTable              RuleType = 10 // Use banned IPs table
	WorldLinkDeadTimer                  RuleType = 11 // Link dead timer
	WorldRemoveDisconnectedClientsTimer RuleType = 12 // Remove disconnected clients timer
	WorldPlayerCampTimer                RuleType = 13 // Player camp timer
	WorldGMCampTimer                    RuleType = 14 // GM camp timer
	WorldAutoAdminPlayers               RuleType = 15 // Auto admin players
	WorldAutoAdminGMs                   RuleType = 16 // Auto admin GMs
	WorldAutoAdminStatusValue           RuleType = 17 // Auto admin status value
	WorldDuskTime                       RuleType = 18 // Dusk time
	WorldDawnTime                       RuleType = 19 // Dawn time
	WorldThreadedLoad                   RuleType = 20 // Threaded loading
	WorldTradeskillSuccessChance        RuleType = 21 // Tradeskill success chance
	WorldTradeskillCritSuccessChance    RuleType = 22 // Tradeskill critical success chance
	WorldTradeskillFailChance           RuleType = 23 // Tradeskill fail chance
	WorldTradeskillCritFailChance       RuleType = 24 // Tradeskill critical fail chance
	WorldTradeskillEventChance          RuleType = 25 // Tradeskill event chance
	WorldEditorURL                      RuleType = 26 // Editor URL
	WorldEditorIncludeID                RuleType = 27 // Editor include ID
	WorldEditorOfficialServer           RuleType = 28 // Editor official server
	WorldSavePaperdollImage             RuleType = 29 // Save paperdoll image
	WorldSaveHeadshotImage              RuleType = 30 // Save headshot image
	WorldSendPaperdollImagesToLogin     RuleType = 31 // Send paperdoll images to login
	WorldTreasureChestDisabled          RuleType = 32 // Treasure chest disabled
	WorldStartingZoneLanguages          RuleType = 33 // Starting zone languages
	WorldStartingZoneRuleFlag           RuleType = 34 // Starting zone rule flag
	WorldEnforceRacialAlignment         RuleType = 35 // Enforce racial alignment
	WorldMemoryCacheZoneMaps            RuleType = 36 // Memory cache zone maps
	WorldAutoLockEncounter              RuleType = 37 // Auto lock encounter
	WorldDisplayItemTiers               RuleType = 38 // Display item tiers
	WorldLoreAndLegendAccept            RuleType = 39 // Lore and legend accept
)

// ZONE RULES
const (
	ZoneMinLevelOverrideStatus   RuleType = 0  // Min level override status
	ZoneMinAccessOverrideStatus  RuleType = 1  // Min access override status
	ZoneXPMultiplier             RuleType = 2  // Experience multiplier
	ZoneTSXPMultiplier           RuleType = 3  // Tradeskill experience multiplier
	ZoneWeatherEnabled           RuleType = 4  // Weather enabled
	ZoneWeatherType              RuleType = 5  // Weather type
	ZoneMinWeatherSeverity       RuleType = 6  // Min weather severity
	ZoneMaxWeatherSeverity       RuleType = 7  // Max weather severity
	ZoneWeatherChangeFrequency   RuleType = 8  // Weather change frequency
	ZoneWeatherChangePerInterval RuleType = 9  // Weather change per interval
	ZoneWeatherDynamicMaxOffset  RuleType = 10 // Weather dynamic max offset
	ZoneWeatherChangeChance      RuleType = 11 // Weather change chance
	ZoneSpawnUpdateTimer         RuleType = 12 // Spawn update timer
	ZoneCheckAttackPlayer        RuleType = 13 // Check attack player
	ZoneCheckAttackNPC           RuleType = 14 // Check attack NPC
	ZoneHOTime                   RuleType = 15 // Heroic opportunity time
	ZoneUseMapUnderworldCoords   RuleType = 16 // Use map underworld coords
	ZoneMapUnderworldCoordOffset RuleType = 17 // Map underworld coord offset
	ZoneSharedMaxPlayers         RuleType = 18 // Shared zone max players
	ZoneRegenTimer               RuleType = 19 // Regeneration timer
	ZoneClientSaveTimer          RuleType = 20 // Client save timer
	ZoneShutdownDelayTimer       RuleType = 21 // Shutdown delay timer
	ZoneWeatherTimer             RuleType = 22 // Weather timer
	ZoneSpawnDeleteTimer         RuleType = 23 // Spawn delete timer
)

// LOOT RULES
const (
	LootRadius                     RuleType = 0 // Loot pickup radius
	LootAutoDisarmChest            RuleType = 1 // Auto disarm chest
	LootChestTriggerRadiusGroup    RuleType = 2 // Chest trigger radius group
	LootChestUnlockedTimeDrop      RuleType = 3 // Chest unlocked time drop
	LootAllowChestUnlockByDropTime RuleType = 4 // Allow chest unlock by drop time
	LootChestUnlockedTimeTrap      RuleType = 5 // Chest unlocked time trap
	LootAllowChestUnlockByTrapTime RuleType = 6 // Allow chest unlock by trap time
	LootSkipGrayMob                RuleType = 7 // Skip loot from gray mobs
	LootDistributionTime           RuleType = 8 // Loot distribution time
)

// SPELLS RULES
const (
	SpellsNoInterruptBaseChance            RuleType = 0  // No interrupt base chance
	SpellsEnableFizzleSpells               RuleType = 1  // Enable fizzle spells
	SpellsDefaultFizzleChance              RuleType = 2  // Default fizzle chance
	SpellsFizzleMaxSkill                   RuleType = 3  // Fizzle max skill
	SpellsFizzleDefaultSkill               RuleType = 4  // Fizzle default skill
	SpellsEnableCrossZoneGroupBuffs        RuleType = 5  // Enable cross zone group buffs
	SpellsEnableCrossZoneTargetBuffs       RuleType = 6  // Enable cross zone target buffs
	SpellsPlayerSpellSaveStateWaitInterval RuleType = 7  // Player spell save state wait interval
	SpellsPlayerSpellSaveStateCap          RuleType = 8  // Player spell save state cap
	SpellsRequirePreviousTierScribe        RuleType = 9  // Require previous tier scribe
	SpellsCureSpellID                      RuleType = 10 // Cure spell ID
	SpellsCureCurseSpellID                 RuleType = 11 // Cure curse spell ID
	SpellsCureNoxiousSpellID               RuleType = 12 // Cure noxious spell ID
	SpellsCureMagicSpellID                 RuleType = 13 // Cure magic spell ID
	SpellsCureTraumaSpellID                RuleType = 14 // Cure trauma spell ID
	SpellsCureArcaneSpellID                RuleType = 15 // Cure arcane spell ID
	SpellsMinistrationSkillID              RuleType = 16 // Ministration skill ID
	SpellsMinistrationPowerReductionMax    RuleType = 17 // Ministration power reduction max
	SpellsMinistrationPowerReductionSkill  RuleType = 18 // Ministration power reduction skill
	SpellsMasterSkillReduceSpellResist     RuleType = 19 // Master skill reduce spell resist
	SpellsUseClassicSpellLevel             RuleType = 20 // Use classic spell level
)

// EXPANSION RULES
const (
	ExpansionGlobalFlag  RuleType = 0 // Global expansion flag
	ExpansionHolidayFlag RuleType = 1 // Global holiday flag
)

// DISCORD RULES
const (
	DiscordEnabled    RuleType = 0 // Discord enabled
	DiscordWebhookURL RuleType = 1 // Discord webhook URL
	DiscordBotToken   RuleType = 2 // Discord bot token
	DiscordChannel    RuleType = 3 // Discord channel
	DiscordListenChan RuleType = 4 // Discord listen channel
)

// Rule validation constants
const (
	MaxRuleValueLength    = 1024 // Maximum rule value length
	MaxRuleCombinedLength = 2048 // Maximum combined rule string length
	MaxRuleNameLength     = 64   // Maximum rule name length
)

// Database constants
const (
	TableRuleSets       = "rulesets"
	TableRuleSetDetails = "ruleset_details"
	TableVariables      = "variables"
	DefaultRuleSetIDVar = "default_ruleset_id"
)

// Error variables
var (
	ErrRuleNotFound        = errors.New("rule not found")
	ErrRuleSetNotFound     = errors.New("rule set not found")
	ErrInvalidRuleCategory = errors.New("invalid rule category")
	ErrInvalidRuleType     = errors.New("invalid rule type")
	ErrInvalidRuleValue    = errors.New("invalid rule value")
	ErrDuplicateRuleSet    = errors.New("duplicate rule set")
	ErrRuleSetNotActive    = errors.New("rule set not active")
	ErrGlobalRuleSetNotSet = errors.New("global rule set not set")
	ErrZoneRuleSetNotFound = errors.New("zone rule set not found")
	ErrRuleValueTooLong    = errors.New("rule value too long")
	ErrRuleNameTooLong     = errors.New("rule name too long")
)

// Rule category names for string conversion
var CategoryNames = map[RuleCategory]string{
	CategoryClient:    "Client",
	CategoryFaction:   "Faction",
	CategoryGuild:     "Guild",
	CategoryPlayer:    "Player",
	CategoryPVP:       "PVP",
	CategoryCombat:    "Combat",
	CategorySpawn:     "Spawn",
	CategoryUI:        "UI",
	CategoryWorld:     "World",
	CategoryZone:      "Zone",
	CategoryLoot:      "Loot",
	CategorySpells:    "Spells",
	CategoryExpansion: "Expansion",
	CategoryDiscord:   "Discord",
}

// Reverse mapping for category name lookup
var CategoryByName = make(map[string]RuleCategory)

func init() {
	// Initialize reverse category mapping
	for category, name := range CategoryNames {
		CategoryByName[name] = category
	}
}

// GetCategoryName returns the string name for a rule category
func GetCategoryName(category RuleCategory) string {
	if name, exists := CategoryNames[category]; exists {
		return name
	}
	return "Unknown"
}

// GetCategoryByName returns the rule category for a string name
func GetCategoryByName(name string) (RuleCategory, bool) {
	category, exists := CategoryByName[name]
	return category, exists
}
