"""Generate original pixel sprites, armor UV textures and equipment progression data.

All bitmaps are drawn from coordinates; no external assets or image libraries are needed.
Run from any directory after editing palettes, recipes or translations here.
"""
from pathlib import Path
import json
import struct
import zlib

ROOT = Path(__file__).resolve().parents[1]
RES = ROOT / 'src/main/resources'
NS = 'mydimension_lord'
SETS = ('lord',)
SLOTS = ('helmet', 'chestplate', 'leggings', 'boots')
PALETTES = {
    'lord': ('171323', '373044', '62596f', 'b7a17e', 'f4d691', 'ad68ee', 'e4baff'),
}


def write(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    if isinstance(data, dict): data = (json.dumps(data, ensure_ascii=False, indent=2) + '\n').encode()
    if not path.exists() or path.read_bytes() != data: path.write_bytes(data)


class Canvas:
    def __init__(self, w, h):
        self.w, self.h = w, h
        self.pixels = [[(0, 0, 0, 0) for _ in range(w)] for _ in range(h)]
    def pixel(self, x, y, color):
        if 0 <= x < self.w and 0 <= y < self.h:
            self.pixels[y][x] = tuple(bytes.fromhex(color)) + (255,) if color else (0, 0, 0, 0)
    def rect(self, x0, y0, x1, y1, color):
        for y in range(y0, y1 + 1):
            for x in range(x0, x1 + 1): self.pixel(x, y, color)
    def line(self, x0, y0, x1, y1, color):
        dx, dy = abs(x1-x0), -abs(y1-y0)
        sx, sy = 1 if x0 < x1 else -1, 1 if y0 < y1 else -1
        error = dx + dy
        while True:
            self.pixel(x0, y0, color)
            if (x0, y0) == (x1, y1): break
            e2 = error * 2
            if e2 >= dy: error += dy; x0 += sx
            if e2 <= dx: error += dx; y0 += sy
    def png(self):
        def chunk(kind, data): return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
        raw = b''.join(b'\0' + bytes(v for pixel in row for v in pixel) for row in self.pixels)
        return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', self.w, self.h, 8, 6, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'')


def sprite(kind, palette):
    edge, dark, steel, rim, light, energy, glow = palette
    c = Canvas(16, 16)
    if kind == 'helmet':
        c.rect(4, 3, 11, 12, edge); c.rect(3, 5, 12, 11, edge)
        c.rect(4, 5, 11, 10, dark); c.rect(5, 4, 10, 5, steel)
        c.line(4, 7, 11, 7, rim); c.rect(5, 8, 10, 9, edge)
        c.pixel(5, 8, energy); c.pixel(10, 8, energy)
        c.rect(4, 10, 5, 12, steel); c.rect(10, 10, 11, 12, steel)
        c.line(7, 3, 8, 3, light); c.rect(7, 4, 8, 6, energy); c.pixel(7, 4, glow)
    elif kind == 'chestplate':
        c.rect(4, 4, 11, 13, edge); c.rect(2, 3, 5, 6, edge); c.rect(10, 3, 13, 6, edge)
        c.rect(3, 4, 4, 5, steel); c.rect(11, 4, 12, 5, steel)
        c.rect(5, 5, 10, 11, dark); c.rect(5, 6, 10, 8, steel)
        c.line(5, 6, 7, 8, rim); c.line(10, 6, 8, 8, rim)
        c.rect(7, 7, 8, 9, energy); c.pixel(7, 7, glow)
        c.rect(5, 12, 10, 12, rim); c.rect(6, 4, 9, 4, None)
    elif kind == 'leggings':
        c.rect(3, 3, 12, 6, edge); c.rect(4, 7, 6, 13, edge); c.rect(9, 7, 11, 13, edge)
        c.rect(4, 4, 11, 5, dark); c.line(4, 4, 11, 4, rim)
        c.pixel(7, 4, energy); c.pixel(8, 4, glow)
        c.rect(4, 7, 5, 12, steel); c.rect(9, 7, 10, 12, steel)
        c.line(4, 9, 5, 9, energy); c.line(9, 9, 10, 9, energy)
        c.line(4, 12, 5, 12, rim); c.line(9, 12, 10, 12, rim)
    elif kind == 'boots':
        c.rect(4, 5, 6, 10, edge); c.rect(9, 5, 11, 10, edge)
        c.rect(2, 10, 6, 13, edge); c.rect(9, 10, 13, 13, edge)
        c.rect(4, 6, 5, 10, steel); c.rect(9, 6, 10, 10, steel)
        c.line(4, 6, 5, 6, rim); c.line(9, 6, 10, 6, rim)
        c.pixel(4, 8, energy); c.pixel(9, 8, energy)
        c.rect(3, 11, 5, 11, steel); c.rect(10, 11, 12, 11, steel)
        c.line(3, 12, 5, 12, rim); c.line(10, 12, 12, 12, rim)
    elif kind == 'alloy':
        c.rect(4, 5, 11, 11, edge); c.rect(2, 7, 13, 10, edge)
        c.rect(3, 7, 12, 9, dark); c.line(5, 6, 11, 6, light)
        c.line(4, 7, 10, 7, rim); c.line(4, 10, 11, 10, steel)
        c.line(6, 8, 9, 8, energy); c.pixel(7, 8, glow); c.pixel(10, 9, energy)
    elif kind in ('mind_shard', 'lord_core'):
        for y in range(2, 14):
            half = min(y-2, 13-y) // 2 + 1
            for x in range(7-half, 9+half): c.pixel(x, y, edge)
        c.line(7, 3, 4, 9, rim); c.line(8, 3, 11, 9, steel)
        c.line(7, 4, 6, 10, energy); c.line(8, 4, 9, 10, glow)
        c.line(6, 10, 8, 12, rim); c.pixel(7, 5, glow)
        if kind == 'lord_core':
            for x, y in ((1, 7), (14, 7), (7, 1), (7, 14)):
                c.pixel(x, y, light)
            c.line(2, 7, 4, 7, energy); c.line(11, 7, 13, 7, energy)
    elif kind == 'lord_upgrade_template':
        c.rect(3, 2, 12, 13, edge); c.rect(4, 3, 11, 12, steel)
        c.line(4, 3, 11, 3, light); c.line(4, 4, 4, 11, rim)
        c.rect(5, 5, 10, 10, dark); c.rect(7, 5, 8, 10, energy)
        c.line(5, 7, 10, 7, energy); c.pixel(7, 7, glow); c.line(6, 12, 10, 12, rim)
    elif kind == 'dimension_blade':
        c.line(2, 13, 13, 2, edge); c.line(3, 13, 13, 3, edge)
        c.line(4, 12, 14, 2, edge); c.line(5, 11, 14, 3, rim)
        c.line(6, 10, 13, 3, steel); c.line(6, 9, 12, 3, energy)
        c.line(7, 9, 13, 3, glow); c.pixel(13, 2, light)
        c.line(3, 8, 7, 12, edge); c.line(3, 7, 8, 12, rim)
        c.pixel(4, 8, light); c.pixel(7, 11, light)
        c.line(2, 13, 4, 11, dark); c.pixel(2, 14, rim); c.pixel(1, 13, light)
    elif kind == 'dimension_pickaxe':
        c.line(2, 14, 11, 5, edge); c.line(3, 14, 12, 5, edge)
        c.line(3, 13, 10, 6, rim); c.line(4, 13, 11, 6, dark)
        c.line(4, 3, 11, 3, edge); c.line(7, 2, 12, 2, edge)
        c.line(5, 4, 12, 4, steel); c.line(6, 3, 11, 3, light)
        c.line(11, 3, 14, 6, edge); c.line(11, 4, 14, 7, rim)
        c.line(10, 4, 13, 7, steel); c.line(14, 7, 14, 10, edge)
        c.line(13, 7, 13, 9, energy); c.pixel(13, 10, light)
        c.rect(9, 4, 10, 5, energy); c.pixel(9, 4, glow)
        c.pixel(3, 13, light); c.pixel(7, 9, energy)
    return c


def armor_texture(palette, leggings=False):
    edge, dark, steel, rim, light, energy, glow = palette
    c = Canvas(64, 32)
    # Standard vanilla humanoid UV islands: head, body, legs and arms.
    for x0, y0, w, h in ((0, 0, 32, 16), (16, 16, 24, 16), (0, 16, 16, 16), (40, 16, 16, 16)):
        c.rect(x0, y0, x0+w-1, y0+h-1, dark)
        for y in range(y0, y0+h):
            for x in range(x0, x0+w):
                if (x*3+y*5) % 17 == 0: c.pixel(x, y, steel)
    for x in (0, 8, 16, 24):
        c.line(x, 8, x+7, 8, rim); c.line(x, 15, x+7, 15, steel)
    # Visible helmet face with open eyes and bright central crest.
    c.rect(9, 10, 14, 12, edge); c.line(10, 11, 11, 11, energy); c.line(12, 11, 13, 11, energy)
    c.rect(11, 8, 12, 9, glow); c.rect(9, 13, 14, 13, rim)
    if not leggings:
        c.line(20, 21, 23, 24, rim); c.line(27, 21, 24, 24, rim)
        c.rect(23, 23, 24, 26, energy); c.pixel(23, 23, glow)
        c.line(20, 30, 27, 30, rim); c.line(20, 28, 27, 28, steel)
        for x in (40, 44, 48, 52):
            c.line(x, 21, x+3, 21, rim); c.line(x, 26, x+3, 26, energy); c.line(x, 30, x+3, 30, rim)
        for x in (0, 4, 8, 12):
            c.line(x, 27, x+3, 27, rim); c.line(x, 29, x+3, 29, energy); c.line(x, 31, x+3, 31, steel)
    else:
        c.line(16, 20, 39, 20, rim); c.rect(23, 20, 24, 21, glow)
        for x in (0, 4, 8, 12):
            c.line(x, 23, x+3, 23, steel); c.line(x, 27, x+3, 27, energy); c.line(x, 30, x+3, 30, rim)
    return c


def item(name, bitmap):
    write(RES / f'assets/{NS}/textures/item/{name}.png', bitmap.png())
    write(RES / f'assets/{NS}/models/item/{name}.json', {'parent': 'minecraft:item/handheld' if name in ('dimension_blade', 'dimension_pickaxe') else 'minecraft:item/generated', 'textures': {'layer0': f'{NS}:item/{name}'}})
    write(ROOT / f'ports/1.21.11/resources/assets/{NS}/items/{name}.json', {'model': {'type': 'minecraft:model', 'model': f'{NS}:item/{name}'}})


def recipe(name, data): write(RES / f'data/{NS}/recipes/{name}.json', data)
def ingredient(name): return {'item': name if ':' in name else f'{NS}:{name}'}
def shapeless(name, names, count=1, result=None):
    recipe(name, {'type': 'minecraft:crafting_shapeless', 'ingredients': [ingredient(n) for n in names], 'result': {'item': f'{NS}:{result or name}', 'count': count}})
def shaped(name, pattern, key, count=1, result=None):
    recipe(name, {'type': 'minecraft:crafting_shaped', 'pattern': pattern, 'key': {k: ingredient(v) for k, v in key.items()}, 'result': {'item': f'{NS}:{result or name}', 'count': count}})


def main():
    # Remove only obsolete assets produced by the initial three-set design.
    for source_root in (RES, ROOT / 'ports/1.21.11/resources'):
        for namespace_root in (source_root / f'assets/{NS}', source_root / f'data/{NS}'):
            assert namespace_root.resolve().is_relative_to(ROOT.resolve())
            for path in namespace_root.rglob('*'):
                if path.is_file() and (path.name.startswith(('warden_', 'rift_', 'starborn_', 'repairs_warden', 'repairs_rift', 'repairs_starborn'))
                        or path.stem in ('warden', 'rift', 'starborn')):
                    path.unlink()
    for set_id in SETS:
        palette = PALETTES[set_id]
        for slot in SLOTS:
            name = f'{set_id}_{slot}'
            item(name, sprite(slot, palette))
            recipe(name + '_smithing', {'type': 'minecraft:smithing_transform', 'template': ingredient('lord_upgrade_template'),
                    'base': ingredient(f'minecraft:netherite_{slot}'), 'addition': ingredient('lord_core'), 'result': {'item': f'{NS}:{name}'}})
        item(f'{set_id}_alloy', sprite('alloy', palette))
        for layer in (1, 2):
            bitmap = armor_texture(palette, leggings=layer == 2).png()
            write(RES / f'assets/{NS}/textures/models/armor/{set_id}_layer_{layer}.png', bitmap)
            kind = 'humanoid' if layer == 1 else 'humanoid_leggings'
            write(ROOT / f'ports/1.21.11/resources/assets/{NS}/textures/entity/equipment/{kind}/{set_id}.png', bitmap)
        write(ROOT / f'ports/1.21.11/resources/assets/{NS}/equipment/{set_id}.json', {'layers': {
            'humanoid': [{'texture': f'{NS}:{set_id}'}], 'humanoid_leggings': [{'texture': f'{NS}:{set_id}'}]}})
    for name in ('mind_shard', 'lord_core', 'lord_upgrade_template', 'dimension_blade', 'dimension_pickaxe'):
        item(name, sprite(name, PALETTES['lord']))
    recipe('dimension_blade_smithing', {'type': 'minecraft:smithing_transform', 'template': ingredient('lord_upgrade_template'),
            'base': ingredient('minecraft:netherite_sword'), 'addition': ingredient('lord_core'), 'result': {'item': f'{NS}:dimension_blade'}})
    recipe('dimension_pickaxe_smithing', {'type': 'minecraft:smithing_transform', 'template': ingredient('lord_upgrade_template'),
            'base': ingredient('minecraft:netherite_pickaxe'), 'addition': ingredient('lord_core'), 'result': {'item': f'{NS}:dimension_pickaxe'}})
    write(RES / f'data/{NS}/tags/items/repairs_lord_core.json', {'replace': False, 'values': [f'{NS}:lord_core']})
    for old_tag in ('repairs_lord_alloy', 'repairs_mind_shard'):
        (RES / f'data/{NS}/tags/items/{old_tag}.json').unlink(missing_ok=True)
    write(RES / f'data/{NS}/tags/blocks/vein_mineable.json', {'replace': False, 'values': [
        '#minecraft:coal_ores', '#minecraft:iron_ores', '#minecraft:copper_ores', '#minecraft:gold_ores',
        '#minecraft:redstone_ores', '#minecraft:lapis_ores', '#minecraft:diamond_ores', '#minecraft:emerald_ores',
        'minecraft:nether_quartz_ore', 'minecraft:ancient_debris']})
    shapeless('lord_core', ['mind_shard'] * 4 + ['minecraft:crying_obsidian'] * 4)
    # Old alloy stacks keep their ID and can enter the new core progression.
    (RES / f'data/{NS}/recipes/lord_alloy.json').unlink(missing_ok=True)
    shapeless('lord_core_from_alloy', ['lord_alloy'], result='lord_core')
    shaped('lord_upgrade_template', ['ACA', 'CTC', 'ACA'], {'A': 'minecraft:amethyst_shard', 'C': 'minecraft:crying_obsidian', 'T': 'minecraft:netherite_upgrade_smithing_template'})
    shaped('lord_upgrade_template_duplication', ['DTD', 'DCD', 'DDD'], {'D': 'minecraft:diamond', 'T': 'lord_upgrade_template', 'C': 'minecraft:crying_obsidian'}, 2, result='lord_upgrade_template')
    for slot in SLOTS:
        write(RES / f'data/minecraft/tags/items/{slot}s.json', {'replace': False, 'values': [f'{NS}:{s}_{slot}' for s in SETS]})
    write(RES / 'data/minecraft/tags/items/swords.json', {'replace': False, 'values': [f'{NS}:dimension_blade']})
    write(RES / 'data/minecraft/tags/items/pickaxes.json', {'replace': False, 'values': [f'{NS}:dimension_pickaxe']})
    write(RES / 'data/minecraft/tags/items/trimmable_armor.json', {'replace': False, 'values': [f'{NS}:{s}_{slot}' for s in SETS for slot in SLOTS]})
    # 1.21's enchantment definitions use item tags rather than class checks.
    for tag, values in {'head_armor': [f'{s}_helmet' for s in SETS], 'chest_armor': [f'{s}_chestplate' for s in SETS],
                        'leg_armor': [f'{s}_leggings' for s in SETS], 'foot_armor': [f'{s}_boots' for s in SETS],
                        'armor': [f'{s}_{slot}' for s in SETS for slot in SLOTS], 'sword': ['dimension_blade'],
                        'weapon': ['dimension_blade'], 'sharp_weapon': ['dimension_blade'],
                        'mining': ['dimension_pickaxe'], 'mining_loot': ['dimension_pickaxe'],
                        'durability': [f'{s}_{slot}' for s in SETS for slot in SLOTS] + ['dimension_blade', 'dimension_pickaxe']}.items():
        write(RES / f'data/minecraft/tags/items/enchantable/{tag}.json', {'replace': False, 'values': [f'{NS}:{v}' for v in values]})
    zh, en = {}, {}
    labels = {'lord': ('维主', 'Lord')}
    parts = {'helmet': ('头盔', 'Helmet'), 'chestplate': ('胸甲', 'Chestplate'), 'leggings': ('护腿', 'Leggings'), 'boots': ('靴子', 'Boots')}
    for s, (z, e) in labels.items():
        for slot, (pz, pe) in parts.items():
            zh[f'item.{NS}.{s}_{slot}'] = z + pz; en[f'item.{NS}.{s}_{slot}'] = e + ' ' + pe
        zh[f'item.{NS}.{s}_alloy'] = z + '合金'; en[f'item.{NS}.{s}_alloy'] = e + ' Alloy'
    for name, z, e in [('mind_shard', '心境残晶', 'Mind Shard'), ('lord_core', '维主核心', 'Lord Core'),
                       ('lord_upgrade_template', '维主升级锻造模板', 'Lord Upgrade Smithing Template'), ('dimension_blade', '界主之刃', 'Dimension Blade'),
                       ('dimension_pickaxe', '维主之镐', 'Dimension Pickaxe')]:
        zh[f'item.{NS}.{name}'] = z; en[f'item.{NS}.{name}'] = e
    strings = {
        'full_set': ('整套奖励（4 件同系列盔甲）', 'Full-set bonus (4 matching armor pieces)'),
        'set.lord.defense': ('生命上限 +12；额外抗击退 +30%；伤害减免 50%', '+12 maximum health; +30% knockback resistance; 50% damage reduction'),
        'set.lord.offense': ('攻击伤害 +8；攻击速度 +0.4', '+8 attack damage; +0.4 attack speed'),
        'set.lord.mobility': ('移动速度 +20%；摔落伤害降低 60%', '+20% movement speed; 60% less fall damage'),
        'set.lord.flight': ('心境内：双击跳跃开启自由飞行；离开心境或缺少一件盔甲后解除', 'In mind dimensions: double-tap jump to fly; removed outside minds or without all four pieces'),
        'repair': ('铁砧修复材料：%s', 'Anvil repair material: %s'),
        'mind_shard': ('心境击杀敌对生物有 25% 概率掉落 1 个，凋灵或末影龙必掉 4 个；4 残晶与 4 哭泣黑曜石无序合成维主核心后使用', 'Mind hostile kills: 25% for 1 shard; mind bosses drop 4. Craft 4 shards and 4 crying obsidian into a Lord Core'),
        'lord_alloy': ('旧版材料：无序合成可将 1 维主合金转换为 1 维主核心', 'Legacy material: craft 1 Lord Alloy into 1 Lord Core'),
        'lord_core': ('4 心境残晶与 4 哭泣黑曜石无序合成；用于维主盔甲、界主之刃和维主之镐的锻造升级与铁砧修复', 'Craft from 4 Mind Shards and 4 crying obsidian; upgrades and repairs Lord armor, the Dimension Blade and Pickaxe'),
        'lord_upgrade_template': ('首次用下界合金升级模板改造；之后用模板、7 钻石和哭泣黑曜石复制', 'Convert a netherite upgrade template first; duplicate with a template, 7 diamonds and crying obsidian'),
        'dimension_blade': ('按住右键蓄力，松开释放剑气；2 秒满蓄力：范围 6→14 格，伤害 16→64；命中冷却 8 秒、消耗 12 耐久', 'Hold right click to charge, release to slash; full charge in 2s: range 6–14, damage 16–64; hit: 8s cooldown, 12 durability'),
        'mind_repair': ('心境自修复：主手持刃或穿戴盔甲，每秒恢复 1 耐久', 'Mind repair: main-hand blade or worn armor restores 1 durability/s'),
        'dimension_pickaxe': ('瞬间挖掘，无方块间冷却；保留时运、精准采集；用维主核心修复', 'Instant mining with no delay between blocks; Fortune and Silk Touch apply; repair with Lord Cores'),
        'pickaxe.vein': ('潜行+右键切换连锁采矿：%s（仅同种相连矿石，最多 64 块）', 'Sneak + right click: vein mining %s (same connected ore, up to 64 blocks)'),
        'pickaxe.magic': ('手持：吸附 6 格内可见掉落物；心境中每秒修复 1 耐久', 'While held: collect visible drops within 6 blocks; restore 1 durability/s in mind dimensions'),
        'pickaxe.on': ('开启', 'ON'), 'pickaxe.off': ('关闭', 'OFF'),
    }
    for key, (z, e) in strings.items(): zh[f'tooltip.{NS}.{key}'] = z; en[f'tooltip.{NS}.{key}'] = e
    for mode, z, e in [('vein', '维主之镐：连锁采矿已开启', 'Dimension Pickaxe: vein mining enabled'), ('single', '维主之镐：单块挖掘', 'Dimension Pickaxe: single-block mining')]:
        zh[f'message.{NS}.pickaxe.{mode}'] = z; en[f'message.{NS}.pickaxe.{mode}'] = e
    for key, (z, e) in {'applies_to': ('下界合金盔甲、剑和镐', 'Netherite Armor, Swords and Pickaxes'), 'ingredients': ('维主核心', 'Lord Core'),
                        'title': ('维主升级', 'Lord Upgrade'), 'base_slot': ('放入下界合金盔甲、剑或镐', 'Add netherite armor, a sword or a pickaxe'),
                        'addition_slot': ('放入维主核心', 'Add a Lord Core')}.items():
        zh[f'smithing.{NS}.{key}'] = z; en[f'smithing.{NS}.{key}'] = e
    zh[f'message.{NS}.blade.charge'] = '裂界斩蓄力：%s%%（松开右键释放）'
    en[f'message.{NS}.blade.charge'] = 'Rift Slash charge: %s%% (release right click)'
    for lang, data in (('zh_cn', zh), ('en_us', en)):
        write(RES / f'assets/{NS}/lang/{lang}.json', data)
    print('Generated 10 item sprites, 2 armor layers and 10 progression recipes.')
    # Models are generated only after the concept exists; this also prevents
    # regenerating recipes/translations from restoring the old flat gear.
    if (ROOT / 'design/concepts/lord-gear-concept-v1.png').exists():
        from generate_gear_models import main as gear_models
        gear_models()


if __name__ == '__main__': main()
