"""Retrofit the 6 first library tanks (Sherman, Tiger I, IS-3, Abrams, Leclerc, T-90; 10 Oct 2026, old tank contract) to the
destructible contract tank-damage/v1 of batch 2 (11 Oct 2026 ~20:30 CET): same model, its bolt-on items split into Part_ nodes,
Barrel split from Gun, Fx empties, plus the second damage GLB. Each job starts from the previous build script and GLB.
usage: python3 tools/vehicles/make_jobs_tanks_retrofit.py   (order -> /tmp/tanks-retro-20261011/order.txt)"""
import json, os, re, shutil
from make_jobs_tanks2 import GAME, NOMARK, PIVOTS, SCRATCH, TURRET, DAMAGE, rig, paint, ROOT

SCR = '/tmp/tanks-retro-20261011'
TIME = ('Pace: re-export the healthy GLB with the new rig within about 30 minutes (it is a split of the existing model, not a new '
        'model), the damage file by about 60 minutes, then use what is left of about 75 minutes to improve what the renders show '
        'is weakest. Use Cycles with the GPU (OptiX/CUDA) and modest samples for bakes and renders. ')

# slug, latest version, era, country, the bolt-on items this type really carries (Part_ hints)
J = [
 ('sherman-tank', 1, 'era-ww2', 'usa', 'sandbags on the glacis and hull sides (several Part_Sandbags_ groups), spare track links on the glacis, '
  'applique armour plates on the hull sides, pioneer tools (shovel, axe, pick, crowbar), fenders and front mudguards, rear stowage '
  'box, jerrycans, exhaust deflector, headlight guards, tow cable, antenna; turret: rear stowage bin, appliqué cheek plate, roof MG mount'),
 ('tiger-heavy-tank', 1, 'era-ww2', 'germany', 'front mudguards and side fender sections, the two Feifel air filters and their pipes on the rear, '
  'tool sets (shovels, axe, jack, tow cables) on the hull sides and glacis, rear stowage box, headlights with guards, exhaust guards, '
  'track cleaning tool tube; turret: spare track links on the turret sides, the rear stowage bin (Rommel box), smoke grenade launchers, '
  'the commander cupola ring'),
 ('is3-heavy-tank', 1, 'era-ww2', 'ussr', 'the four external rear fuel tanks, fender stowage boxes, side fender sections, spare track links, '
  'tow cables, unditching log, headlight with guard, exhaust guards; turret: the DShK roof machine gun mount, grab rails, the '
  'commander cupola ring, sight housings'),
 ('abrams-tank', 1, 'era-modern', 'usa', 'the heavy ballistic side skirt plates (one node per plate, at least four per side), rear fender '
  'sections, rear grille doors, tow cables, tail light boxes, headlight guards; turret: bustle rack basket with its stowage, side '
  'stowage bins, smoke grenade launchers, the commander weapon station, gunner and commander sight heads, wind sensor, antennas'),
 ('leclerc-tank', 1, 'era-modern', 'france', 'side skirt plates (one per plate, at least four per side), front mudguards, the two external '
  'rear fuel drums, rear stowage boxes, tow cables, headlight guards, exhaust grille; turret: the GALIX launcher blocks, bustle '
  'stowage, side bins, sight heads, roof MG mount, antennas'),
 ('t90-tank', 2, 'era-modern', 'russia', 'the Kontakt reactive armour blocks on the glacis and turret (grouped: one Part_ per row or panel '
  'of blocks), rubber side skirts with ERA panels (one per panel), the rear fuel drums, the recovery log, snorkel tube, stowage boxes, '
  'tow cables; turret: the Shtora dazzler boxes, smoke grenade launchers, roof machine gun station, sight heads, antennas'),
]


def main():
    order = []
    for slug, ver, era, country, items in J:
        src, nv = f'{ROOT}/jobs/{slug}-v{ver}', ver + 1
        dst = f'{ROOT}/jobs/{slug}-v{nv}'
        os.makedirs(dst, exist_ok=True)
        old = json.load(open(f'{src}/job.json'))
        default = old['nodes'].split('default factor = ')[1].split(').')[0] + ')'
        for f, g in (('sheet.jpg', 'sheet.jpg'), (f'{slug}-raw.glb', 'previous.glb'), ('final.png', 'previous_final.png'),
                     ('side.png', 'previous_side.png'), (f'build_{slug}.py', f'build_{slug}.py'), ('paints.png', 'previous_paints.png'),
                     ('nodes.json', 'previous_nodes.json'), ('NOTES.md', 'previous_NOTES.md')):
            if os.path.exists(f'{src}/{f}'):
                shutil.copyfile(f'{src}/{f}', f'{dst}/{g}')
        fb = (f'RETROFIT, not a new model. This tank is already in the library (previous.glb, previous_final.png, previous_side.png, '
              f'build_{slug}.py, previous_nodes.json; its baked textures are on gex44 in /root/fal-author/{slug}-v{ver}/textures: copy what '
              f'you reuse into your own remote dir, never write in the old one). Games now need it DESTRUCTIBLE like the newer library '
              f'tanks. Keep the model exactly: same shape, proportions, frame, origin, materials, texture look, node names, pivots, Paint '
              f'material and factor, paints in nodes.json. Start from build_{slug}.py and change only this: (1) every bolt-on item becomes '
              f'its own Part_ node with a complete surface underneath (for this type: {items}); (2) the barrel is split from Gun into a '
              f'child Barrel, the empty Muzzle becomes a child of Barrel at the tip with identity rotation (+Z forward); (3) add the Fx_ '
              f'empties and the hatches the rig asks for; (4) build FILE B, the damage GLB, from copies of your meshes, with its Burnt '
              f'and Scars textures; (5) render states.png and look at it. Everything else in the contract below holds.')
        nodes = GAME + rig(TURRET) + paint(default) + DAMAGE.replace('__SLUG__', slug).replace('__TW__', 'Turret') + NOMARK + PIVOTS + SCRATCH + TIME
        cards = f"{ROOT}/cards/{old['id'].replace('.', '/')}"   # the card version: the next free one (repacks took some)
        cv = max([nv] + [int(f[1:-5]) + 1 for f in os.listdir(cards) if re.fullmatch(r'v\d+\.json', f)]) if os.path.isdir(cards) else nv
        j = dict(old, version=cv, refs=[r for r in ('sheet.jpg', 'previous_final.png', 'previous_side.png') if os.path.exists(f'{dst}/{r}')],
                 tris='100k to 160k', mats=10, effort='medium', nodes=nodes, feedback=fb, family='tanks', damage='tank-damage/v1',
                 tags=[era, country], layout='turret')
        json.dump(j, open(f'{dst}/job.json', 'w'), indent=1)
        order.append(f'{slug}-v{nv}')
    os.makedirs(SCR, exist_ok=True)
    open(f'{SCR}/order.txt', 'w').write('\n'.join(order) + '\n')
    print(len(order), 'jobs:', ' '.join(order))


if __name__ == '__main__':
    main()
