def get_unit_max_strength(unit, ally, params=None):
    strength = int(unit["unit"].get("-strength", "0"))
    _, island, map_item = get_current_island(params)
    if not ally and island != None and "strength" in map_item["island"][island]:
        strengths = simple_list(map_item["island"][island]["strength"])
        strength = apply_map_mod_strength(unit, strength, strengths)
        # print("Mod strenghts",repr(strengths))
    elif ally:
        strength = handle_strength_upgrades(strength, unit)
    return strength
def apply_consumable_direct_impact(meta, selected_consumable, targeted_unit,
                                   units, units_strengths, params, ally,
                                   active_consumables):
    unit_current_strength = units_strengths[targeted_unit]
    direct_impact = int(selected_consumable["consumable"].get("-di", 0))
    damage = direct_impact
    against = simple_list(selected_consumable["consumable"].get("against", ''))
    # TODO: also units have against mod damage: Man_O_War_Battleship, Spec_Ops_Man_O_War_Battleship, LE_Elite_ManOWar_Battleship,
    # pirateship04(npc), pirateship03(npc), pirateinfantry02 PU2(npc), pirateInfantry02 PU4(npc), pirateAntiAir02(npc), pirateAntiAir03(npc),
    # pirateBalloon01(npc), pirateFighter01, pirateBomber01, pirateFighter02, pirateBomber02, pirateFighter03,pirateBomber03, pirateFighter05, pirateBomber05,
    # pirateUBoat03, pirateCaptainKrunsch and many more
    for a in against:
        if a['-type'] in (get_unit_type(units[targeted_unit]),
                          get_unit_terrain(units[targeted_unit])):
            damage *= float(a['-mod'])

    if damage > 0 and is_shielded(("ally" if ally else "enemy", targeted_unit),
                                  active_consumables) == True:
        consume_shield(("ally" if ally else "enemy", targeted_unit),
                       active_consumables)

    elif units_strengths[targeted_unit] > 0:  #can't damage/heal dead units
        units_strengths[targeted_unit] -= damage
        if not ally and 1 >= units_strengths[targeted_unit] > 0:
            units_strengths[targeted_unit] = 0
            print("Enemy inced to prevent 1 strength")
        if units_strengths[targeted_unit] <= 0:
            units_strengths[targeted_unit] = 0  # dead
            print("Enemy unit" if not ally else "Friendly unit", targeted_unit,
                  "down")
            if ally:
                handle_quest_progress(
                    meta,
                    progress_battle_damage_count("battleKill", 1, {},
                                                 units[targeted_unit]))
                doBattleRewards("kill", unit_current_strength,
                                unit_current_strength, 0)

        if units_strengths[targeted_unit] > get_unit_max_strength(
                units[targeted_unit], ally, params):
            print("Limiting heal to max strength")
            units_strengths[targeted_unit] = get_unit_max_strength(
                units[targeted_unit], ally, params)
        print("Consumable", selected_consumable["-code"],
              selected_consumable["consumable"].get("-diweapon", ""),
              "used to " + ("friendly" if ally else "baddie:"), targeted_unit,
              "di", direct_impact, "damage", damage)
    else:
        print("Consumable", selected_consumable["-code"],
              selected_consumable["consumable"].get("-diweapon", ""),
              "not used to dead " + ("friendly" if ally else "baddie:"),
              targeted_unit, "di", direct_impact, "damage", damage)

    if "-chipFactor" in selected_consumable["consumable"]:
        for i in range(len(units)):
            if units_strengths[i] > 0:
                collateral_unit_current_strength = units_strengths[i]
                colateral_damage = math.ceil(
                    get_adjacent_factor(targeted_unit, i, len(units)) *
                    int(selected_consumable["consumable"]["-chipFactor"]) *
                    int(selected_consumable["consumable"].get("-di", 0)) / 100)
                for a in against:
                    if a['-type'] in (get_unit_type(units[i]),
                                      get_unit_terrain(units[i])):
                        colateral_damage *= float(a['-mod'])
                units_strengths[i] -= colateral_damage
                if not ally and 1 >= units_strengths[i] > 0:
                    units_strengths[i] = 0
                    print("Enemy inced to prevent 1 strength")
                print("Enemy unit" if not ally else "Friendly unit suffered",
                      collateral_unit_current_strength - units_strengths[i],
                      "collateral damage")
                if units_strengths[i] <= 0:
                    units_strengths[i] = 0  # dead
                    print("Enemy unit" if not ally else "Friendly unit", i,
                          "down by collateral damage")
                    if ally:
                        handle_quest_progress(
                            meta,
                            progress_battle_damage_count(
                                "battleKill", 1, {}, units[i]))
                        doBattleRewards("kill",
                                        collateral_unit_current_strength,
                                        collateral_unit_current_strength, 0)
def init_battle(params):
    if 'target' not in params:
        if params.get("name") == "AI":
            print("AI fleet")
            future_enemy_fleet = get_new_enemy_fleet_name()
            friendlies = [
                lookup_item_by_code(friendly.split(',')[0])
                for friendly in session['fleets'][get_previous_fleet(
                    get_previous_fleet(get_previous_fleet(
                        future_enemy_fleet)))]
            ]
            baddies = [
                lookup_item_by_code(baddy[1:]) for sub_fleet in simple_list(
                    session['fleets'][get_previous_fleet(
                        get_previous_fleet(future_enemy_fleet))])
                for baddy, count in sub_fleet.items()
                for i in range(int(count))
            ]
        elif isinstance(
                simple_list(
                    session['fleets']
                    [params['fleet'] if params['fleet'] else params['name']])
            [0], str):
            print("Ally direct target")
            friendlies = [
                lookup_item_by_code(friendly.split(',')[0])
                for friendly in session['fleets']
                [params['fleet'] if params['fleet'] else params['name']]
            ]
            baddies = [
                lookup_item_by_code(baddy[1:])
                for sub_fleet in simple_list(session['fleets'][get_next_fleet(
                    params['fleet'] if params['fleet'] else params['name'])])
                for baddy, count in sub_fleet.items()
                for i in range(int(count))
            ]
        else:
            baddies = [
                lookup_item_by_code(baddy[1:]) for sub_fleet in simple_list(
                    session['fleets']
                    [params['fleet'] if params['fleet'] else params['name']])
                for baddy, count in sub_fleet.items()
                for i in range(int(count))
            ]
            friendlies = [
                lookup_item_by_code(friendly.split(',')[0])
                for friendly in session['fleets'][get_previous_fleet(
                    params['fleet'] if params['fleet'] else params['name'])]
            ]
    elif params['target'].startswith('fleet'):
        baddies = [
            lookup_item_by_code(baddy[1:])
            for sub_fleet in simple_list(session['fleets'][params['target']])
            for baddy, count in sub_fleet.items() for i in range(int(count))
        ]
        friendlies = [
            lookup_item_by_code(friendly.split(',')[0])
            for friendly in session['fleets'][params['fleet']]
        ]
    elif params['target'] == "FleetName":
        baddies = [
            lookup_item_by_code(baddy.split(',')[0]) for sub_fleet in
            simple_list(session['fleets'][get_next_fleet(params['fleet'])])
            for baddy in sub_fleet["units"]
        ]
        friendlies = [
            lookup_item_by_code(friendly.split(',')[0])
            for friendly in session['fleets'][params['fleet']]
        ]
    else:
        quest = lookup_quest(params['target'])
        tasks = get_tasks(quest)
        [task] = [t for t in tasks if t["_action"] == "fight"]
        enemy_fleet = lookup_item_by_code(task["_item"])
        baddies = [
            lookup_item_by_code(baddie_slot["-item"])
            for baddie_slot in simple_list(enemy_fleet["baddie"])
        ]
        friendlies = [
            lookup_item_by_code(friendly[1:])
            for friendly, count in task["fleet"].items()
            for i in range(int(count))
        ]

    if "battle" not in session or not session["battle"]:
        baddie_strengths = [
            get_unit_max_strength(baddie, False, params) for baddie in baddies
        ]
        friendly_strengths = [
            get_unit_max_strength(friendly, True) for friendly in friendlies
        ]
        active_consumables = []
        session["battle"] = (friendly_strengths, baddie_strengths,
                             active_consumables)
    else:
        (friendly_strengths, baddie_strengths,
         active_consumables) = session["battle"]
    return friendlies, friendly_strengths, baddies, baddie_strengths, active_consumables