using UnityEngine;

[CreateAssetMenu(fileName = "New Enemy", menuName = "RPG/Characters/Enemy")]
[System.Serializable]
public class EnemyCharacterData : ScriptableObject
{
    [Header("Basic Info")]
    public string enemyName = "New Enemy";
    [TextArea(2, 4)]
    public string description = "A fearsome enemy";
    public Sprite enemySprite;

    [Header("Core Stats")]
    [Range(1, 100)]
    public int maxHealth = 10;
    [Range(1, 30)]
    public int attack = 8;
    [Range(1, 30)]
    public int constitution = 5;
    [Range(1, 30)]
    public int dexterity = 3;
    [Range(1, 30)]
    public int wisdom = 2;

    [Header("Combat Modifiers")]
    [Range(-10, 10)]
    public int initModifier = -2;
    [Range(-10, 10)]
    public int damageModifier = 0;
    [Range(-10, 10)]
    public int spellModifier = 0;
    [Range(1, 50)]
    public int movementSpeed = 10;
    [Range(1, 30)]
    public int armorClass = 6;

    [Header("Weapon Configuration")]
    public WeaponItem preferredWeapon; // Assign a WeaponItem asset

    [Header("AI Behavior")]
    [Range(0f, 1f)]
    public float aggressiveness = 0.7f; // How likely to attack vs defend
    [Range(1, 10)]
    public int threatLevel = 1; // Used for encounter balancing

    [Header("Rewards")]
    [Range(0, 1000)]
    public int goldReward = 10;
    [Range(0, 500)]
    public int experienceReward = 25;
    public DropTable dropTable; // For item drops

    [Header("Visual Settings")]
    public Material enemyMaterial;
    public GameObject enemyModel; // 3D model prefab
    [Range(0.5f, 3f)]
    public float modelScale = 1f;

    [Header("Special Abilities")]
    public bool canCastSpells = false;
    public bool hasRangedAttack = false;
    public bool canFly = false;
    public bool regeneratesHealth = false;
    [Range(0, 10)]
    public int healthRegenPerTurn = 0;

    /// <summary>
    /// Creates a complete enemy character script class from this data
    /// </summary>
    public string GenerateCharacterScript()
    {
        string className = enemyName.Replace(" ", "") + "Character";
        string weaponCreationCode = GenerateWeaponCreationCode();

        return $@"using UnityEngine;

/// <summary>
/// Auto-generated enemy character: {enemyName}
/// {description}
/// Generated from EnemyCharacterData
/// </summary>
public class {className} : Character
{{
    [Header(""{enemyName} Configuration"")]
    public WeaponItem preferredWeapon; // Assign weapon item asset in inspector
    
    protected override void InitializeStats()
    {{
        // Basic Stats
        MaxHealth = {maxHealth};
        CurrentHealth = MaxHealth;
        Attack = {attack};
        Constitution = {constitution};
        Dexterity = {dexterity};
        Wisdom = {wisdom};
        
        // Combat Modifiers  
        InitModifier = {initModifier};
        DamageModifier = {damageModifier};
        SpellModifier = {spellModifier};
        MovementSpeed = {movementSpeed};
        ArmorClass = {armorClass};
        
        // Special Abilities
        // TODO: Implement special abilities based on data
        // Can Cast Spells: {canCastSpells.ToString().ToLower()}
        // Has Ranged Attack: {hasRangedAttack.ToString().ToLower()}
        // Can Fly: {canFly.ToString().ToLower()}
        // Regenerates Health: {regeneratesHealth.ToString().ToLower()}
        // Health Regen Per Turn: {healthRegenPerTurn}
    }}
    
    public override Character Spawn(int count)
    {{
        name = ""{enemyName}"";
        CharacterName = ""{enemyName}"";
        if (count > 1)
        {{
            name += "" "" + count;
            CharacterName += "" "" + count;
        }}
        
        return this;
    }}
    
    public override Weapon GetWeapon()
    {{
        // Return null to trigger direct weapon creation from WeaponItem
        return CreateDirectWeapon();
    }}
    
    protected override Weapon CreateDirectWeapon()
    {{
{weaponCreationCode}
    }}
    
    /// <summary>
    /// Gets the reward data for defeating this enemy
    /// </summary>
    public (int gold, int experience) GetRewards()
    {{
        return ({goldReward}, {experienceReward});
    }}
    
    /// <summary>
    /// Gets the threat level for encounter balancing
    /// </summary>
    public int GetThreatLevel()
    {{
        return {threatLevel};
    }}
}}";
    }

    private string GenerateWeaponCreationCode()
    {
        return $@"        // Create weapon from WeaponItem asset
        if (preferredWeapon != null)
        {{
            spawnedWeapon = preferredWeapon.CreateWeaponInstance(this.transform);
            if (spawnedWeapon != null)
            {{
                spawnedWeapon.SetWielder(this);
                return spawnedWeapon;
            }}
        }}
        
        // Fallback: Create basic sword if no weapon item assigned
        GameObject weaponObject = new GameObject(""Basic Weapon"");
        weaponObject.transform.SetParent(this.transform, false);
        spawnedWeapon = weaponObject.AddComponent<SimpleSword>();
        spawnedWeapon.SetWielder(this);
        return spawnedWeapon;";
    }
}

[System.Serializable]
public class DropTable
{
    [System.Serializable]
    public class DropItem
    {
        public string itemName;
        [Range(0f, 1f)]
        public float dropChance;
        [Range(1, 10)]
        public int maxQuantity = 1;
    }

    public DropItem[] possibleDrops;
}