# =============================================================================
# ALLT I PROGRAMMET SKA ALLTID VARA PÅ ENGELSKA - ALDRIG SVENSKA!
# =============================================================================
#
# EQ_CheatSheet.py
# An interactive EQ reference guide for rock music production.
#
# ToDo / Structure:
#   v3.41 (2026-11-21): TUBA FOLDER FOUND. Lars's SWAM folder is 'SWAM Tuba Eb' (key 'tuba eb'), but SWAM_PRODUCT only looked for
#         'tuba', so Generate > SWAM room presets said there was no folder for the Tuba. SWAM_PRODUCT 'tuba' now tries 'tuba eb',
#         'eb tuba', 'tuba'. (The .swam side already knew 'tubaeb'.) Backup EQ_CheatSheet.py.2026-11-21_before-tuba-eb.bak
#   v3.40 (2026-11-20): ALSO 'Trombone Tenor-Bass' (tenor_bass_trombone) and 'Trombone Double Bass' (double_bass_trombone), the other two
#         SWAM trombones Lars owns (folders 'SWAM Tenor Bass Trombone' / 'SWAM Double Bass Trombone'); same tables as below.
#   v3.40 (2026-11-20): TROMBONE TENOR added (SWAM Tenor Trombone, id tenor_trombone, Brass tab). Lars: 'Trombone tenor is missing as a
#         choice and as SWAM generation'. New card + every per-instrument table (smart:EQ, depth, low cut, compression, Trackspacer,
#         multi-part advice, stage row, pan, M/S, bus, Corridor, Omega, Cascadia, Bandwidth preset 'Tenor Trombone . Presence'),
#         and SWAM_PRODUCT 'tenor trombone' so Generate > SWAM room presets finds his folder 'SWAM Tenor Trombone'.
#         The generic 'Trombone' card is unchanged (no SWAM folder). Backup EQ_CheatSheet.py.2026-11-20_before-tenor-trombone.bak
#   v3.39 (2026-11-16): LADDERS NEVER PUT TWO RUNGS ON ONE SPOT. 8 toms next to a hi-hat printed 'L15 . Centre . Centre . R10'
#         (the rungs were squeezed inside the hi-hat and +-5 was printed as Centre). Now vstage_snap_ladder() rounds a
#         ladder to unique 5-steps, and in a ladder 5 is a real position: 'L55 . L45 . L35 . L25 . L15 . L5 . R5 . R15'.
#         Used by the printed ladder label AND the Virtual Stage presets (a file says what the line says). Single
#         placements are unchanged (+-5 is still Centre there). Backup EQ_CheatSheet.py.2026-11-16_before-ladder-unique.bak
#   v3.38 (2026-11-14): TWO HI-HAT CHANNELS (closed + open) are no longer one point. Same position (still ONE hi-hat,
#         e.g. R25) but each copy HIHAT_COPY_STEP (4) Distance points deeper: #1 closed at the base Distance, #2 open
#         4 deeper. drum_stage_plan gives the row 'pos_pcts' (all equal) + 'dists'; the Virtual Stage presets /
#         Stage map already read per-copy numbers. One hi-hat channel is placed exactly as before.
#         Backup EQ_CheatSheet.py.2026-11-14_before-hihat-copies.bak
#   v3.37 (2026-11-14): (a) VIOLA IS THE VIOLIN'S PARTNER: Viola is now MID in smart:EQ (was BACK) and MID in reverb
#         depth (was FAR), the same as Violin, so a viola no longer ends up behind the violin (the stage distance of a SWAM
#         part comes from the depth tier, and who yields comes from the smart:EQ tier - both were lower for the viola).
#         The 'Viola (front)' card is kept (old songs use it) but is no longer needed for that. (b) Cascadia
#         'Strings - Flowing and Floating' keeps its name but is much drier: Amount 30->18, Feedback 55->20, ping-pong
#         off, Mod depth 20->10, low pass 8000->6000, Unmask 15->35 (the echo ducks while the instrument plays).
#         Backup EQ_CheatSheet.py.2026-11-14_before-viola-mid-cascadia.bak
#         (c) the Cascadia report's 'Kept' line is now a warning: when you answer 'Keep existing' an
#         existing file with other numbers is NOT replaced, so the plug-in kept loading the old (wet) sound.
#         (d) NO MORE 'overwrite existing presets' TICK BOXES in Options (you could not see their state). Every preset
#         generator (Lowtility, SubMass, Corridor, Omega, Bandwidth, Cascadia, Virtual Stage, Knock, PatchWork,
#         smart:reverb) now asks with a popup the FIRST time a file with the name to be written already exists:
#         'Overwrite with new' (old file kept as .bak) or 'Keep existing' (Esc). One question per run; nothing is
#         asked when nothing exists (_OverwriteAsk + EQApp._ask_overwrite_popup, DEL 04z). Kirchhoff never asks: an
#         identical EQ (same signature) is simply reused. Backup EQ_CheatSheet.py.2026-11-14_before-overwrite-popup.bak
#   v3.36 (2026-11-10): (a) PAIRS HAVE PRIORITY IN THE SWAM ROOM. The spacing step (_swam_space) now places the
#         Pair groups (and siblings) BEFORE every other SWAM part and moves the members of a pair TOGETHER (same
#         number of 0.7 m steps; if that is not enough the angles are opened up a little), so a cello or a
#         flugelhorn with no pair is the one that gives way - before, the stage order decided and they pushed a
#         pair away. The 'moved' lines say so ('a pair member - pairs keep their spot'). Groups = EQApp._swam_hold_groups,
#         passed to swam_apply(hold=...). (b) '📋 Copy info' button next to Kill MediaBay: line-up, counts, pairs,
#         hand placements, both rooms, every SWAM spot + the moved-lines, and the stage map's numbers/reasons,
#         as text on the clipboard (EQApp._info_text). (c) SWAM room shown as Room Sizes + Absorption Materials
#         ('Room Type never changes'): header label (2 lines), the sheets and the report. Backup
#         EQ_CheatSheet.py.2026-11-10_before-room-label-mediabay-kill.bak is from before v3.35 (no newer one).
#   v3.35 (2026-11-10): HEADER OF 'Selected Instruments' (a thin strip under the title line - the title
#         line itself is only ~475 px wide at the normal window size and was already full): (a) the song's ROOM SIZE
#         ('🏠 Medium', hand mark when forced; plus 'SWAM: LARGE 2' when the song has SWAM parts) - from
#         vstage_room(), the same value as on every Virtual Stage instance, so it no longer has to be hunted for
#         in the cards (EQApp._sync_room_info, refreshed with the panel). (b) Button '☠ Kill MediaBay': ends
#         Steinberg's background process (SteinbergMediaBayServer.exe, found by name, ended by PID with the full
#         path of taskkill) so Cubase rebuilds its preset list at the next start - new SWAM/Virtual Stage presets
#         show up. Asks first if Cubase is still running. Backup EQ_CheatSheet.py.2026-11-10_before-room-label-mediabay-kill.bak
#   v3.34 (2026-11-09): SWAM: (a) EXPRESSION + VIBRATO written into every generated preset (File > SWAM: Expression and
#         Vibrato in the presets...; settings swam_expression default 1.0 = all the way up, swam_vibrato default empty =
#         keep the seed's; an ABSOLUTE number, not a percentage, because a generated file can be the next seed and a
#         percentage would shrink every run). (b) COPIES THAT TAKE TURNS: File > SWAM: copies that take turns (this song)
#         - a part with 2+ copies where one takes over from the other is ONE player: all copies get copy 1's Angle/Distance
#         (SWAM_TURNS, settings swam_turns per song); copies that play together keep their own spots, spaced apart.
#   v3.33 (2026-11-09): SWAM PRESETS THAT CUBASE DID NOT SHOW. Cause found: Cubase lists .vstpreset files from its
#         MediaBay database, built when Cubase STARTS (checked in mediabay3.db: the new 'Fyrvaktarens son' files were
#         on disk, not in the database). Generate > SWAM room presets now (a) tells him so in the report - restart
#         Cubase or MediaBay > right-click VST3 Presets > Rescan Disk, and says if Cubase is running - and (b) ALSO
#         writes every preset as a '.swam' into SWAM's own User folder (%APPDATA%\Audio Modeling\AMData\...\Presets\
#         User), which SWAM's own browser reads (setting swam_native, default on). Same XML as the .vstpreset (only
#         syncLock, program name and date differ). NOT verified in the real SWAM browser. The preset already holds
#         the MIDI mapping (the LEARN), vibrato, expression, volume and room position of the seed.
#   v3.32 (2026-11-09): NAME ROW TAGS. On the name row of every block in Selected Instruments (📋 Instruments view)
#         a short tag line is printed after the name / count / ✎: smart:EQ tier - reverb depth - duck source,
#         e.g. 'MID - NEAR - Duck vocal' (EQ first = first plug-in in the chain). Duck only where the instrument has one
#         and its source (Kick / Lead Vocal) is in the song. Same tables as the footnotes (SMARTEQ_GROUP, DEPTH,
#         DUCKING; the Pair layer counts), see EQApp._header_tags. Backup EQ_CheatSheet.py.2026-11-09_before-name-row-tags.bak
#   v3.31 (2026-11-08): KNOCK PRESETS (KNOCK 1 and KNOCK 2). Generate > Knock presets: Selected / All writes the
#         Plugins That Knock punch processor's presets per instrument (kick, snare, toms, hats, cymbals, basses,
#         guitars, organ, low strings, brass, vocals, piano, synth) - plus Drum_Bus and Mix_Bus with 'All'. Which
#         version is written is a SETTING: Generate > Options > Knock version (KNOCK 1 = default, as before;
#         KNOCK 2). Folders: File > Set KNOCK 1 / KNOCK 2 preset folders (auto: Documents\VST3 Presets\Plugins That
#         Knock\KNOCK and ...\Knock Audio\KNOCK 2). The 24 KNOCK 1 presets he already had are rebuilt BYTE FOR BYTE
#         (nothing of KNOCK 1 is lost); the KNOCK 2 twins were designed by rendering test signals through both
#         plug-ins until the band levels and crest factor matched (a sound-alike start, not a copy). New opt-in
#         filter box '\U0001f94a Knock' shows the footnote (numbers + why) in the Instruments view. Names:
#         '<Label>---Knock1_<Name>.vstpreset' / '---Knock2_'. KNOCK 2's file format was decoded 2026-11-08 (see
#         DEL 02e3 and Knock2_format.py). Backup EQ_CheatSheet.py.2026-11-08_before-knock.bak
#         ALSO v3.31: KNOCK 2 ALSO AS NATIVE .k2p. Cubase lists the .vstpreset files, but KNOCK 2's OWN browser
#         (User tab) only reads .k2p files from C:\ProgramData\Knock Audio\KNOCK 2\Presets\User, so with version 2
#         every preset is now ALSO written there as '<name>.k2p' (raw state, same values; folder = File > Set KNOCK
#         preset folders, 3rd question). Not verified in the real plug-in's browser.
#         ALSO v3.31: FOLDED LEFT SIDE NO LONGER COMES BACK SQUEEZED. Cause: when the program STARTED with the left
#         side folded, the divider was read before anything was drawn (answer: the minimum, 200) and that overwrote
#         the saved width, so every unfold was narrow until he dragged it out. Now the divider is only remembered
#         when the window has really been laid out (_remember_sash), the restore waits for the window instead of
#         clamping against width 1, the saved wish is no longer overwritten by the clamped value, and a one-time
#         repair (sash_fix_331) widens a divider that was already saved too narrow (to at least 820, once).
#   v3.30 (2026-11-08): BACKING VOCALS IN THREE ROLES. Under the normal Virtual Stage numbers of Backing
#         Vocals (card footnote and the Stage window's 'What to dial in') come three ALTERNATIVE lines:
#         Doubles (L100 . R100, close behind the lead, ~20 dB under it), Harmonies (L10 . R10, just off
#         centre) and Own parts (wide, L70 . R70). Distance follows the lead's. Idea from
#         musicguymixing.com/panning-backing-vocals. The Pan view text and the card tip say the same in
#         one line. Not written into the Virtual Stage presets (see the ToDo at VSTAGE_BACKING_ALTS).
#         Backup EQ_CheatSheet.py.2026-11-08_before-backing-alts.bak
#   v3.29 (2026-11-07): (a) SWAM SECTION plug-ins. A 'Sect' box left of SWAM in Song Variants: tick it on a
#         violin / viola / cello / double bass that you run in the SWAM SECTION plug-in. The section plug-in
#         is a DIFFERENT plug-in with its own preset folder (SWAM Cello Section ...) and its own file format
#         (a solo preset does not load there), so the presets are built from a preset you saved IN the section
#         plug-in and written into its folder. No such folder / seed yet = the report says exactly which
#         folder and what to save. (b) The compact rows in Selected Instruments show the SWAM numbers
#         (they said only 'OFF - SWAM'). (c) ROOM SIZE: the step-down 'no overheads' now only applies to a
#         kit with NO cymbal channel at all (cymbals, hihat or ride): hihat / ride carry the air, so adding
#         a cymbals channel no longer flips Small <-> Medium. (d) '◀ Fold left side' button at the far left
#         of the Selected Instruments header: folded = Selected Instruments alone at the far left, unfolded =
#         the tabs come back and it moves right (setting left_folded). (e) Instrument names: the main thing
#         first (Saxophone Alto, Trumpet Piccolo, Flute Bass ...). (f) Sect box not on Double Bass; seeds
#         named '1000---...' are preferred; the divider starts wider (once). Backup EQ_CheatSheet.py.2026-11-07_before-swam-sections.bak
#   v3.28 (2026-11-05): NOTHING FLICKERS BEFORE UPDATE / SAVE. A SWAM tick is a waiting change like
#         a tick, a count or a Pair (mark 🎻, _applied_swam, _swam_for_engines), a count typed in the
#         Selected Instruments panel waits too (it used to go in at once), and Selected Instruments
#         has its own ⟳ Update after 💾 Save. Ticking SWAM switches the instrument ON (like a count
#         raised from 1). A 'SWAM' button between Delete and Save As in Song Variants runs Generate >
#         SWAM room presets (it takes in anything waiting first). Hand placements in the Stage window
#         still go in at once (a dialog, not a tick).
#   v3.27 (2026-11-05): SWAM ROOM PRESETS. His test (Viola, 73 deg / 4.9 m) worked, so Generate >
#         '\U0001f3bb SWAM room presets: this song' writes one preset per SWAM-ticked instrument, named
#         '<song>---<instrument>---SWAM', into that instrument's own folder under Audio Modeling
#         (File > Set SWAM preset folder...), built from a preset he saved himself there (a file with
#         'Claude' in the name first, else the newest): only roomSourceAngle / roomSourceDistance change.
#         No two SWAM sources share a spot (_swam_space: moved back, else turned). Re-run after any
#         change of line-up: same names, old files kept as .bak. Other changes in v3.27: (a) The Pair / Prio / SWAM column names are pinned above the list (they no
#         longer scroll away). (b) 'Keys & Winds' is split into tabs Winds | Keys (organ, piano,
#         accordion) | Other (synths, harmonica); order Brass, Winds, Keys, Other, Strings; same order in
#         Selected Instruments. (c) 'Synth Mallet / Bell (xylophone)' is now 'Synth Mallet';
#         'Organ (melody / harmony)' is 'Organ (melody)'. (d) NEW CARD 'Viola (front)' (id viola_front):
#         the viola in the melody role, placed like a solo violin, bed/lead pair with Viola; no Pair or
#         Prio needed. (e) The SWAM box only exists for Brass, Winds and Strings. (f) A 💾 Save button
#         right after '🏠 Room'.
#   v3.26: SWAM ROOM (2026-11-05, DEL 04d). A SWAM box at the far right of each row in Song
#         Variants (left of Pair). Tick it for an instrument you run as SWAM: Virtual Stage is then
#         OFF on that channel (SWAM's own Ambiente room places it; two rooms on one channel = two
#         pans and two echoes) and the sheet prints the Angle (degrees) and Distance (metres) to type
#         into the SWAM room, worked out from the SAME stage plan (so pairs, siblings, hand placements
#         and the line-up all still count). The SWAM part sits under a row of ************ in the
#         instrument's block, in the Stage map and in the Stage list. Everything else (Bandwidth,
#         Cascadia, smart:EQ, Lowtility, Kirchhoff, Omega) is shown as before. Room advice: the room is
#         shared by every SWAM instance, so it is picked ONCE: LARGE 2 / Set 2: MEDIUM (his Studio A)
#         for 3+ SWAM parts or a section, a SMALL type for one or two. Format read from his own
#         Viola preset: roomSourceAngle / roomSourceDistance per instrument, room settings per room.
#         Angle 90 = straight ahead, above 90 = left (from his Room0 screenshot: Viola left of centre
#         = 131 deg / 2.70 m). Saved per variant ('swam'), Ground, Save as, Duplicate. Goes in AT ONCE
#         (no Update wait), like the hand placements. Not tried with the real SWAM plug-in.
#         SWAM PRESET WRITER (functions only, no menu yet): make_swam_preset(seed, angle, metres) changes
#         just roomSourceAngle / roomSourceDistance in a preset he saved himself; all length fields move
#         with it; the seed's own numbers give the seed back byte for byte. One test file written to
#         0---Claude_work_dir\\SWAM_test\\SWAM Viola 3 for him to load in SWAM Viola 3.
#   v3.25: PAIR + PRIO (2026-11-05, DEL 04c). Two number boxes at the far right of each row in
#         Song Variants. Parts with the same PAIR number (1-9) are ONE level: they share the
#         smart:EQ priority and the reverb depth of the OWNER (highest PRIO 1-9, ties = the
#         front-most), a dry part keeps its dry reverb, and on the Virtual Stage two equal
#         members become Siblings while unequal ones become Feature (owner) / Support. Hand
#         placements in the Stage window still win. Built as a LAYER on top of SMARTEQ_GROUP and
#         DEPTH (_PairedDict.layer, filled by EQApp._pair_sync), so the tables and every .get()
#         in the program are untouched. Saved per variant ("pairs"), Ground, Save as, Duplicate;
#         waits for ⟳ Update like a tick or a count. Not tried on a real song yet; tested with a
#         scripted line-up (violin + viola, chord guitar + organ).
#         ALSO v3.25 (same day): (a) Song Variants buttons in his order: New, Rename, Duplicate,
#         Delete, Save As..., Save, then ⟳ Update (moved up from the second row; Reset and Ground
#         stay below). ⟳ Update no longer writes the variant file (_commit_left(persist=False));
#         Save does. (b) A changed Pair/Prio waits for Update like a tick or a count (pending
#         mark '&'). (c) The Selected Instruments panel, after every redraw (_summary_settle):
#         fits its scroll area to the content, never leaves the view past the end (the big empty
#         space after switching view/filter), and scrolls to the instrument touched last
#         (_mark_focus: card tick/count, picker tick, panel count, Pair/Prio, Stage by hand).
#         NOTE: hand placements in the Stage window and the Room size still go in at once.
#   v3.24: LIST ORDER, BRASS TAB, STAGE WINDOW FIXES (2026-11-05).
#         - Order (see 'LIST ORDER' after EQ_DATA): Vocals, Drums, Bass, Guitar as before, then
#           Brass | Keys & Winds | Strings A to Z, and A to Z inside each. Roles now stand AFTER the
#           instrument: 'Organ (lead)', 'Organ (background)', 'Organ (melody)',
#           'Accordion (lead)', 'Piano (background)', 'Flute (background)', 'Brass (lead)',
#           'Violin (background)', 'Strings (lead)'. Ids are unchanged, so saved songs, presets and
#           file names are untouched. Drums: Toms, Percussion, Cymbals (Hand Drums last).
#         - NEW TAB 'Brass': brass, brass_lead, trumpet, trombone, horn_section, flugelhorn,
#           french_horn, tuba, euphonium, piccolo_trumpet, alto_trombone, bass_trombone, tenor_trombone, tenor_bass_trombone, double_bass_trombone. It stays
#           on the 'Keys/Winds' smart:EQ bus family (_SMARTEQ_SHORT_FAM), so no bus plan changes.
#         - Selected Instruments panel: same order, Vocals LAST (pick order only; 'Per position'
#           is sorted by reverb bus and is left alone).
#         - Virtual Stage by hand: the whole page scrolls with the wheel (it used to scroll only
#           over the table, not over the Room size row or the text above it) and the window has a
#           '🎪 Stage map…' button back to the map (it was a dead end).
#   v3.23: HI-HAT AND RIDE TAKE TURNS (2026-11-04, drum_stage_plan). Lars: hi-hat and ride are
#         almost never played at the same time - hi-hat through the song, ride in the loud
#         ending. The Virtual Stage planner had treated two ticked metals as two timekeepers at
#         once and pushed both out wide (hi-hat R20 -> R25 with a ride, R25 -> R40 with no toms;
#         the tom sweep followed). Now each is placed as if it were the only timekeeper, so
#         ticking the ride moves nothing: hi-hat R20 / ride L20 (R25 / L25 with no toms). The
#         opposite-sides placement stays (that is where they stand in a real kit) but the text no
#         longer claims it is a masking fix. Presets written for a hat+ride kit get new names.
#         The EQ cards / compressor / reverb tables never assumed the two together (the Ride
#         card already says 'instead of the hi-hat'), so they were left alone.
#   v3.22: VIRTUAL STAGE NAMES BY FAMILY (2026-11-01, DEL 02t). The instrument part of a
#         Virtual Stage preset name now starts with the family, so the files group in the
#         Cubase list: 'Guitar_chord' (was 'Chord_Guitar'), 'Guitar_rhythm', 'Organ_lead' ...
#         = the Kirchhoff labels. The drums follow his FX chain names - Drum_1_Kick, Drum_2_Snare,
#         Drum_3_Hihat, Drum_4_Ride, Drum_5_Tom, Drum_6_Percussion, Drum_7_Cymbal, Drum_Hand - and
#         the basses Bass_ground, Bass_X, Bass_double, Bass_double_section. Presets written under
#         the old names are NOT removed (delete them by hand); nothing else changed.
#   v3.21: VIRTUAL STAGE PRESETS: ALL (2026-10-31, DEL 02t). Generate > Virtual Stage presets: All
#         writes a whole library in all three rooms: every instrument on its own; rhythm + chord
#         guitar together (1+1, plus 2+1 / 1+2 / 2+2 for the exceptions); the drum kit in seven
#         shapes (with / without toms, ride, overheads); and Toms and Cymbals for every count
#         1-9 (each count has its own L / C / R spread), toms with and without overheads. Same
#         names-hold-the-numbers rule as Selected, so duplicates are written once. Distance in the
#         library comes from these reference line-ups (a real song can nudge it a few points).
#   v3.20: VIRTUAL STAGE PRESETS (2026-10-31, DEL 02t). Generate > Virtual Stage presets: Selected
#         writes one Cubase .vstpreset per row of the CURRENT stage plan (every ticked channel the
#         plug-in is meant for; a x N part gets one per copy) into Documents\VST3 Presets\EVA
#         Instruments\Virtual Stage. The name holds the numbers - '3---Cello---D46---L10' =
#         Large room, Distance 46, 10 % left - so the same numbers are the same file and a
#         different song never overwrites another. Lock Position is ALWAYS on. The file format
#         was read off his own '3---Cello' plus four test presets (knbVol = Distance x 2, knbPan
#         = Position + 100, three room buttons); all five rebuild byte for byte. The container is
#         embedded, so no seed file is needed. File > Set Virtual Stage preset folder..., Options:
#         overwrite. The old 'there are no presets' texts in DEL 02m and the help were rewritten.
#   v3.19: PRESETS WITHOUT A DATE IN THE NAME, AND A BACKUP OF WHAT GETS REPLACED
#         (2026-10-31, DEL 02s). The generators used to start every name with the month
#         ('2026-06---Cello---Lowcut'); the month moved, so every FX chain that pointed at the
#         old name went MISSING (342 slots in one FxChainChecker scan). Names are now just
#         what the preset IS: '<Label>---Solo' / '---Group---<tags>' (Kirchhoff .keq and its
#         Cubase .vstpreset), '<Label>---Lowcut', '<Label>---Chain', '<Label>---SubMass_Amp..',
#         'Corridor---<name>', 'Omega---<name>'. A file that already exists with different
#         contents is first renamed to '<file>.<YYYY-MM-DD_HHMMSS>.bak' beside it (write_preset_file;
#         a plug-in never lists a .bak) and the result window lists what was replaced - this
#         also covers Bandwidth, Cascadia and smart:reverb, and the Helpfiles copies. Identical
#         files are left alone. Kirchhoff: a changed EQ takes over the same name (no more
#         '__02'); an old '0---' / dated registry entry is moved to the plain name when it is
#         regenerated (the old file is left). Template/seed pickers now recognise our own
#         files by name pattern (is_generated_name) instead of by the date prefix.
#         NOTE: with plain names an existing file is 'kept' until Overwrite is ticked - tick it
#         to push a changed preset into the plug-in folder.
#         Kirchhoff 'Reused' fix (same day): a registry hit used to count as 'Reused' even when
#         the file was NOT in the Kirchhoff folder, and an old dated registry name was reused as
#         it was ('2026-09---Lead_vocal_(lowtility)---Solo') unless Overwrite was ticked. Now a hit
#         is only reused when its name has no date/0--- prefix AND the file exists in Helpfiles and
#         the Kirchhoff folder; otherwise the plain-name file is written (reported as RENAMED or
#         RESTORED). The old dated files are left on disk.
#   v3.18: THE REST OF THE SWAM SOLO LINE-UP (2026-10-25): Piccolo, Alto Flute, Bass
#         Flute, Soprano / Alto / Tenor / Baritone Saxophone, Piccolo Trumpet, Alto Trombone
#         and Bass Trombone (Keys & Winds). Same coverage as v3.16-3.17, ten new Bandwidth
#         presets. The generic Trumpet, Trombone, Saxophone and Flute cards stay.
#   v3.17: FIVE MORE SWAM INSTRUMENTS (2026-10-25): English Horn, Euphonium, Bass
#         Clarinet, Contrabass Clarinet (Keys & Winds) and Double Bass Section (Strings;
#         one bass desk = one bass-role channel: lows mono, same bus and rules as the
#         solo Double Bass, but several players so more mid width and a harder mud cut).
#         Five new Bandwidth presets; Corridor/Omega/Cascadia reuse the nearest preset.
#   v3.16: SEVEN NEW INSTRUMENTS FOR SWAM (2026-10-25): Clarinet, Oboe, Bassoon,
#         Contrabassoon, Flugelhorn, French Horn and Tuba (ids clarinet, oboe, bassoon,
#         contrabassoon, flugelhorn, french_horn, tuba, all in 'Keys & Winds'). Each has
#         its own EQ card, smart:EQ tier, reverb tier, low cut, compressor, stage spot
#         (the horns join the 'horn line', the reeds the wind row), pan, M/S advice, bus
#         and Kirchhoff label, plus Bandwidth, Corridor, Omega and Cascadia presets (7 new
#         Bandwidth presets; the others reuse the nearest existing preset). Double Bass
#         was already a card (SWAM 'Double Bass' = the orchestral contrabass).
#   v3.15: SONG LIST IN ALPHABETICAL ORDER, AND THE CURRENT SONG IS UNMISSABLE
#         (2026-10-22). The song variants list is always shown A-Z (case-blind,
#         numbers in number order: 'Song 2' before 'Song 10'); the stored order in
#         song_variants.json is untouched. The song you are working on is lit in the
#         list (accent bar + a ▶ in front) and its name is also shown in the title bar
#         ('♪ Now: ...') on EVERY tab - fixed width, so a long name never moves the
#         buttons. APP_VERSION was stuck at 3.8; it is 3.15 now.
#   v3.14: LEAD VOCAL ON ITS OWN (2026-10-21). With backing vocals the lead stays dry and
#         the backing makes the depth; a lead with no other vocal layer has nothing to
#         contrast with and gets a little more room: smart:reverb Dist +6 / Size +8, the
#         Corridor 'Pop Plate (alone)' and the Cascadia 'Eighth-Note Echo (alone)'
#         presets, and one line under its reverb that says why. Everything else on the
#         lead is the same either way. 'Company' = backing vocals, extra vocals or a
#         choir pad (LEAD_COMPANY). Only the right-hand panel (and Generate: Selected)
#         look at the line-up; the left-hand cards stay in reference mode.
#   v3.13: COLOUR WHERE YOU LOOK, AND A DETAILS BOX (2026-10-21). smart:EQ no longer
#         paints the whole line green - only the tier (FRONT / MID / BACK); smart:reverb
#         colours its tier word; Virtual Stage colours Position, Distance and Room;
#         the Trackspacer line colours WHAT it ducks under (Lead Vocal, Kick ...).
#         _head_line takes `accents` (regex -> colour). Corridor and Omega moved into
#         the Set & forget box (two checkboxes fewer). New 'Details' box before
#         SubMass, off by default: it shows or hides the lines of values a preset
#         sets for you - Bandwidth crossovers, Cascadia low cut / Unmask, Omega and
#         Corridor detail lines, and the two Trackspacer rows under the header
#         ('Side-chain = ...' and 'Band 500 Hz-5 kHz · Amount ...').
#   v3.12: NEW INSTRUMENT 'Organ Melody / Harmony' (id organ_melody, 2026-10-21). The
#         organ had two cards - Background (a bed that yields) and Lead (the tune that
#         goes forward) - and an organ that plays a counter-line or harmony fitted
#         neither. The new card sits halfway: EQ between the two (+1 body, -3 mud, +3
#         note core, +2 shimmer), smart:EQ tier MID, a light-medium send, a compressor
#         in between, a bed/lead pair with the Background Organ (so the two still
#         get their high-pass / presence hand-off), a stage position between the
#         two organs, plus a Bandwidth and a Cascadia preset. Importance in the MIX
#         (equal to the vocal? one of several?) is still the Stage Role.
#   v3.11: ≈ CASCADIA PRESETS (2026-10-20). iZotope Cascadia (delay) presets can be
#         recreated: the 15 the user made on 2026-07-26 (value for value, under
#         English file names that match what the program shows) plus 14 new ones for the channels they did
#         not cover. A .vstpreset is a zlib-compressed JSON state (decoded from the
#         user's own 'radera-cascadia'); rebuilding that file from its own values
#         gives the SAME BYTES, so the writer is exact. Needs one Cascadia preset
#         in the folder as the container. Kicks, basses, cymbals and a single-note
#         low guitar get AIR-ONLY versions (low cut 600-900 Hz). Only Tempo Sync index 7 (= 1/8) is
#         confirmed; presets that carry another index say so. Surfaces: a ≈
#         footnote after the Corridor line, 'Cascadia' in the filter row, a ≈
#         effect-sorted list, Generate ▸ ≈ Cascadia presets: Selected/All,
#         File ▸ Set Cascadia preset folder…, an overwrite option, Explain ▸
#         Cascadia. Default folder: Documents\VST3 Presets\iZotope\Cascadia.
#   v3.10: ↔ BANDWIDTH PRESETS (2026-10-20). In The Mix "Bandwidth" (stereo width)
#         had no presets here, and the user's hand-made ones (organ / drums /
#         brass / strings) had been lost with a drive. DEL 02q now holds 47
#         presets: the 13 hand-made ones value for value (byte-identical to the
#         original files, checked) plus presets for every instrument in the
#         chart - vocals (lead / backing / extra / choir), cymbals, percussion,
#         basses, guitars, keys, winds, synths, strings, a mono-source and a
#         mix-bus setting. An .itmpreset is plain XML, so no seed file is
#         needed. Rules from the manual: Low band 0 on bass/kick, Strength < 6 on
#         low sources, leads barely widened. Surfaces: a ↔ footnote on every
#         card and block (after the Virtual Stage, before the reverb), 'Bandwidth'
#         in the filter row, a ↔ effect-sorted list, Generate ▸ ↔ Bandwidth
#         presets: Selected/All, File ▸ Set Bandwidth preset folder…, an
#         overwrite option, and Explain ▸ Bandwidth. Default folder
#         C:\ProgramData\In The Mix\Bandwidth\Presets\User.
#   v3.9: ↩ RESET ALSO CLEARS THE STAGE (2026-10-17). His report: Reset did not
#         zero the contents of the ✋ Stage button and maybe not the room.
#         _var_reset now empties stage_manual (hand Roles / Sides / pairings
#         and the forced 🏠 room) and resyncs the Room button and the open
#         ✋ dialog. File > Clear all selections and the panel's Clear all
#         share the code, so they follow. With ⟳ Update holding, only memory
#         is cleared - the variant on disk keeps them until Update / close.
#   v3.8: TWO ROWS OF SINGERS NO LONGER STAND ON ONE SPOT (2026-10-14).
#         His report: 3 backing vocals (L60 C R60, Distance 72) and 3 Extra
#         Vocals at the SAME Distance 72 and L60 / L40 / L20 - "two different
#         levels of background singing on exactly the same place. Should
#         Extra Vocals not be further back?" Yes. Two faults:
#         - the Distance: Extra Vocals now stand BEHIND the backing vocals,
#           STAGE_BEHIND = one step (10) further back than the backing row,
#           whatever the backing row ended up at (hand Role, nudges). Without
#           backing vocals in the song it keeps its own Distance.
#         - the SHAPE: Extra Vocals is now a ROW like the backing vocals
#           (VSTAGE_LADDERED), so three of them stand L40 / Centre / R40 -
#           a narrower row behind the L60 / Centre / R60 one - instead of a
#           lopsided L60 / L40 / L20 on one side. One of them still takes
#           the side opposite the backing vocals.
#   v3.7: BACKING VOCALS COUNT AS ONE PLACE, AND A NEW VOCAL LAYER (2026-10-13).
#         His words: "Backing vocals alltid rakna som 1, oavsett antal... men
#         du kan lagga in ett nytt val: Huvudsang, bakgrundssang (ord) och en
#         niva till (ooooh/aaaah, snarkningar, slapande ord - 'Jag ar sa
#         trott' + 'sa trooootttt')... Backing extra / Extra vocals, det kan
#         raknas som ett separat instrument."
#         - stage_units(): vocals_backing and the new vocals_extra weigh ONE
#           place however many tracks there are (VSTAGE_COUNT_ONCE) - a vocal
#           stack is one group standing together, not a person per take. Its
#           x N ladder on the stage and the x N advice are unchanged; only the
#           ROOM count changes.
#         - NEW INSTRUMENT "Extra Vocals" (id vocals_extra, Vocals tab, right
#           after the sampled choir): oohs/aahs, whispers, snores and
#           trailing words ("sa troootttt" after "Jag ar sa trott"). Carried
#           through the engines that matter: EQ bands + tip, smart:EQ BACK,
#           Trackspacer duck under the lead vocal (swells back when the lead
#           stops - which is exactly the trailing-word effect), reverb depth
#           FAR, low cut, compression, x N advice, Virtual Stage family
#           (the side opposite the backing vocals), Corridor / Omega presets,
#           bus, pan, M/S, .keq label and the lead-vocal conflict tips.
#   v3.6: THE STAGE BY HAND, PER COPY - and a room you can force (2026-10-13).
#         His words: "Jag vill ha den knappen latthittad; kanske efter
#         Pick order-knappen. Den behover vara smart nog att dela upp. Nu har
#         jag 3 solo-gitarrer... och jag kan inte satta in att en eller tva
#         av dem ar supportive. Det behovs en rad (med den stems namn) for
#         varje sak." and: "en knapp dar jag kan FORCE annan rumstorlek".
#         - TWO NEW BUTTONS on the right panel's View row, right after
#           "Pick order" (and, like it, kept in the 🔎 focus view):
#           "✋ Stage" opens the by-hand dialog, "🏠 Room: Auto" picks the
#           room (Auto / Small / Medium / Large). The room is also a drop-down
#           inside the dialog.
#         - ONE ROW PER COPY. A part you have more than one of (x3 single
#           leads) gets a row per copy - "Single-String Lead (Low) #1, #2,
#           #3" - each with its own Role and Side. Saved in stage_manual as
#           "id" (copy 1, as before) and "id#2", "id#3" ... Copy rows have no
#           "Opposite of" (it pairs whole channels). The engine (stage_plan
#           step 4d) gives every copy its own Distance step from its Role,
#           seats the louder copies on the slots nearest the middle, pulls the
#           louder of two copies in (the v3.5 level balance), and prints the
#           result per copy: "#1 R65 · #2 Centre · #3 L65" and, when the
#           Distances differ, "Distance #1 18 · #2 30 · #3 18".
#         - FORCED ROOM. stage_manual["__room__"] = "Small"|"Medium"|"Large"
#           (absent = Auto). vstage_room(force=...) returns it with the
#           reason: the places it would have counted, and that a forced room
#           is final (no step-down for missing overheads). Saved per variant
#           with the hand placements, so the song keeps its room.
#   v3.5: SAVE MEANS UPDATE, A COUNT TICKS THE BOX, AND THE STAGE KNOWS WHO IS
#         LOUDER (2026-10-12).
#         - Save and Save as... now ALSO press Update. A saved variant that the
#           right-hand panel did not yet show was a variant saved "on the
#           side": _var_save used to snapshot the panel as if it had taken the
#           line-up in, while it had not (with the hold on, nothing had been
#           handed over). Both now go through _commit_left(), the same road
#           the Update button takes.
#         - More or fewer of an instrument that is NOT ticked ticks it
#           (_tick_if_count_changed). A real CHANGE only: a FocusOut that
#           leaves the number alone does nothing, so tabbing past a count box
#           can never switch an instrument on.
#         - DEL 02m, two new rules in stage_plan:
#             step 4  ONE VOICE OR TWO? Several lead vocals at once no longer
#                     all stand on Centre at one Distance. They are equal
#                     partners (the Co-lead logic, +-14 close to the middle,
#                     ONE shared Distance), and the sheet says that a
#                     double-tracked single singer is the other reading
#                     (main take Centre, double one step behind). The x N
#                     block of the lead vocal says the same (spread "duet").
#             step 4c LEVEL BALANCE. Two parts of one family on opposite
#                     sides, one carrying more of the song than the other
#                     (by Role: Lead/Feature louder, Support/Bed quieter),
#                     no longer mirror each other: the louder one is drawn IN
#                     towards the middle until the two weigh the same on the
#                     stage (position x level, 'centre of mass'). Equal roles
#                     (or both Auto) change nothing. Levels come from the
#                     Roles, STAGE_ROLE_WEIGHT; the program has no fader
#                     values, and the Role is what already says who leads.
#   v3.4: MORE ROLES IN THE VIRTUAL STAGE (DEL 02m) - not a new EQ layer.
#         His words: "Ar det inte i virtual stage som det ska justeras? Om det
#         ska in i EQ sa blir det ett himla pillande."
#         - He is right: Virtual Stage already has Role / Side / Opposite of,
#           and the EVA plug-in works out EQ, width and room from the PLACE a
#           part stands in. So "more than Bed and Lead" is more STEPS on the
#           same Role switch, not frequency dips to dial in by hand.
#         - Role is now Auto / Lead / Co-lead / Feature / Support / Double /
#           Harmony / Bed / Texture. Each one is a Distance step and a place
#           in the "who yields" queue; two of them also move a part sideways:
#             Co-lead  two or more equal partners (a duet, two main vocals)
#                      take opposite sides, close to the middle - the same
#                      thing "Opposite of" does for two parts that answer each
#                      other, done for the whole group at once.
#             Double   drawn halfway in towards the middle, just behind the
#                      part it doubles.
#         - Guitar / Guitar R: Role says which of them carries the song at the
#           moment, "Opposite of" keeps them on opposite sides - flip the Role
#           when the arrangement flips.
#         - The basses are NOT in the dialog, on purpose: Virtual Stage stays
#           OFF a bass (room on a bass is mud). A second bass (grit layer) is
#           the existing "x2 on a bass" option on the bass's own card.
#   v3.3: THE LEFT SIDE IS A SCRATCH PAD - and three buttons at the end of
#         the Song Variants toolbar say what happens to it.
#         His words: "sa fort som jag lagger till en cymbal, sa ska allt
#         blinka till (och andras). Det ar en stonig process. Battre att
#         jag kan andra vad jag vill (i vanster-delen), UTAN att det andras
#         nagot i hogerdelen... forr an jag klickar pa Update."
#         - NEW SETTING "hold_left_updates" (default ON, View menu turns it
#           off). The right-hand panel is a SNAPSHOT of the last line-up
#           committed to it; _applied_sel / _applied_counts are that
#           snapshot; _checked_ids() and _count_of() hand it back for as
#           long as something is waiting. Every engine in this program asks
#           the line-up through those two, so that is the whole mechanism -
#           no second copy of the panel, no frozen widgets. "Waiting" is
#           COMPUTED by comparing the two sides (_compute_pending_bits), so
#           it can never be a flag somebody forgot to clear.
#         - THE RIGHT SIDE NEVER WAITS. A count changed on the
#           Selected-Instruments row still goes in the moment it is touched
#           (from_summary), which is what he asked for: two ways round, and
#           he picks per action.
#         - ⟳ Update turns amber and counts what is waiting; an amber line
#           at the top of the panel says the same thing and is clickable. A
#           snapshot that does not say it is a snapshot is a wrong answer.
#         - ↩ Reset = a BLANK left side: every box off, every count back to
#           1 ("nollstaller alla markerade checkbox till OFF och alla
#           siffror till 1"). File > Clear all selections and the panel's
#           own Clear all now CALL it, so the three cannot drift apart -
#           the only difference there ever was is that they forgot the
#           counts. It asks first only when it cannot be taken back, i.e.
#           with the hold switched off; with the hold ON the panel and the
#           saved variant both still hold the line-up, so clicking that
#           variant in the list loads it straight back.
#         - ⚓ Ground = the line-up you always come back to. Shift-click the
#           button (or File ▸ Set … as my Ground) saves it. A SNAPSHOT and
#           not a pointer at a variant: a pointer is tidy right up to the
#           evening that variant is renamed, and then the one button that is
#           meant to always work is the one that does nothing.
#         - Room for three more buttons came from the padding: padx 8 -> 5,
#           gap 2 -> 1, plus a hairline so the three that act on the LINE-UP
#           are visibly not three more ways to act on the LIST of variants.
#         - Nothing is lost by never clicking Update: whatever is waiting is
#           written into the variant on close, exactly as it always was -
#           except that an EMPTY left side is never written over a variant
#           that has a line-up. Reset + close would otherwise wipe it with
#           no way back, and that promise is about the work, not about the
#           absence of it. Emptying a variant on purpose is one Update.
#
#         A COUNT ON A CHANNEL THAT IS NOT IN THE MIX REDRAWS NOTHING.
#         His report: "varfor det blinkar i hogerdelen, nar jag andrar antal
#         pa ett instrument, som inte ar aktivt... det borde inte paverka
#         valda instruments installningar."
#         - It should not, and it never did: stage_plan() lays out what is
#           TICKED and so does every other engine here. Four celli you are
#           not using cannot change one number on the right - and the whole
#           panel was being rebuilt for them anyway.
#         - _live_multi holders now carry their channel id, so
#           _refresh_multi_notes(only=iid) redraws that one ✖N box and
#           leaves every other widget on screen alone.
#
#         ✋ MANUAL INFLUENCE ON THE VIRTUAL STAGE (DEL 02m).
#         His words: "Ibland sa kanske jag vill markera att en piano-riff
#         inte ska ligga ovanpa utan vara en grund... att jag tycker att
#         nagot borde vara motpol till nagot annat = kanske inte optimalt
#         att bagge ar R."
#         - Three switches, and every one of them is about the ARRANGEMENT
#           rather than the instrument - which is exactly why no amount of
#           looking at the line-up could ever have worked them out:
#             ROLE        Bed pushes a channel back (+16 Distance) and makes
#                         it the one that MOVES in a collision; Feature
#                         walks it forward (-14) and makes it the one that
#                         STAYS PUT. A piano riff can be either, and the
#                         channel looks identical both ways.
#             SIDE        Left / Right / Centre, for a reason nothing in a
#                         mix can see. Centre also pins Lock Position ON.
#             OPPOSITE OF the counterpole. Written both ways round, because
#                         it is one fact about two channels.
#         - Honoured BEFORE the balance pass (step 2c) and the counterpoles
#           after the ladders and before the collision pass (step 4b), so
#           the rest of the stage is laid out AROUND a hand placement rather
#           than over it, and the result is still collision-checked.
#         - Every override writes its own line, starting with ✋ and the
#           word YOU, and those lines are SETTINGS - never hidden with the
#           why-lines. The sheet must always be able to say which numbers
#           are its own and which are his.
#         - A hand-placed channel WINS a collision. When TWO hand-placed
#           channels collide, neither moves and both say so: inventing a
#           compromise would silently undo the decision that was made on
#           purpose.
#         - The kit and the VSTAGE_SKIP channels are not offered at all. The
#           kit is laid out as ONE object (drum_stage_plan) and one drum
#           dragged out of it is a broken kit; a position on a channel this
#           plug-in is supposed to be OFF would contradict the reason
#           printed next to it.
#         - Saved per VARIANT ("stage_manual"), because whether a riff is
#           the hook or the bed is a fact about the song. Applied at once -
#           a dialog is a decision, not a tick you are still thinking about.
#         - View ▸ ✋ Virtual Stage by hand, and a button in the 🎪 Stage map.
#
#         AND THE TICK ON A CARD FINALLY MEANS THE SAME AS THE TICK IN THE
#         PICKER. It never reached the variant, so it was thrown away the
#         next time that variant was loaded. Same question, one answer.
#
#   v3.2: ONE BUTTON DECIDES THE ORDER OF THE RIGHT PANEL - and the new
#         default is YOUR order, not the room's.
#         - His words: "jag behover vaxlingsknapp for att valja mellan att visa
#           befintlig 'per position' och 'i samma ordning som jag valjer
#           instrument (sa att jag far alla gitarrer efter varandra)'... som
#           ska vara default."
#         - Both list views were sorted by WHERE A CHANNEL SITS, and neither
#           said so. The Channel Plan split every song into three boxes -
#           FRONT / MID / BACK, the smart:EQ priority. The Instruments view
#           sorted by reverb bus (Front / Near / Mid / Far / DRY). Right for
#           routing, wrong for reading: a chord guitar in FRONT and a rhythm
#           guitar in BACK are two screens apart, and comparing the two things
#           you are actually deciding between meant scrolling past the drums.
#         - New setting "list_order": "pick" (DEFAULT) | "position", one
#           StringVar (self.list_order_var) shared by the new "⇅" button on the
#           right panel's View row and the two View-menu radio items, so they
#           can never disagree. Remembered between runs like every other view
#           choice.
#         - "pick" = the order the instruments stand in the picker on the left,
#           which is EQ_DATA order - the one list that decides where an
#           instrument turns up anywhere in this program. All the guitars after
#           each other, because that is how the picker lists them.
#         - NOTHING IS LOST in pick order, which is the point: the Channel Plan
#           still prints the tier on every row (_TIER_GLYPH: the same ▲ ■ ▼ in
#           the same three colours as the box headings it replaces), and every
#           block in the Instruments view still carries its own reverb line.
#           What goes is only the SPLIT.
#         - The ⇅ button greys out in the 🔀 Effects view: that one is sorted by
#           the effect you picked, and an order button there would be a lie.
#         - Deliberately NOT in _panel_extra_btns, so the 🔎 focus view keeps
#           it on the row - the short face is exactly where it is used.
#
#   v3.1: FILLER OR MELODY IS A ROLE, and three instruments now say which.
#         - His question: "borde det inte vara skillnad pa om Organ ar
#           fyllnadsinstrument eller melodiinstrument?" It should, and the
#           program only had the filler. The piano has had that split from the
#           beginning (Background Piano / Piano Riff) and the organ never got
#           it, so an organ solo was being mixed with a pad recipe: low warmth
#           kept, 300-600 Hz left alone, width encouraged, BACK priority - the
#           four things that stop a melody from being heard as a melody.
#         - Then, his second answer: "jag har ofta brass och strings som
#           melodier ocksa... inte bara som utfyllnad." So the same split runs
#           through all three. THREE new ids - organ_lead, brass_lead,
#           strings_lead - beside the beds they belong to, and the beds are
#           untouched. "organ" is now called Background Organ (same data,
#           clearer name against its own lead).
#         - Each new id is carried through every engine: EQ bands, smart:EQ
#           tier, duck, depth, low cut, comp, multiples, stage spot, Corridor,
#           Omega, pan, M/S, .keq label, lead priority, the conflict rules and
#           the mix recommendations. The ids are NEW, so nothing saved changes:
#           old variants, old settings files and old .keq presets still say
#           "organ" / "brass" / "string_section" and still mean the filler.
#         - BED_LEAD_PAIRS (DEL 02) is the new single source of truth for the
#           three pairs - what to say about them, and how high to push the
#           lead's high-pass when the bed plays as well (organ 250 Hz, brass
#           200, strings 160 - a string tune can live in the cello register,
#           a trumpet line cannot go below its own 165 Hz floor). Both the
#           conflict view and the mix recommendations loop over it, so a
#           fourth pair is one tuple, not two more if-statements.
#         - The String Section had NO 1-3 kHz band at all - correct for a bed,
#           fatal for a tune. Lead Strings has one, and it is the loudest move
#           in the whole entry (+4 dB).
#         - "fixa dem med": accordion, flute and violin too, so SIX pairs. And
#           here the DIRECTION flips, which is the thing to notice. The
#           accordion card is a filler, so it got a new LEAD (Lead Accordion).
#           The Flute and Violin cards are already SOLO cards - "Transverse
#           flute / solo", core +4, breath +5, air +4 - so what was missing is
#           the BED, and they got Background Flute and Background Violin
#           instead. BED_LEAD_PAIRS does not care which half is the new one,
#           which is exactly why it is a tuple and not a naming convention.
#         - The single band that tells the whole story, per pair: the Violin
#           card BOOSTS 1-3 kHz +3 and Background Violin CUTS it -3. A held
#           violin that keeps the solo curve is why a tune under it vanishes.
#           Same shape on the flute: the solo lives on 4-8 kHz breath, the bed
#           cuts it (that breath is hiss when it is held for four bars).
#         - Beds that were never ducked now are: plain Flute and Violin have no
#           DUCKING entry at all (a solo does not duck), so Background Flute and
#           Background Violin got their own, under the lead vocal.
#         - NOT changed, deliberately: Flute and Violin keep their
#           "Background: Winds" / "Background: Strings" bus, even though the new
#           lead ids all go straight to Master. Moving them would silently
#           re-route sessions that already exist. Say the word and they move.
#         - Where the two actually differ: high-pass 80 Hz vs 150 - warmth
#           +3 dB @100-200 Hz vs +2 @200-350 - mud -2 vs -4 - 1-3 kHz +3 vs +4
#           (the note core, and this is the one that matters) - shimmer +3 vs
#           +2 - BACK vs MID - wide vs centre - gentle vs control - medium
#           reverb send vs light - and the lead keeps its own path instead of
#           riding the Background: Keys bus. Same Corridor room on purpose: it
#           is one player in one building, so it sends LESS, it does not move.
#   v3.0: THE WINDOW HAS TWO FACES - and the short one is the normal one.
#         - 🔎 FOCUS VIEW. His own description of how he uses this program:
#           "jag bara kollar instruments in this variant + selected instruments
#           (och vill kunna snabb-se Channel plan ocksa). Det andra ar bra, men
#           behover inte vara synligt hela tiden." So that is now the window it
#           opens as: the ★ Song Variants tab with "Instruments in this
#           variant" on the left, "📋 Selected Instruments" on the right with
#           its three View buttons (📐 Channel Plan is one click away) and its
#           Filter row, the BOOST/CUT/TRY legend, and 🎪 Stage map. One button
#           in the title bar - "⚙ Show everything" / "🔎 Focus" - swaps to the
#           long face and back, and the choice is remembered.
#           Hidden by the short face, on his answers: the EQ engine row ("vet
#           jag inte ens vad det ar"), ⚠ Conflicts & recommendations ("kollar
#           jag aldrig heller" - four cymbals are four cymbals, and Virtual
#           Stage is what spreads them), the 📚 theory tabs, the 🧩 Plugins
#           tab, and the 📐/🌫/🎯/🗺/🦻 popup buttons. NOTHING is destroyed:
#           the widgets are unpacked and packed straight back with their ticks,
#           their text and their scroll positions intact, and every hidden
#           button also has a home on the View / Generate / Help menus, so
#           nothing is reachable only through the long face.
#         - FIVE FILTER BOXES BECAME ONE: "⚙ Set & forget" = Low cut · EQ ·
#           Comp. · SubMass · Pan. His reason, and it is the right one: those
#           are the five he has never once ticked, because they are dialled
#           once and then they are simply true. One box brings all five back on
#           the day he wants to look. The SECTION keys underneath are unchanged,
#           so _build_summary_block and older settings files still work - an
#           old file with "lowcut" in it opens with the new box ticked.
#         - CHORD GUITAR NOW SITS ABOVE RHYTHM GUITAR in EQ_DATA, which is the
#           order the tabs, the variant list, the panel and the Channel Plan
#           all read. His order.
#         - FIXED, and it was a live one: _apply_theory_tabs() walked the WHOLE
#           tab_frames dict, which also holds the two special keys
#           "__variants__" and "__plugins__". It runs once at the end of
#           _build_tabs(), so in v2.9 (verified by running it) EVERY start
#           relabelled the two tabs "__variants__" and "__plugins__", and
#           unticking View ▸ Theory tabs hid every tab in the window — the
#           whole left side went blank. Both keys are stepped over now: Song
#           Variants is always on, Plugins follows the focus view.
#   v2.9: DEFAULTS & DEVIATIONS (Δ) - read the difference, not the answer.
#         - THE ROOM IS COUNTED IN PLACES ON THE STAGE, NOT IN CHANNELS. His
#           question, and it was the right one: "should a drum kit not have the
#           same place in the room whether it has 1 tom or 4, 0 cymbals or 7?"
#           It should, and vstage_room() was counting ticked channels, so a
#           well-miked kit looked like five performers. stage_units() now
#           counts: the whole kit = 1 place (including the shaker/tambourine
#           extras, which are played from behind it), hand drums = their own
#           place, every other instrument = 1 each and x2 really is 2, a
#           section or a bed = 2 (one channel, but not one person). Scale, his:
#           1-5 Small, 6-10 Medium, 11+ Large - troubadour, rock band, big or
#           over-produced. It also retired the old "a pad plus cymbals plus 11
#           channels" special case: a bed weighs 2 because a bed IS wide.
#         - PERCUSSION SPLIT IN TWO, also his: "Percussion extras" (shaker,
#           cowbell, tambourine, chimes) is played from the kit and counts as
#           part of it, while the new HAND DRUMS (congas, bongos, djembe,
#           taiko) needs a second player and gets its own place on the stage.
#           37 instruments now. The percussion ID did not change, so his saved
#           variants still point at the right thing.
#         - ONE DEFAULT SET PER ROOM SIZE (DEFAULT_BANDS). A single set could
#           only ever be right in one room; in the other two every channel
#           would light up its Room field. Three bands - Small 4 places, Medium
#           9 (his own band), Large 14 - each sized to stay in its own room
#           WITH ONE GUEST standing in it, and the sheet compares against the
#           set for the room this song is in. The Defaults window can pin a
#           size to print that set.
#         - DEL 02p - every instrument gets a DEFAULT: what it is set to when
#           there is ONE of it, in the kind of song it usually turns up in. He
#           saves that in each plug-in's own preset, and from then on the sheet
#           is read the other way round - a field that MATCHES the default is
#           greyed out (the preset already did it), a field that does not keeps
#           its colour and gets a Δ in the margin (this song is the exception,
#           dial it). "Then I do not have to double-check whether I really have
#           the right setting in every VST."
#         - WHERE A DEFAULT COMES FROM: THE DEFAULT BAND (DEFAULT_BAND, his
#           own list). One line-up of thirteen - lead vocal + backing vocals,
#           chord + rhythm guitar, bass + bass X, kick, snare, hi-hat, tom,
#           cymbal, piano, organ - and
#           EVERYTHING ELSE gets its default by standing in that band as a
#           GUEST, one of it: the ride beside the band's hi-hat, the percussion
#           beside its kit, a cello in front of its guitars. One rule, and it is
#           the context he named for each of them.
#         - Two things measuring his list settled. (a) The solo guitar is a
#           guest, on his own condition "if it does not affect the other
#           guitars": it does, a third guitar widens the row and the other two
#           go R65/L65 -> R75/L75. Same for ride and percussion, which move the
#           hi-hat R20 -> R25. (b) Thirteen, not sixteen: the room engine steps
#           up to Large at 15 channels, so 13 + one guest = 14 keeps the whole
#           chart in ONE room. A fourteenth permanent member would break that.
#           (c) The two vocals move nothing and FIX something: the backing
#           vocals go R30 -> R50, properly off a lead vocal that is now always
#           there, instead of the position a lone guest gets.
#         - The older way is still there under View: a VOTE over ten reference
#           songs, PER FIELD. Voting on the whole line gave Virtual Stage
#           defaults that had won one song out of five, because a Position that
#           moved dragged Distance and Room with it. It is the better answer for
#           an instrument his band never contains, and it prints the score of
#           any field the songs did not agree on.
#         - The Δ switch is ON by default and sits in the View menu AND on the
#           Filter row; 'View > Defaults...' opens the whole list with the vote
#           printed beside each field and a Copy-all, which is what he builds
#           the presets from. It can vote over his own Song Variants instead.
#         - THE RESULT, measured on his own default mix: of everything the nine
#           engines print, only the Virtual Stage of two channels and the ducks
#           whose source is not in the song came back in colour. Everything else
#           is grey, which is the whole point - those are the rows he stops
#           reading.
#         - The duck is the one engine whose default is NOT voted: "no ducking
#           needed" cannot be saved in a preset, so its default is always the
#           configured duck and a song without the side-chain source is a
#           deviation every time. That IS the song where Trackspacer comes off.
#   v2.8: OMEGA 458a (Kush Audio) + the stage counted wrong.
#         - DEL 02o - OMEGA 458a. A transformer/preamp saturator, and the
#           best-documented plug-in in this program: it ships its own
#           <ENGINEDATA> table inside the .vst3 naming every parameter, range,
#           step, default and skew, the complete signal path and the fixed EQ
#           curve the model applies. So unlike Corridor (ranges inferred) and
#           unlike smart:EQ (an opaque blob we can only clone), NOTHING here is
#           guessed. 25 presets, one for every one of the 37 instruments, each
#           written into the plug-in's declared ranges and read back field by
#           field before it is kept. A seed of his own is still the CONTAINER.
#           The four facts that shaped the presets, all read out of the plug-in:
#             · THE HPF/LPF SIT BEFORE THE SATURATOR AND THE DRY PATH IS TAPPED
#               BEFORE THEM. HPF 140 + Blend 50 % = the saturator never sees the
#               sub, while half the original arrives untouched. That is the Kick
#               and Bass preset, and the only honest way to saturate low end.
#             · INTENSITY IS A MACRO, not a drive knob: it moves the saturator
#               drive (-28.25…+15.45 dB), a 61 Hz bump, a 12.5 kHz lift, a
#               1.79 kHz dip and 27 dB of compressor make-up compensation at
#               once — most of the level, not all of it.
#             · MAKEUP IS BEFORE THE BLEND, OUTPUT GAIN IS AFTER. Identical at
#               Blend 100 %, different the moment you blend.
#             · THE -20 dB PAD IS COMPENSATED (-20 in, +20 out), so it drops the
#               SATURATION by 20 dB and leaves the level alone — which Input
#               Gain does not. Hence the Bus preset is the only one using it.
#           And there is a Kush compressor in the path with no user control at
#           all (attack 3.24 ms / release 135 ms), which is why it thickens even
#           at low Intensity and why it works on a snare.
#           omega_overlap() cross-checks the model's fixed +6.4 dB @ 376 Hz /
#           +0.3 dB @ 2.13 kHz / +1.2 dB @ 16.2 kHz against the instrument's own
#           Kirchhoff chart and prints a ↔ line where the two would make the
#           same move twice.
#           Surfaces: a 🔥 footnote on every card and block (placed after the
#           low cut, before the EQ — it IS the input stage), 'Omega' in the 📋
#           filter row, a 🔥 effect-sorted list, Generate ▸ 🔥 Omega 458a
#           presets: Selected/All, File ▸ Set Omega 458a preset folder…, an
#           overwrite option, and Explain ▸ Omega 458a.
#
#         THE STAGE COUNTED WRONG (reported 2026-09-07).
#         - ✖1, ✖2 AND ✖3 BACKING VOCALS ALL PRINTED "L50 · Centre · R50".
#           stage_plan() step 4 laddered the three VSTAGE_LADDERED channels
#           (backing vocals, horn section, string section) with max(n, 3)
#           instead of n, so the row only started counting at four. One singer
#           cannot stand in three places, and the middle rung of that ladder was
#           dead centre — where the lead vocal already is. Now:
#             ✖1 → ONE position, and it keeps the one the family/crowding
#                  passes worked out (R50, off to the side) rather than landing
#                  on the lead. Virtual Stage has one Position per instance, so
#                  a row needs at least two channels to be a row.
#             ✖2 → L50 · R50      ✖3 → L50 · Centre · R50    ✖N → N positions.
#         - THE SAME FAULT, ONE LEVEL DOWN: positions print rounded to 5 and
#           anything inside ±5 prints as "Centre", so any ladder tighter than 15
#           handed out the same instruction twice — 'double_bass ✖3 → L20 ·
#           Centre · Centre'. STAGE_RUNG_MIN widens a row until its rungs are
#           really apart, as far as the family is allowed to reach; step 5b then
#           checks the FINAL labels and, when the stage has genuinely run out of
#           places, says so instead of printing one spot twice.
#         - AND THE PROGRAM CONTRADICTED ITSELF. The ✖N engine calls a lead
#           vocal and a double bass MONO with verdict 'layer' ("split the
#           frequency range, not the stereo field") while the stage laddered
#           them anyway. Step 4 now asks multi_rule() and refuses to spread a
#           mono part, quoting the ✖N block so the two agree on screen.
#         - Found by sweeping every instrument × ✖1–✖8 × both perspectives and
#           diffing multi_pan_ladder() against stage_plan(); the kit ladders and
#           every non-laddered channel are unchanged.
#
#   v2.7: LESS SCROLLING, MORE ROOM.
#         - DEL 02n - CORRIDOR (Quantastical Sound). A reverb whose preset is
#           plain readable XML, so this program writes REAL presets for it from
#           the chart instead of cloning a seed (the trick smart:EQ forces on
#           us). 20 of them, weighted hard toward voices: five for a lead vocal,
#           three for backing, two for a choir/pad, then one space each for the
#           kit, guitars, piano, organ, horns, strings, a pad and percussion.
#           Dry channels get none, on purpose. One of the user's own presets is
#           still needed as the CONTAINER (class id, JUCE trailer, RoomPans), so
#           every generated file is one this exact build already accepts, and
#           each one is read back after it is written. Corridor names its rooms
#           but not their order, so CORRIDOR_USE_ROOM_MODELS stays False and
#           every preset uses the model his test preset proves is good.
#         - HOW MUCH PROSE. Every explanatory line now goes through
#           _note_label() and is either a SETTING (never hidden) or a WHY. View
#           menu: "Extra comments" (default OFF) hides the whys - "The top of
#           the sweep stops at ~R42 because...", "Flipped to the other side..."
#           - which do not change a single number you dial in; and "Hide empty
#           comment rows" (default ON) collapses a section that has a head line
#           and nothing under it. Side-chain lines, Trackspacer amounts, the
#           Kickstart curve and every warning stay put. The Stage map and the
#           Explain windows ignore both settings - you open those to read the
#           reasoning.
#         - VIRTUAL STAGE, THE ONE EXCEPTION. "Never on a bass" is right for
#           ONE bass. At two, the ✖N plan has already split them into a
#           foundation below 100 Hz and a character layer high-passed at
#           100-120 Hz - and the ban was a low-end ban, so the layer with no low
#           end left may have it. vstage_multi_option() offers it with the
#           numbers and with the condition that decides it (two PARTS, or one
#           bass in two layers?). The kick never gets the exception.
#         - "HOW MANY" ON THE SELECTED-INSTRUMENTS ROW. The count and a reset
#           now sit on every block header in the right-hand panel, sharing the
#           card's variable. Editing there does NOT rebuild the panel the widget
#           lives in - it refreshes only what the count feeds.
#
#   v2.6: WHERE DOES IT STAND? (🎪 Virtual Stage, EVA Instruments)
#         • DEL 02m - VIRTUAL STAGE. Position · Distance · Room · Lock Position
#           for every channel — and, unlike every other engine in this program,
#           it writes NO PRESETS. That is deliberate: the numbers depend on the
#           rest of the line-up, so a saved preset would be a snapshot of a song
#           you are no longer mixing. stage_plan() lays out the WHOLE band at
#           once and every channel carries a "because" list saying what moved it:
#             - STAGE_FILL: one of a family sits at 0.50 of its half-width, two
#               at 0.82, three at 0.93, four+ at 1.00. So a lone chord guitar
#               lands at R40 and a rhythm+chord pair at L65/R65.
#             - a min-gap collision pass in which the channel that YIELDS under
#               masking (smart:EQ BACK before MID before FRONT) is the one that
#               moves, and STAGE_SAME_DIST so a guitar pair / horn line / string
#               desk ends up on ONE line.
#             - drum_stage_plan(): the kit as one object. No toms → hats/ride
#               move OUT to cover the empty flanks. No overheads → the whole kit
#               moves FORWARD and the room drops a size. Hi-hat and/or ride →
#               pulled in toward centre (v3.23: both ticked = they take turns, so
#               still pulled in). Kick+snare only → everything centre.
#               Kick and both basses → the plug-in stays OFF, with the reason.
#             - ONE room for the whole song (vstage_room), never per channel.
#           Shown as a 🎪 footnote on every card, as a chip in the Channel Plan,
#           as its own effect-sorted list, and in the 🎪 Stage map window (a
#           top-down map + the numbers + why each one is what it is).
#
#   v2.5: HOW MANY + WHO IS PLAYING + MIXING WITH HEARING LOSS.
#         • DEL 02j - MULTIPLES. "Does it matter if I have one or two of these?"
#           YES, and now the program says exactly what changes. The count you
#           set in Song Variants (and NEW: right on every instrument card) drives
#           real advice: the stacking gain (+3 dB per doubling, so pull each copy
#           down 10·log10(N)), a per-copy PAN LADDER, a per-copy TONE SPLIT (who
#           owns which band), a HIGH-PASS LADDER (copy 2+ cut higher), a REVERB
#           ladder (one forward, the rest further back) and the bus verdict.
#           MULTI_ADVICE holds the per-instrument version (two rhythm guitars are
#           not two pads); everything else falls back to a group-level rule.
#           Shown on the card, in the right panel, the Channel Plan (×N), the
#           Planner and the Variants conflict list.
#         • DEL 02k - HEARING PROFILE (🦻). The point of this program is to
#           replace an ear you cannot fully trust. Tell it, per octave band,
#           whether you hear that range well / unsure / not at all, and it:
#             - marks EVERY band row with ✔ / ◐ / ⛔ ("judge by ear" vs "use the
#               number and don't touch it"),
#             - CAPS boosts in your lost ranges (the classic hearing-loss trap is
#               boosting until YOU hear it — everyone else then gets a harsh mix),
#             - turns "TRY / depends on the track" bands inside a lost range into
#               a DECIDED number,
#             - prints a personal 🦻 rules window: what to set by number, what to
#               check on a meter, and which of your plugins DECIDE BY ANALYSIS
#               instead of by ear (smart:EQ, smart:comp, Bandwidth presets).
#           Off until you fill it in; nothing changes for a normal user.
#         • NEW INSTRUMENTS: Trumpet, Trombone, Saxophone, Horn Section,
#           Harmonica and (a real hole) Acoustic Guitar. 'Brass' stays as the
#           generic section card but no longer claims to cover the saxophone —
#           a sax is a reed, not a brass instrument, and it is EQ'd differently.
#         • ★ FOCUS PLUGINS: the eight you actually work with right now sit in a
#           pinned box at the top of the 🧩 Plugins tab, are starred in the list
#           and in the insert map, and have their own filter. Click ★ on any row
#           to add/remove; the set is remembered (settings 'focus_plugins').
#   v2.4: ADVICE THAT KNOWS WHAT IS IN THE SONG + Accordion + All/none per tab.
#         • ADVICE IS NOW SOURCE-CHECKED. A song with bass + piano and NO drums
#           used to be told to "duck the bass under the kick". Every duck names
#           the instrument(s) that can trigger it (DUCK_SOURCE_IDS) and
#           ducking_for(iid, selected_ids) hides it when that source is not in
#           the song — in the instrument cards, the right-hand summary, the
#           🔀 Effects duck view, the channel plan and the Planner table. The
#           card prints a dim "No ducking needed — there is no Kick in this
#           song" instead, so you can see WHY the line is gone. With nothing
#           ticked the cards stay in reference mode and show every duck.
#         • Same idea for partner-dependent SENTENCES (PARTNER_NOTES): the bass
#           no longer reads "split 60–100 Hz with the kick AND sidechain" or
#           "pair with the kick sidechain" when there is no kick, and the kick
#           does not talk about a bass that isn't there.
#         • NEW INSTRUMENT: Accordion (Keys & Winds) — full card, low-cut,
#           compressor, smart:EQ tier, reverb depth, pan, M/S, duck-under-vocal,
#           bus routing, Kirchhoff label, plus its own conflict tips (mid-range
#           clash with organ/piano/guitars, left-hand reeds doubling the bass).
#         • ALL / NONE per instrument tab: a tri-state checkbox in every group
#           tab's toolbar ticks or clears that whole tab in one click (Drums &
#           Percussion, Bass, Guitar, …). "Some ticked" shows as tri-state, and
#           clicking it then selects the whole tab.
#   v2.3: BUS ROADMAP + smart:EQ merge suggestions + less noise.
#         • DEL 02i: the routing tree (BUS_LEAF / BUS_PARENT / build_roadmap).
#           Your drum convention is baked in — Kick+Snare→Drums: Front, Toms→
#           Drums: Toms, +Hats/Ride→Drums: Mid, Cymbals→Drums: Cymbals,
#           +Percussion→Drums: Back, all three→Drums: All — plus a Bass bus, a
#           Guitars bus and Background: Keys/Winds/Strings→Background: All. A bus
#           is DISSOLVED automatically unless ≥2 channels sit under it, so one
#           lonely tom never gets its own bus. New 🗺 Roadmap window (right-panel
#           button, Generate menu, Explain topic): the tree, a numbered Cubase
#           build order, and which bus carries which smart:EQ slot.
#         • smart:EQ no longer just reports "11 buses > 10 slots". SMARTEQ_MERGES
#           lists the cheapest merges best-first; the program APPLIES them until
#           the plan fits and COLOURS the buses that belong together (one colour
#           per merge), showing what it did and what is still optional.
#         • Noise removed: no "No reverb (keep DRY)" anywhere (a channel with no
#           reverb simply has no reverb line), no per-duck "start gentle" repeat
#           (it lives once, in the Effects duck view / Explain / Help), and the
#           duck side-chain + band now share one line.
#         • Defaults you actually use: right panel opens on 📋 Instruments with
#           EQ-group + Duck + Reverb ticked. Both are remembered between runs.
#         • Lead Guitar removed from the instrument list (HIDDEN_INSTRUMENT_IDS —
#           delete the id from that set to bring it back; its data is untouched).
#         • PLUGIN_VERDICT: program-authored "should I actually be using this?"
#           answers on the 🧩 Plugins tab, with a ★ Start using these box. Honest
#           "ask" verdicts where the plug-in could not be verified.
#   v1.9: DSPTone SubMass — tracked sub-harmonic 'feel' generator added as a
#         core tool. Amp/Freq/Center (the 3 verified 0..1 params) are patched
#         IN PLACE into a user-made SEED .vstpreset (flat JUCE ValueTree, not
#         protobuf/XML — same "patch the doubles in place, don't rebuild"
#         approach as smart:reverb/Lowtility). Only sounds worth reinforcing
#         (kick, basses) get an entry/footnote/generated preset — SUBMASS
#         dict. Chain position: after Comp/Duck, before Width/Chorus/sends
#         (PLUGIN_KIND_CHAIN["Sub"] = 42). Folder default: Documents\VST3
#         Presets\DSPTone\SubMass (Generate ▸ SubMass presets / File ▸ Set
#         SubMass preset folder…). Level + Mono-below-Hz left at the seed's
#         own values (no second verified data point yet for those two).
#   v1.8: smart:reverb preset generation — EXACT Distance/Size/Width patched (in
#         place) into a user-made SEED preset (the .vstpreset plugin state is
#         protobuf; only 3 fixed-size floats change, learned profile untouched).
#         Per-instrument or per-tier (bus) layout. smart:EQ is NOT generated (a
#         clone drags the seed's name + EQ onto every track) — add it manually +
#         Learn, ranked by the Front/Mid/Back tier the program prints (DEL 02f).
#         Effect-sorting view auto-scrolls to top. Pan glossary ('Spread',
#         'Wide L+R') added to the Pan view and Help. Low-cut effect view groups
#         identical Hz·dB/oct into colour-coded sections.
#   v1.8b: Kirchhoff presets ALSO written as Cubase .vstpreset (the .keq only show
#         in Kirchhoff's OWN browser; .vstpreset show in CUBASE's). The .vstpreset
#         is a VST3 wrapper around the .keq JSON — built from a template the user
#         already has (keq_json_to_vstpreset). '+ .vstpreset (Cubase)' checkbox.
#   1. Imports & AppUserModelID (must be before tk.Tk())
#   2. Constants: colors, fonts, EQ data
#   3. Helper: no_blink(), _set_window_icon(), settings persistence
#   4. App class:
#      a. __init__ / layout
#      b. Tab: Drums & Percussion
#      c. Tab: Bass
#      d. Tab: Guitar
#      e. Tab: Keys & Winds
#      f. Summary panel (right side, shows checked instruments together)
#      g. Menu: Help, About
#      h. Settings save/load
#   5. Crash catcher / main()
# =============================================================================

# *************** DEL 01 - IMPORTS & APPUSERMODELID ***************************

import ctypes
import os
import sys
import platform
import json
import re
import math
import struct
import base64
import traceback
import webbrowser
import tkinter as tk
from tkinter import ttk
from tkinter import font as tkfont
from datetime import datetime
import os
import sys


# ---- Where Helpfiles and Icons live -----------------------------------------
# Helpfiles is a SIBLING of the program's folder, not a child of it, so the
# answer is "the nearest folder above me that holds Helpfiles". One rule covers
# Py\, Folder-exe\<Name>\ and the old layout alike, so it stops mattering
# where the .py or the .exe is put. Capped at four levels so a stray Helpfiles
# far up the tree is not adopted by accident; nothing found means behave as
# before, which is what keeps a test copy away from live data.
def _find_home(start):
    # Py\ and Folder-exe\<Name>\ are ALWAYS direct children of home, so
    # their own name settles it. This runs BEFORE the walk: a stray
    # Helpfiles inside Py\ used to win the walk and silently became every
    # program's home - that is how Notes lost a day (2026-09-04).
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    if os.path.basename(os.path.dirname(start)).lower() == "folder-exe":
        return os.path.dirname(os.path.dirname(start))
    # Otherwise: the nearest folder above me that HAS a Helpfiles. Capped at
    # four levels so a stray one far up is not adopted by accident; nothing
    # found means behave as before, which keeps a test copy off live data.
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower checks for this before offering the swap


import subprocess   # used by the block below

# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# A link, a folder, a PDF, a log or an image opened from here should land in MY
# programs - not in Edge, Explorer, Notepad or Adobe.
#
# Registering them as Windows' default apps is possible but miserable, and
# Windows identifies an application by its .exe PATH: point every file type at
# pythonw.exe and Windows sees ONE app called "Python" for all of them, with
# one icon, and Default Apps cannot tell WhyBrowse from F(re)email.
#
# WHICH program opens WHAT is NOT decided here.  It is decided in one file,
#
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
#
# so changing "PDFs open in X instead of PDFull" is one edit in one place, not
# 122 edits in 122 sources.  This block only reads that table and acts on it.
# _FALLBACK_KINDS below is used only when the file cannot be read, so a
# program still works on a machine that has no DefaultHub.
#
# Three rules this block must never break:
#
#   1. It may never raise.  The Help button has to open even when WhyBrowse is
#      missing, broken, or mid-rebuild, and even when defaults.json is gone.
#   2. It may never hand a thing to ITSELF (File_manager opening a folder,
#      WhyBrowse opening a link) - that is how you build a loop.
#   3. Popen, never run().  run() would freeze this program until the browser
#      is closed again.
#
# NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it would start another copy of this program instead of Python.
# (PyManager did exactly that on 2026-09-04 and fork-bombed the machine.)
#
# Cost, measured 2026-09-05: the table is read ONCE, the first time something
# is actually opened - 0.11 ms cold, 0.05 ms warm, plus 0.04 ms of path
# checks.  Nothing is read at start-up, so start-up is not affected at all.

MY_PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False) else __file__))[0]

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the others: a music program
    lives in <root>\\1---Musik\\Py so its home is 1---Musik, and Chess /
    Foul_bridge / Quiz_manager / Railroad_racing are their own worlds - none
    of those has a WhyBrowse or a DefaultHub.  So after its own home it walks
    UP, exactly like _find_home, four levels."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - it is
    not an interpreter, and which() finds it first wherever the Store stub is
    on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


_HUB_PY_ROOTS = None


def _hub_py_roots() -> list:
    """The program folders DefaultHub names, or [] meaning "find them yourself".

    EMPTY IS THE DEFAULT AND IT IS THE RIGHT ONE.  An absolute path in a data
    file is the first thing to break when the tree moves to another drive -
    which it did on 2026-09-08, C: to X:.  Nothing else in this block holds a
    drive letter: _find_home walks up from __file__, and the table stores only
    NAMES ("SeeView"), so a move costs nothing.  A list of absolute paths here
    would be the one file that has to be edited every time, and that is exactly
    what this design is for avoiding.

    So a RELATIVE entry ("1---Musik\\Py") is the intended shape: it is
    resolved against every root in _py_folders, and it survives the move too.
    An absolute one is still honoured - it is his tree - but it is on him."""
    global _HUB_PY_ROOTS
    if _HUB_PY_ROOTS is not None:
        return _HUB_PY_ROOTS
    found = []
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    found = (json.load(fh) or {}).get("py_roots") or []
                break
        except Exception:
            pass                       # unreadable or half-written: automatic
    try:
        _HUB_PY_ROOTS = [str(x).strip() for x in found if str(x).strip()]
    except Exception:
        _HUB_PY_ROOTS = []
    return _HUB_PY_ROOTS


def _py_folders() -> list:
    """Every folder that may hold <Name>.py, nearest first.

    DefaultHub's list first, then the plain <root>\\Py that has always been
    searched.  With no list this is exactly the old behaviour, which is why
    "empty means automatic" costs nothing."""
    out, roots = [], _my_app_roots()
    for entry in _hub_py_roots():
        try:
            if os.path.isabs(entry):
                out.append(entry)
            else:
                for r in roots:
                    out.append(os.path.join(r, entry))
        except Exception:
            continue
    for r in roots:
        out.append(os.path.join(r, "Py"))
    seen, uniq = set(), []
    for d in out:
        try:
            key = os.path.normcase(os.path.abspath(d))
            if key not in seen and os.path.isdir(d):
                seen.add(key)
                uniq.append(d)
        except Exception:
            continue
    return uniq


def _program_candidates(name: str) -> list:
    """Every file that could BE that program, best first.

    ALL the .py folders are searched before ANY build.  The old loop asked
    "script or exe?" one tree at a time, so a stale build in a near tree beat
    the live source in a further one - the very thing "the .py wins" exists to
    prevent."""
    out = []
    for d in _py_folders():
        try:
            p = os.path.join(d, name + ".py")
            if os.path.isfile(p):
                out.append(p)
        except Exception:
            continue
    for root in _my_app_roots():
        try:
            e = os.path.join(root, "Folder-exe", name, name + ".exe")
            if os.path.isfile(e):
                out.append(e)
        except Exception:
            continue
    return out


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, and a build is only the fallback.  The .exe used to be
    preferred, which was wrong on every count:

      * it is not faster - a one-folder build and the .py start in about the
        same time (the ten-times difference was one-FILE builds);
      * it does not help the hand-over - both bind the same port, so a
        running copy takes the argument whichever one is started;
      * and it is the only thing that can be OUT OF DATE.  A build from last
        week does not have this week's source in it, so preferring it means
        quietly running old code.  That is exactly what happened on
        2026-09-05: File_manager's build was a day old and had no command
        line handling at all, so "open this folder" would have opened a
        second window and dropped the path.

    WHERE it looks is DefaultHub's business now, not this block's - see
    _py_folders - so his music programs and the own worlds under 1---Annat
    can be named as targets like anything else.

    subprocess and webbrowser MUST be imported at module level for this to
    work.  They were not, in 57 of 121 programs, and because every call site
    sits inside a bare `except Exception` the failure was completely silent:
    the program simply stopped handing files to his own programs and dropped
    them all on Windows.  That is what made "Save & Open" open nothing at all
    on 2026-09-09, and it left no trace anywhere."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    for path in _program_candidates(name):
        cmd = None
        if path.lower().endswith(".py"):
            pyw = _real_pythonw()
            if pyw:
                cmd = [pyw, path, str(argument)]
            # no interpreter on this machine: try the build instead
        else:
            cmd = [path, str(argument)]
        if not cmd:
            continue
        try:
            subprocess.Popen(cmd, cwd=os.path.dirname(path) or None)
            return True
        except Exception:
            continue                      # try the next candidate
    return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------


# AppUserModelID MUST be set BEFORE tk.Tk() for correct taskbar grouping
try:
    ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
        "LarsIssu.EQ_CheatSheet.1"
    )
except Exception:
    pass

# *************** DEL 02 - CONSTANTS & EQ DATA ********************************

# --- Color palette ---
C_BG        = "#1a1a2e"   # Main background
C_BG2       = "#16213e"   # Secondary background / panel
C_BG3       = "#0f3460"   # Header / accent background
C_CARD      = "#1e2a45"   # Instrument card background
C_CARD_SEL  = "#243558"   # Selected card highlight
C_FG        = "#e0e0e0"   # Primary text
C_FG_DIM    = "#a0a8c0"   # Dimmed / secondary text
C_ACCENT    = "#7eb8f7"   # Accent / links
C_SEP       = "#2a3a5a"   # Separator lines
C_BOOST     = "#3ddc97"   # Boost indicator (green)
C_CUT       = "#ff6b6b"   # Cut indicator (red)
C_CHAR      = "#7eb8f7"   # Character / depends-on-song (blue)
C_NEUTRAL   = "#a0a8c0"   # Neutral gray
C_CHECKBOX  = "#7eb8f7"   # Checkbox accent
C_BTN       = "#0f3460"   # Button background (change: grey/white/red/blue/green...)
C_BTN_FG    = "#e0e0e0"   # Button foreground
# Δ vs default (DEL 02p): a field that already matches the preset goes
# GREY, a field this song changes keeps its engine colour, and the Δ in the
# margin is what makes a changed section findable without reading it.
C_DEFAULT   = "#5a6379"   # "same as your preset — nothing to do"
C_DIFF      = "#ffd166"   # the Δ marker on a section that DID change

# The three buttons that act on the LINE-UP rather than on the list of
# variants. Normal colours written out, so one word changes any of them.
C_UPD_IDLE   = "#0f3460"  # ⟳ Update, nothing waiting   (dark blue)
C_UPD_WAIT   = "#b5701f"  # ⟳ Update, changes waiting   (amber)
C_RESET_BTN  = "#4a3a5a"  # ↩ Reset                     (muted purple)
C_GROUND_BTN = "#2f5a3a"  # ⚓ Ground                    (green)

# The song being worked on: lit in the song list and named in the title bar.
# Background is C_ACCENT; this is the text colour on it.
C_SONG_NOW_FG = "#0d1b2a"  # dark navy
SONG_NOW_CHARS = 34        # width of the title-bar name, in characters

FONT_TITLE   = ("Segoe UI", 11, "bold")
FONT_NORMAL  = ("Segoe UI", 9)
FONT_SMALL   = ("Segoe UI", 8)
FONT_MONO    = ("Consolas", 9)
FONT_HEADER  = ("Segoe UI", 10, "bold")

APP_NAME    = "EQ Cheat Sheet"
APP_VERSION = "3.41"
SETTINGS_FILE = None   # set in main after path resolution

# ---- EQ DATA ----------------------------------------------------------------
# Each instrument: id, group, name, sub, color_dot, bands[], tip
# band: {hz, note, type ("boost"/"cut"/"char"/"neutral"), db, label}
# type->color: boost=green, cut=red, char=blue, neutral=gray
# db: approximate dB suggestion (positive=boost, negative=cut)

EQ_DATA = [
    # ---- VOCALS ----
    {
        "id": "vocals_lead",
        "group": "Vocals",
        "name": "Lead Vocal",
        "sub": "Main vocal, centre of mix",
        "color": C_ACCENT,
        "bands": [
            {"hz": "< 80–120 Hz",  "note": "Rumble/proximity","type": "cut",    "db": -18, "filter": "High-pass",     "label": "Remove low rumble, mic handling noise, proximity buildup"},
            {"hz": "200–400 Hz",   "note": "Mud/boxiness",   "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Mud cut — sweep to find boxiness, cut 2–4 dB with Q 1–2"},
            {"hz": "1–2 kHz",      "note": "Body/honk",      "type": "char",    "db": -2,  "db_lo": -4, "db_hi": 0,  "filter": "Parametric EQ", "label": "Honky buildup around 1 kHz — cut if congested, leave if thin"},
            {"hz": "3–5 kHz",      "note": "Presence",       "type": "boost",   "db": +2,  "filter": "Parametric EQ", "label": "Intelligibility and forward energy — wide Q (+1–3 dB)"},
            {"hz": "6–8 kHz",      "note": "Sibilance",      "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "'S' and 'sh' harshness — use a de-esser or narrow cut here"},
            {"hz": "10–15 kHz",    "note": "Air/shimmer",    "type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "Open, expensive shimmer — keep subtle (+1–2 dB)"},
        ],
        "tip": "Lead vocal owns 3–5 kHz. Cut that range on guitars and synths to carve space. High-pass at 80–120 Hz on every vocal track, no exceptions."
    },
    {
        "id": "vocals_backing",
        "group": "Vocals",
        "name": "Backing Vocals",
        "sub": "Harmonies, doubles, choir",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 150–200 Hz", "note": "Rumble",         "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass more aggressively than lead — backing vocals have no low end"},
            {"hz": "200–500 Hz",   "note": "Mud",            "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Cut mud more aggressively than lead vocal — backing lives in the mids"},
            {"hz": "3–5 kHz",      "note": "Presence",       "type": "char",    "db": +1,  "db_lo": 0,  "db_hi": +2, "filter": "Parametric EQ", "label": "Less presence boost than lead — should sit behind, not compete"},
            {"hz": "8–12 kHz",     "note": "Air/blend",      "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "High-shelf air helps blend and glue backing layers together"},
        ],
        "tip": "Back vocals should support, not compete. Use more high-pass, more mud cut, less presence than the lead. Narrow the stereo field or hard-pan doubles for width (about 20 dB under the lead); harmonies stay ~10% off centre so they blend with the lead; parts of their own go out to the sides."
    },
    {
        "id": "vocals_choir_pad",
        "group": "Vocals",
        "name": "Sampled Choir / Vocal Pad",
        "sub": "Held sampled voices / 'aah'-'ooh' pad (organ-like)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 100–150 Hz", "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — a held vocal pad needs no true low end (bass/keys own it)"},
            {"hz": "200–400 Hz",   "note": "Warmth/lush",   "type": "char",    "db": +1,  "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "Body of the pad — small boost for lushness, cut if it clouds the mix"},
            {"hz": "400–800 Hz",   "note": "Mud/congestion","type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Many stacked voices pile up here — cut to keep the pad from masking everything"},
            {"hz": "3–5 kHz",      "note": "Lead-vocal zone","type": "cut",    "db": -3,  "filter": "Parametric EQ", "label": "Dip the lead-vocal presence range so the pad sits BEHIND a lead vocal"},
            {"hz": "8–12 kHz",     "note": "Air/sheen",     "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "High-shelf air for an open, angelic, blended sheen"},
        ],
        "tip": "It needs its OWN EQ — not the lead-vocal recipe. Treat it like an organ pad made of voices: tame 400–800 Hz mud and carve 3–5 kHz so it never fights the lead vocal, then add air. Sidechain it gently to the lead vocal if it still crowds."
    },
    {
        "id": "vocals_extra",
        "group": "Vocals",
        "name": "Extra Vocals",
        "sub": "Third vocal layer: ooh/aah, whispers, snores, trailing words",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 150–200 Hz", "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass higher than the lead and the word-singing backing - a held vowel or a whisper has no use for a low end"},
            {"hz": "250–500 Hz",   "note": "Mud",           "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Held vowels pile up here - cut so the layer stays a colour and not a body"},
            {"hz": "3–5 kHz",      "note": "Lead-vocal zone","type": "cut",    "db": -3,  "filter": "Parametric EQ", "label": "Dip the lead's presence range - this layer is never the words people follow"},
            {"hz": "6–9 kHz",      "note": "Breath/hiss",   "type": "char",    "db": 0,   "db_lo": -4, "db_hi": +3, "filter": "Parametric EQ", "label": "Breath, whisper and snore noise - boost a touch for an airy whisper, cut if it hisses against the hi-hat"},
            {"hz": "10–14 kHz",    "note": "Air/sheen",     "type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "Gentle air so the layer floats above the mix instead of sitting in it"},
        ],
        "tip": "Not the backing-vocal recipe: nothing here has to be understood, so it can be darker, airier and further back than the backing vocals. A trailing word ('so tired' ... 'sooo tiiired') is the one exception - keep its first consonant clear, and let the duck under the lead vocal bring it back up when the lead stops singing. Several layers: high-pass the stack, bus it, and put the air on the bus."
    },
    # ---- DRUMS ----
    {
        "id": "kick",
        "group": "Drums & Percussion",
        "name": "Kick Drum",
        "sub": "Bass drum",
        "color": C_CUT,
        "bands": [
            {"hz": "20–60 Hz",     "note": "Sub rumble",    "type": "cut",     "db": -6,  "filter": "High-pass",     "label": "Remove unnecessary sub-rumble"},
            {"hz": "60–80 Hz",     "note": "Body/punch",    "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Kick drum 'thud' — the main body"},
            {"hz": "100–200 Hz",   "note": "Boom",          "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Cut boominess and low-mid mud"},
            {"hz": "300–500 Hz",   "note": "Boxy tone",     "type": "cut",     "db": -5,  "filter": "Parametric EQ", "label": "Always check — 'cardboard box' sound"},
            {"hz": "2–5 kHz",      "note": "Beater attack", "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Beater click — cuts through mix"},
            {"hz": "6–10 kHz",     "note": "Air",           "type": "cut",     "db": -3,  "filter": "High-shelf",    "label": "Reduce unwanted high-frequency air"},
        ],
        "tip": "High-pass below 40 Hz. Sidechain-compress bass guitar against the kick. Cut 300–500 Hz to fix 'boxiness'."
    },
    {
        "id": "snare",
        "group": "Drums & Percussion",
        "name": "Snare",
        "sub": "Snare drum",
        "color": C_CUT,
        "bands": [
            {"hz": "100–200 Hz",   "note": "Body tone",     "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Snare body and warmth"},
            {"hz": "250–400 Hz",   "note": "Fat/mud",       "type": "cut",     "db": -5,  "filter": "Parametric EQ", "label": "Cut thick muddy mid — 'cardboard' tone"},
            {"hz": "1–3 kHz",      "note": "Crack",         "type": "boost",   "db": +5,  "filter": "Parametric EQ", "label": "Snap and crack — cuts through guitars"},
            {"hz": "5–8 kHz",      "note": "Snap",          "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Papery/wooden snap on the stick hit"},
            {"hz": "10+ kHz",      "note": "Sizzle/air",    "type": "char",    "db": +3,  "db_lo": -2, "db_hi": +4, "filter": "High-shelf",    "label": "Opens up air — boost or cut depending on track"},
        ],
        "tip": "200 Hz hump = 'cardboard box' — always cut there. Boost 3 kHz to cut through distorted guitars."
    },
    {
        "id": "hihat",
        "group": "Drums & Percussion",
        "name": "Hi-Hat",
        "sub": "Closed & open hi-hat",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 200 Hz",     "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass aggressively — hi-hat has no low end"},
            {"hz": "200–800 Hz",   "note": "Cymbal body",   "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Reduce boxy cymbal body mud"},
            {"hz": "3–6 kHz",      "note": "Stick attack",  "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The 'tick' of the stick on metal"},
            {"hz": "8–12 kHz",     "note": "Air/openness",  "type": "boost",   "db": +4,  "filter": "High-shelf",    "label": "Openness and airy shimmer"},
            {"hz": "16+ kHz",      "note": "Sizzle",        "type": "char",    "db": +2,  "db_lo": 0,  "db_hi": +3, "filter": "High-shelf",    "label": "Metallic sizzle — experiment with amount per track"},
        ],
        "tip": "High-pass at 200–400 Hz. Open hi-hat: boost a shelf at 10 kHz+. Be careful — too much air muddies the mix."
    },
    {
        "id": "ride",
        "group": "Drums & Percussion",
        "name": "Ride (hihat)",
        "sub": "Ride cymbal used as the timekeeper, instead of the hi-hat",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 250 Hz",     "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — a ride has no low end (like the hi-hat)"},
            {"hz": "200–700 Hz",   "note": "Cymbal body",   "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Reduce boxy cymbal body mud"},
            {"hz": "3–5 kHz",      "note": "Ping/stick",    "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The stick 'ping' that keeps time — the ride's version of the hi-hat tick. Keep it clear"},
            {"hz": "5–8 kHz",      "note": "Bell/shimmer",  "type": "char",    "db": -2,  "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "Bell ring & wash — boost for sparkle, cut if the sustain is harsh/smears"},
            {"hz": "8–12 kHz",     "note": "Wash/air",      "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "Air and openness — keep subtle so the long wash doesn't smear the top"},
        ],
        "tip": "Used INSTEAD of the hi-hat it is the timekeeper: keep the 3–5 kHz 'ping' clear and high-pass the lows. Tame the 5–8 kHz wash so the long sustain doesn't smear the top of the mix. If the ride is only an occasional wash/crash, use the Cymbals card instead."
    },
    {
        "id": "cymbals",
        "group": "Drums & Percussion",
        "name": "Cymbals",
        "sub": "Crash / ride / overheads",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 300 Hz",     "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass overheads to avoid kick/snare bleed"},
            {"hz": "1–3 kHz",      "note": "Harshness",     "type": "char",    "db": -3,  "db_lo": -4, "db_hi": 0,  "filter": "Parametric EQ", "label": "Can be harsh — cut 2–4 dB if fatiguing, leave if smooth"},
            {"hz": "5–8 kHz",      "note": "Shimmer",       "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Cymbal glitter and shimmer"},
            {"hz": "10–15 kHz",    "note": "Air",           "type": "boost",   "db": +4,  "filter": "High-shelf",    "label": "Openness and definition at the top"},
        ],
        "tip": "Overheads: high-pass at 300–600 Hz to avoid duplicating the kick/snare low end. Consider room ambience feel."
    },
    {
        "id": "toms",
        "group": "Drums & Percussion",
        "name": "Toms",
        "sub": "Floor tom / rack toms",
        "color": C_CHAR,
        "bands": [
            {"hz": "60–100 Hz",    "note": "Thud/body",     "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Fundamental tone — floor tom ≈80 Hz, hi-tom ≈200 Hz"},
            {"hz": "200–400 Hz",   "note": "Woodiness",     "type": "cut",     "db": -5,  "filter": "Parametric EQ", "label": "Cut the hollow 'wooden box' tone"},
            {"hz": "3–6 kHz",      "note": "Attack",        "type": "char",    "db": +3,  "db_lo": -2, "db_hi": +4, "filter": "Parametric EQ", "label": "Stick attack — boost for articulation, cut for vintage warmth"},
            {"hz": "8+ kHz",       "note": "Hiss/bleed",    "type": "cut",     "db": -6,  "filter": "High-shelf",    "label": "Cut down bleed when no tom hit is happening"},
        ],
        "tip": "Each tom has its own fundamental frequency — find and boost it. A gate is more important than EQ here."
    },
    {
        "id": "percussion",
        "group": "Drums & Percussion",
        "name": "Percussion extras",
        "sub": "Shaker, cowbell, tambourine, chimes — played from behind the kit",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 500 Hz",     "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "Aggressive high-pass — percussion has no low end"},
            {"hz": "2–5 kHz",      "note": "Attack/click",  "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Transient click and presence in the mix"},
            {"hz": "8–12 kHz",     "note": "Sparkle",       "type": "boost",   "db": +4,  "filter": "High-shelf",    "label": "Airy glitter and shimmer"},
        ],
        "tip": "High-pass at 500 Hz+. These are texture, not mass \u2014 keep them subtle and rhythmically precise. Shaker up at 8\u201312 kHz, tambourine 5\u201310 kHz, cowbell 1\u20133 kHz: give each one its own window."
    },
    {
        "id": "hand_drums",
        "group": "Drums & Percussion",
        "name": "Hand Drums",
        "sub": "Congas, bongos, djembe, taiko \u2014 a second player, standing off the kit",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 50 Hz",      "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass \u2014 stage rumble and handling noise, below anything a skin drum makes"},
            {"hz": "80\u2013200 Hz",    "note": "Body/tone",     "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The drum's own note \u2014 conga \u2248 200 Hz, djembe \u2248 120 Hz, taiko lower still. Find it before you boost it"},
            {"hz": "250\u2013500 Hz",   "note": "Box",           "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "The cardboard-box honk every hand drum has \u2014 cut it, do not EQ around it"},
            {"hz": "2\u20135 kHz",      "note": "Slap/palm",     "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "The slap, and the difference between an open tone and a muted one"},
            {"hz": "8\u201312 kHz",     "note": "Skin air",      "type": "char",    "db": +2,  "db_lo": 0,  "db_hi": +4, "filter": "High-shelf",    "label": "Air off the skin \u2014 lift it only if the drums sit behind the kit"},
        ],
        "tip": "Not the same thing as the shaker/tambourine channel: these have a real fundamental and a real player. Give them their own place on the stage, away from the kit, and keep them out of the snare's 200\u2013400 Hz."
    },
    # ---- BASS ----
    {
        "id": "bass_root",
        "group": "Bass",
        "name": "Root Bass",
        "sub": "Bass guitar / synth bass (foundational)",
        "color": C_BOOST,
        "bands": [
            {"hz": "30–50 Hz",     "note": "Sub bass",      "type": "char",    "db": 0,   "db_lo": -12,"db_hi": +3, "filter": "High-pass",     "label": "Sub content — keep for club/sub systems, high-pass for small speakers"},
            {"hz": "60–100 Hz",    "note": "Body",          "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Main body tone — the 'weight' of the bass"},
            {"hz": "200–400 Hz",   "note": "Mud zone",      "type": "cut",     "db": -5,  "filter": "Parametric EQ", "label": "Classic mud zone — always check this area"},
            {"hz": "700 Hz–1 kHz", "note": "Pick/attack",   "type": "char",    "db": +2,  "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Pick or finger attack — boost for definition, cut if too clicky"},
            {"hz": "2–4 kHz",      "note": "Grind/presence","type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Audibility on small speakers and radio"},
        ],
        "tip": "Kick and bass share 60–100 Hz — sidechain-compress bass against kick. High-pass below 30–40 Hz."
    },
    {
        "id": "bass_loop",
        "group": "Bass",
        "name": "Bass Loop / Riff",
        "sub": "Melodic / rhythmic secondary bass",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 60 Hz",      "note": "Sub",           "type": "cut",     "db": -12, "filter": "High-pass",     "label": "High-pass — leave sub frequencies to the root bass"},
            {"hz": "100–200 Hz",   "note": "Low-mid warmth","type": "char",    "db": +2,  "db_lo": -2, "db_hi": +3, "filter": "Parametric EQ", "label": "Warmth — boost for thickness, cut if competing with root bass"},
            {"hz": "500 Hz–1 kHz", "note": "Midrange",      "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Line clarity — the riff needs to be heard clearly"},
            {"hz": "2–5 kHz",      "note": "Definition",    "type": "boost",   "db": +5,  "filter": "Parametric EQ", "label": "Articulation, finger technique, note separation"},
            {"hz": "8+ kHz",       "note": "Air",           "type": "char",    "db": +1,  "db_lo": 0,  "db_hi": +2, "filter": "High-shelf",    "label": "Rarely needed — try a small boost only if the riff lacks sparkle"},
        ],
        "tip": "Bass riff should differ tonally from root bass. Boost the mids (1–3 kHz) more than root bass — think 'mid-thick'."
    },
    # ---- GUITAR ----
    # CHORD guitar sits ABOVE the rhythm guitar — his order, 2026-09-14. This
    # list is the only thing that decides where an instrument turns up: the
    # group tabs, the Song Variants list, the Selected Instruments panel and
    # the Channel Plan all walk EQ_DATA / GROUP_MAP in this order.
    {
        "id": "guitar_chords",
        "group": "Guitar",
        "name": "Chord Guitar",
        "sub": "Softer strumming, arpeggios",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 100 Hz",     "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — remove unnecessary low end"},
            {"hz": "150–300 Hz",   "note": "Warmth",        "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Warmth and body resonance"},
            {"hz": "500–800 Hz",   "note": "Body",          "type": "char",    "db": 0,   "db_lo": -4, "db_hi": 0,  "filter": "Parametric EQ", "label": "Body — cut 2–4 dB if muddy against other instruments, leave if clear"},
            {"hz": "2–5 kHz",      "note": "Presence",      "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Presence without harshness"},
            {"hz": "8–12 kHz",     "note": "Shimmer",       "type": "boost",   "db": +4,  "filter": "High-shelf",    "label": "Fullness and shimmer in the top end"},
        ],
        "tip": "More warmth, less attack compared to rhythm guitar. Find a tonal 'hole' in the mix that this guitar can fill."
    },
    {
        "id": "guitar_rhythm",
        "group": "Guitar",
        "name": "Rhythm Guitar",
        "sub": "Strumming, power chords",
        "color": C_CUT,
        "bands": [
            {"hz": "< 80 Hz",      "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "Aggressive high-pass — leave low end to bass"},
            {"hz": "100–250 Hz",   "note": "Boom",          "type": "cut",     "db": -5,  "filter": "Parametric EQ", "label": "Remove low-mid mud and boominess"},
            {"hz": "300–600 Hz",   "note": "Nasal/boxiness","type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "'Nasal' tone — cut if it sounds honky"},
            {"hz": "1–3 kHz",      "note": "Cut/presence",  "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Sharpness and presence in the mix"},
            {"hz": "4–8 kHz",      "note": "Pick/bite",     "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Pick attack and top-end bite"},
            {"hz": "10+ kHz",      "note": "Air",           "type": "char",    "db": +2,  "db_lo": -2, "db_hi": +3, "filter": "High-shelf",    "label": "Openness — boost for acoustic feel, cut for a tighter rock sound"},
        ],
        "tip": "Cut everything below 100 Hz hard. When doubling: pan L/R and use slightly different EQ on each side. 'Boxy' = cut 300–500 Hz."
    },
    {
        "id": "guitar_acoustic",
        "group": "Guitar",
        "name": "Acoustic Guitar",
        "sub": "Steel-string / nylon — strummed or picked",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 80–100 Hz",  "note": "Rumble",         "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — floor rumble, body thump and handling noise; the lowest string still sings above this"},
            {"hz": "100–250 Hz",   "note": "Body/boom",      "type": "char",    "db": -2,  "db_lo": -5, "db_hi": +2, "filter": "Parametric EQ", "label": "The big soundhole boom. CUT it when the song has a bass; a small boost only when the acoustic is the whole backing"},
            {"hz": "250–500 Hz",   "note": "Boxiness",       "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Cardboard/boxy zone — the single most useful cut on an acoustic; sweep and dip 3–5 dB"},
            {"hz": "800 Hz–1.5 kHz","note": "Honk",          "type": "char",    "db": -2,  "db_lo": -4, "db_hi": +1, "filter": "Parametric EQ", "label": "Nasal honk of a mic'd top — cut if it sounds like a telephone, leave it if the part must cut through"},
            {"hz": "2–5 kHz",      "note": "Pick/definition","type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Pick attack and note definition — this is where a strum is heard through a band"},
            {"hz": "5–8 kHz",      "note": "String/fret noise","type": "cut",   "db": -3,  "filter": "Parametric EQ", "label": "Squeaks, pick scrape and finger slides — a narrow dip here, not a shelf, or you kill the sparkle"},
            {"hz": "10–15 kHz",    "note": "Air/shimmer",    "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "Open, expensive sparkle — the sound people mean by 'a great acoustic'"},
        ],
        "tip": "The acoustic is a WIDE-BAND instrument: left alone it covers the bass, the guitars AND the vocal all at once. In a full band, treat it as texture — high-pass at 100 Hz, cut 250–500 Hz, dip 800 Hz–1.5 kHz, then add air. Solo or duo? Give the body back (100–250 Hz) because nothing else is holding the low end. Doubled acoustics: pan them apart and record the second one with a capo/different voicing — an identical double just gets louder, not wider."
    },
    {
        "id": "guitar_lead",
        "group": "Guitar",
        "name": "Lead Guitar",
        "sub": "Solo, single-note, bright",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 120 Hz",     "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — give space to bass and kick"},
            {"hz": "200–400 Hz",   "note": "Mud",           "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Cut muddiness and body buildUp"},
            {"hz": "1–2 kHz",      "note": "Presence",      "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "The solo's 'voice' — fundamental presence"},
            {"hz": "3–5 kHz",      "note": "Cut/definition","type": "boost",   "db": +5,  "filter": "Parametric EQ", "label": "Cuts through the full mix — critical for solos"},
            {"hz": "8–12 kHz",     "note": "Air/brilliance","type": "boost",   "db": +4,  "filter": "High-shelf",    "label": "Brilliance and gloss — makes solos soar"},
        ],
        "tip": "Lead guitar needs to own the centre of the mix. Use volume automation: +1–3 dB during solo sections. Consider an exciter above 5 kHz."
    },
    {
        "id": "guitar_single_low",
        "group": "Guitar",
        "name": "Single-String Lead (Low)",
        "sub": "One note at a time, mostly on the low strings",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 70–80 Hz",   "note": "Sub rumble",    "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — leave the deepest lows to bass/kick (low strings still carry plenty above this)"},
            {"hz": "90–140 Hz",    "note": "Note weight",   "type": "char",    "db": +1,  "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Body/weight of the low notes — boost for thickness, cut if it muddies against the bass"},
            {"hz": "200–400 Hz",   "note": "Mud",           "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Low-string single notes pile up here — cut to keep them defined, not woolly"},
            {"hz": "700 Hz–1.5 kHz","note": "Note core",    "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Fundamental/definition of each low note — this is where a low single-note line is actually heard"},
            {"hz": "2–4 kHz",      "note": "Pick/cut",      "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Pick attack and presence so the line cuts through without going bright/thin"},
            {"hz": "5–8 kHz",      "note": "Bite/fret noise","type": "char",   "db": -1,  "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "Edge and finger/fret noise — boost a touch for articulation, cut if harsh or noisy"},
        ],
        "tip": "This is NOT the bright high lead — a low single-note line lives in 700 Hz–4 kHz, not the 'air'. Boost the note core (around 1 kHz) and pick attack (2–4 kHz) to cut through; high-pass and cut 200–400 Hz so it doesn't collide with the bass. Skip the high-shelf air a bright lead would use."
    },
    # ---- KEYS & WINDS ----
    {
        "id": "organ",
        "group": "Keys & Winds",
        "name": "Organ (background)",
        "sub": "Hammond B3-style bed — held drawbar chords behind the band",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 80 Hz",      "note": "Sub",           "type": "cut",     "db": -12, "filter": "High-pass",     "label": "High-pass — bass handles the low end"},
            {"hz": "100–200 Hz",   "note": "Warmth",        "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Organ warmth and low-end fullness"},
            {"hz": "300–600 Hz",   "note": "Mid competition","type": "char",   "db": -2,  "db_lo": -4, "db_hi": 0,  "filter": "Parametric EQ", "label": "Competes with guitar — cut 2–3 dB if congested, leave if panned apart"},
            {"hz": "1–3 kHz",      "note": "Presence",      "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Leslie cabinet character and presence"},
            {"hz": "5–8 kHz",      "note": "Shimmer",       "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "Rotary speaker shimmer and gloss"},
        ],
        "tip": "Organ competes with guitar in 200–800 Hz — pan them differently. Rotary cabinet simulation helps more than EQ. This is the FILLER organ: held chords, wide, and happy to sit at the back. The moment the organ plays the tune instead, it is a different instrument with the opposite EQ — use Organ (lead)."
    },
    {
        "id": "organ_lead",
        "group": "Keys & Winds",
        "name": "Organ (lead)",
        "sub": "Melody line, riff or solo — the organ IS the tune",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 150 Hz",     "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass HARD — a melody line owes nothing to the low end, and the bass (and the background organ) already own it"},
            {"hz": "200–350 Hz",   "note": "Body",          "type": "boost",   "db": +2,  "filter": "Parametric EQ", "label": "Just enough body that the line is not thin — this is all the warmth a lead organ gets"},
            {"hz": "300–600 Hz",   "note": "Mud",           "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Cut HARDER than the background organ: this is the zone that stops a line from being heard as a line"},
            {"hz": "1–3 kHz",      "note": "Note core",     "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Where the melody actually lives — the one boost that makes the organ the lead instead of the bed"},
            {"hz": "2–5 kHz",      "note": "Key click / percussion", "type": "char", "db": +1, "db_lo": -2, "db_hi": +4, "filter": "Parametric EQ", "label": "B3 percussion and key click = the ATTACK of each note. Boost for articulation, cut if it clicks or if the vocal needs the room"},
            {"hz": "6–9 kHz",      "note": "Leslie shimmer","type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "Rotary gloss — LESS than the background organ gets: a lead wins in the mids, not in the air"},
        ],
        "tip": "A lead organ gets the opposite treatment to the bed. The background organ keeps its 100–200 Hz warmth and its width; the lead gives both away and buys 1–3 kHz with the difference. High-pass at 150 Hz (200–300 Hz when the background organ plays too), cut 300–600 Hz harder than feels comfortable, and push the note core. Keep it CENTRE-ish and fairly mono: width is what makes a bed, and a bed is exactly what you are trying not to sound like. Priority-wise it behaves like the saxophone — MID against a lead vocal, FRONT only in the bars where the organ really carries the tune."
    },
    {
        "id": "organ_melody",
        "group": "Keys & Winds",
        "name": "Organ (melody)",
        "sub": "A counter-line, harmony or riff on the organ — more than held chords, not the tune",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 120 Hz",     "note": "Low end",       "type": "cut",     "db": -15, "filter": "High-pass",     "label": "High-pass firmly — the bass and the Organ (background) own the low end, but less hard than a lead gets (that one goes to 150 Hz)"},
            {"hz": "150–300 Hz",   "note": "Body",          "type": "boost",   "db": +1,  "filter": "Parametric EQ", "label": "A little body so the line is not thin — about a third of what the bed gets (+3)"},
            {"hz": "300–600 Hz",   "note": "Mud",           "type": "cut",     "db": -3,  "db_lo": -4, "db_hi": -2, "filter": "Parametric EQ", "label": "Cut between the bed (-2) and the lead (-4): enough that a line reads as a line, not so much that the chords underneath lose their body"},
            {"hz": "1–3 kHz",      "note": "Note core",     "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Where a line is heard — +3, one dB LESS than the lead organ, so it stays a voice among voices and does not take over from the singer"},
            {"hz": "2–5 kHz",      "note": "Key click / percussion", "type": "char", "db": +1, "db_lo": -2, "db_hi": +3, "filter": "Parametric EQ", "label": "Articulation of each note. Boost for a riff, cut if it clicks or if the vocal needs the room"},
            {"hz": "6–9 kHz",      "note": "Leslie shimmer","type": "boost",   "db": +2,  "filter": "High-shelf",   "label": "Like the lead organ (+2) and a notch under the bed (+3): enough rotary air that it still belongs to the same organ"},
        ],
        "tip": "The in-between organ: it plays more than held chords (a counter-melody, a harmony, a riff) but it is one of several lines, not THE line. Use it when the organ would otherwise be filed as Background (and get buried) or as Lead (and get pushed in front of the vocal). EQ is halfway between the two cards: some bed warmth, a firmer mud cut, a note core one dB under the lead. Keep it a step off centre, on the SAME side as the Organ (background) if you have both. For a part that is equal in importance to the vocal, set its Role to Co-lead or Feature in the Stage window; for one that comes and goes, leave Auto."
    },
    {
        "id": "accordion",
        "group": "Keys & Winds",
        "name": "Accordion",
        "sub": "Piano/chromatic accordion — folk, musette, bandoneón",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 60–80 Hz",   "note": "Bellows rumble",  "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — bellows thump, floor rumble and body noise; the left-hand reeds still sing above this"},
            {"hz": "100–250 Hz",   "note": "Left-hand body",  "type": "char",    "db": +1,  "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "Bass/chord-side weight — small boost when it plays alone, CUT it when a real bass is in the song"},
            {"hz": "300–600 Hz",   "note": "Box/mud",         "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "The 'squeezebox in a box' zone — cut so it doesn't cloud guitars, organ and piano"},
            {"hz": "800 Hz–2 kHz", "note": "Reedy honk",      "type": "char",    "db": -2,  "db_lo": -5, "db_hi": +2, "filter": "Parametric EQ", "label": "The nasal reed core — cut 3–5 dB when it fights a vocal, leave (or lift) when the accordion IS the lead"},
            {"hz": "2–4 kHz",      "note": "Presence/bite",   "type": "boost",   "db": +2,  "filter": "Parametric EQ", "label": "Where the reeds cut through — keep it small under a vocal, push it when the accordion carries the tune"},
            {"hz": "5–8 kHz",      "note": "Reed buzz",       "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Raspy reed buzz and key/valve clatter — tame it here rather than with a high-shelf"},
            {"hz": "10+ kHz",      "note": "Air/bellows noise","type": "char",   "db": +1,  "db_lo": -3, "db_hi": +2, "filter": "High-shelf",    "label": "A little air opens it up — but it also lifts the bellows/mechanical hiss, so go gently"},
        ],
        "tip": "An accordion is a MID-RANGE machine: its whole voice sits 300 Hz–4 kHz — exactly where the vocal, the guitars and the organ live. Decide who owns the mids and carve the rest. Musette/tremolo tuning beats two reeds against each other around 1–4 kHz: that shimmer is the character, but it eats presence, so pan the accordion off-centre instead of EQ-ing the life out of it. If the song already has a bass, high-pass the accordion harder (or stop playing the left-hand bass reeds) — the bass side doubles the bass part and mud is the result. This card is the PADDING role. When the accordion carries the tune, use Accordion (lead) — it lifts the same 800 Hz–2 kHz reed core this card cuts."
    },
    {
        "id": "accordion_lead",
        "group": "Keys & Winds",
        "name": "Accordion (lead)",
        "sub": "The accordion carries the tune — melody, riff or solo",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 100–120 Hz", "note": "Bass side",     "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass hard — better still, stop playing the left-hand bass reeds: a melody line must not double the bass part"},
            {"hz": "150–300 Hz",   "note": "Body",          "type": "char",    "db": -1,  "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "Only as much body as the line needs — the first thing to give away when the padding accordion or the organ plays too"},
            {"hz": "300–600 Hz",   "note": "Box",           "type": "cut",     "db": -5,  "filter": "Parametric EQ", "label": "Cut the box HARDER than the padding card does: this is what stops a reed line from being heard as a tune"},
            {"hz": "800 Hz–2 kHz", "note": "Reed core",     "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The nasal reed core — and on a LEAD you LIFT it. The padding card cuts this very band, because there it is fighting the vocal"},
            {"hz": "2–4 kHz",      "note": "Melody bite",   "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Where the reeds cut through and the line reads as a melody. This is the boost that matters"},
            {"hz": "5–8 kHz",      "note": "Reed buzz",     "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Raspy buzz and key/valve clatter — a held lead exposes it far more than a chord wash ever does"},
            {"hz": "10+ kHz",      "note": "Air",           "type": "char",    "db": 0,   "db_lo": -2, "db_hi": +2, "filter": "High-shelf",    "label": "Less air than the padding gets: a lead wins in the mids, and up here it only lifts the bellows noise"},
        ],
        "tip": "The accordion is the one instrument in this chart that sounds like a second singer, and as a lead that is exactly the problem: it lands on the voice in 800 Hz–4 kHz. Lift the reed core and the 2–4 kHz bite, cut the 300–600 Hz box harder than feels right, and duck it under the vocal — then treat the level like a vocal too, because the bellows swing is enormous. If the padding accordion also plays, they are ONE pair of hands: the two cards must not both play the bass side."
    },
    {
        "id": "piano_bg",
        "group": "Keys & Winds",
        "name": "Piano (background)",
        "sub": "Rhythmic comping / chords behind the mix",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 50–80 Hz",   "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — pedal/floor rumble; low notes still carry above this"},
            {"hz": "100–250 Hz",   "note": "Body/warmth",   "type": "char",    "db": +1,  "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "Warmth — small boost for fullness, cut if it muddies with the bass"},
            {"hz": "300–500 Hz",   "note": "Mud/boxiness",  "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Classic mud zone — cut so a chordy comp doesn't cloud the mix"},
            {"hz": "1–2 kHz",      "note": "Clarity",       "type": "char",    "db": 0,   "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "Note clarity — leave flat or dip if it competes with vocals/guitars"},
            {"hz": "2–5 kHz",      "note": "Presence",      "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "As a background comp, dip presence so it sits UNDER vocals and guitars"},
            {"hz": "8–12 kHz",     "note": "Air/sparkle",   "type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "Gentle air for a little sparkle without coming forward"},
        ],
        "tip": "A background/rhythm piano should support, not lead: high-pass it, cut 300–500 Hz mud, and DIP 2–5 kHz so it sits behind the vocal and guitars. Add only gentle air. Pan it opposite the guitars/organ to avoid low-mid clutter."
    },
    {
        "id": "piano_riff",
        "group": "Keys & Winds",
        "name": "Piano Riff / Loop",
        "sub": "Melodic single-line / hook piano",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 80–100 Hz",  "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — leave the lows to bass/background piano"},
            {"hz": "150–300 Hz",   "note": "Warmth/body",   "type": "boost",   "db": +2,  "filter": "Parametric EQ", "label": "Body so the line has weight without being thin"},
            {"hz": "300–500 Hz",   "note": "Mud",           "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Cut mud so the riff stays defined"},
            {"hz": "1–3 kHz",      "note": "Definition",    "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Note definition/presence — this is where the riff is actually heard"},
            {"hz": "3–6 kHz",      "note": "Hammer/attack", "type": "char",    "db": +2,  "db_lo": -2, "db_hi": +3, "filter": "Parametric EQ", "label": "Hammer attack/articulation — boost for clarity, cut if clanky"},
            {"hz": "8–12 kHz",     "note": "Air/shimmer",   "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "Air and shimmer to let the hook sparkle"},
        ],
        "tip": "Opposite recipe to the background piano: a riff/hook should come FORWARD — boost 1–3 kHz definition and the hammer attack, and keep some air. Still high-pass and cut 300–500 Hz so it doesn't fight the bass and background piano."
    },
    {
        "id": "flute",
        "group": "Keys & Winds",
        "name": "Flute",
        "sub": "Transverse flute / solo",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 200 Hz",     "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "Aggressive high-pass — flute has no low content"},
            {"hz": "200–600 Hz",   "note": "Breath body",   "type": "char",    "db": +1,  "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "Breath tone — small boost for warmth, cut if too boxy"},
            {"hz": "800 Hz–2 kHz", "note": "Core tone",     "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Flute's main body and tonal character"},
            {"hz": "4–8 kHz",      "note": "Breath/air",    "type": "boost",   "db": +5,  "filter": "Parametric EQ", "label": "Airy breathiness and expressiveness"},
            {"hz": "10+ kHz",      "note": "Air/openness",  "type": "boost",   "db": +4,  "filter": "High-shelf",    "label": "Openness and shimmer at the top"},
        ],
        "tip": "High-pass at 200–300 Hz. Flute lives in 2–8 kHz. Be careful with compression — it kills the natural dynamics. This card is the SOLO role — it is built on 4–8 kHz breath and 10 kHz+ air. Holding long notes behind the song instead? Use Flute (background): held, that same breath is hiss."
    },
    {
        "id": "flute_bg",
        "group": "Keys & Winds",
        "name": "Flute (background)",
        "sub": "Held / sustained flute behind the song — the filler role",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 180–200 Hz", "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — a shade LOWER than the solo card: the bed is the half that gets to keep the body"},
            {"hz": "200–600 Hz",   "note": "Breath body",   "type": "char",    "db": +1,  "db_lo": -1, "db_hi": +3, "filter": "Parametric EQ", "label": "The warmth the solo flute gives away — a held bed is allowed it, and needs it, or the line is all hiss"},
            {"hz": "800 Hz–2 kHz", "note": "Core tone",     "type": "boost",   "db": +2,  "filter": "Parametric EQ", "label": "Core tone — HALF of what the solo card takes, so the bed never starts sounding like the tune"},
            {"hz": "3–5 kHz",      "note": "Lead-vocal zone","type": "cut",    "db": -4,  "filter": "Parametric EQ", "label": "Dip the singer's presence range. This band is the whole difference between a bed and a solo"},
            {"hz": "5–8 kHz",      "note": "Breath region", "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Breathiness is expression on a two-bar solo phrase and noise on a four-bar held note — the solo card BOOSTS this +5; take it back out across the WHOLE region, not as a notch"},
            {"hz": "10+ kHz",      "note": "Sheen",         "type": "char",    "db": +1,  "db_lo": -1, "db_hi": +3, "filter": "High-shelf",    "label": "A little sheen keeps it open without pulling it forward — a third of what the solo gets"},
        ],
        "tip": "A held flute is a PAD that happens to be played by a person, and the solo recipe is actively wrong for it: breath and air are expression on a two-bar phrase and hiss on a four-bar chord. Keep the body, halve the core, cut 3–5 kHz for the singer, and take the 4–8 kHz breath out entirely. Unlike the solo flute this one DOES want a gentle leveller (it has to sit still) and it DOES want ducking under the vocal. If it starts competing anyway, the honest fix is to automate it down, not to EQ it further."
    },
    {
        "id": "brass",
        "group": "Brass",
        "name": "Brass (generic)",
        "sub": "Fallback card — use Trumpet / Trombone / Horn Section when you know which",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 100 Hz",     "note": "Sub",           "type": "cut",     "db": -12, "filter": "High-pass",     "label": "High-pass — brass has no useful sub content"},
            {"hz": "200–400 Hz",   "note": "Body",          "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Instrument body tone and fullness"},
            {"hz": "500 Hz–1 kHz", "note": "Honk/blare",    "type": "char",    "db": -3,  "db_lo": -4, "db_hi": 0,  "filter": "Parametric EQ", "label": "'Blaring' honky tone — cut 2–4 dB if too aggressive, keep for authenticity"},
            {"hz": "2–5 kHz",      "note": "Presence",      "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Brass presence and forward projection"},
            {"hz": "8+ kHz",       "note": "Air",           "type": "char",    "db": +2,  "db_lo": 0,  "db_hi": +3, "filter": "High-shelf",    "label": "Air and openness — boost for a modern bright sound, skip for vintage"},
        ],
        "tip": "Generic fallback for 'some horns'. Brass section: a little room reverb adds naturalness, and the section belongs on ONE bus. NOTE: a saxophone is NOT brass — it is a reed instrument with a different tonal map. Use the Saxophone card for it. This card is the FILLER role — stabs, pads and answers. When the horns play the tune instead, use Brass (lead)."
    },
    {
        "id": "brass_lead",
        "group": "Brass",
        "name": "Brass (lead)",
        "sub": "The horns carry the tune — a unison/harmony melody line, not stabs",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 120 Hz",     "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass harder than the stab card — a melody line owes nothing below the trombone's floor"},
            {"hz": "200–400 Hz",   "note": "Body",          "type": "boost",   "db": +2,  "filter": "Parametric EQ", "label": "Enough body that the line is not thin — HALF what the stabs get, because a tune has to stay clear of the guitars and the organ"},
            {"hz": "500 Hz–1 kHz", "note": "Honk/blare",    "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Cut it harder than on stabs: the honk is what stops a horn line from being heard as a tune"},
            {"hz": "1.5–3 kHz",    "note": "Melody core",   "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Where the line reads as a melody — its voice through the arrangement. This is the boost that matters"},
            {"hz": "3–6 kHz",      "note": "Blare/edge",    "type": "char",    "db": -2,  "db_lo": -6, "db_hi": +2, "filter": "Parametric EQ", "label": "The brassy BLARE. A held melody spikes here where a short stab never does — cut 3–6 dB under a vocal, boost only for a deliberate mariachi/ska bite"},
            {"hz": "8–12 kHz",     "note": "Air",           "type": "char",    "db": 0,   "db_lo": -2, "db_hi": +2, "filter": "High-shelf",    "label": "A touch of air for a modern sound, none at all for vintage — a lead wins in the mids, not on the top"},
        ],
        "tip": "A horn line carrying the tune is the loudest melodic thing you can put in a mix, and it sits in exactly the 1–5 kHz window a singer needs. Give it the 1.5–3 kHz core, take the 200–400 Hz body and the 3–6 kHz blare away, and remember that this is a LEVEL problem before it is an EQ problem: a played section swings 20 dB between a held note and a stab, so tame the peaks and ride the fader for the musical shape. Against a lead vocal it yields (MID); FRONT only in the bars where the horns really are the song."
    },
    {
        "id": "trumpet",
        "group": "Brass",
        "name": "Trumpet",
        "sub": "Solo trumpet / flugelhorn / cornet (lead line or stab)",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 150–180 Hz", "note": "Rumble",          "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass hard — a Bb trumpet's lowest useful note is around 165 Hz, so everything below is room and breath rumble"},
            {"hz": "200–400 Hz",   "note": "Body/warmth",     "type": "char",    "db": +1,  "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Body — boost for a fat, close, flugelhorn-ish tone; cut it when the trumpet sits in a full band"},
            {"hz": "800 Hz–1.2 kHz","note": "Nasal core",     "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "The pinched, nasal part of the tone — a narrow dip here is what makes a sampled trumpet stop sounding fake"},
            {"hz": "1.5–3 kHz",    "note": "Presence",        "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Where the line reads as a melody — its 'voice' through the arrangement"},
            {"hz": "3–6 kHz",      "note": "Blare/edge",      "type": "char",    "db": -3,  "db_lo": -6, "db_hi": +2, "filter": "Parametric EQ", "label": "The brassy BLARE. Loud playing spikes here — cut 3–6 dB to tame it, boost only for a deliberate mariachi/ska bite"},
            {"hz": "8–12 kHz",     "note": "Air",             "type": "char",    "db": +1,  "db_lo": -2, "db_hi": +2, "filter": "High-shelf",    "label": "A touch of air for a modern sound; skip it for a vintage/close-mic'd tone"},
        ],
        "tip": "The trumpet is the LOUDEST thing you can put over a vocal — it lives in exactly the 1–5 kHz slot the voice needs. When both play, the trumpet must yield: dip 3–5 kHz, duck it under the lead vocal, and pan it well off-centre. The one cut that fixes 'harsh/fatiguing horns' is 3–6 kHz, and a compressor matters more than EQ here because a played trumpet swings 20 dB between a held note and a stab."
    },
    {
        "id": "trombone",
        "group": "Brass",
        "name": "Trombone",
        "sub": "Tenor trombone — section pad or bass-line horn",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 70–80 Hz",   "note": "Rumble",          "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — the tenor trombone goes down to about 82 Hz, so cut just under that, not higher"},
            {"hz": "100–250 Hz",   "note": "Weight/body",     "type": "char",    "db": +2,  "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The trombone's whole point is weight — boost when it carries the low horn line, CUT it when a bass guitar is already there"},
            {"hz": "300–600 Hz",   "note": "Mud/box",         "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Where a bone turns woolly and clouds the guitars — the standard cut"},
            {"hz": "1–2 kHz",      "note": "Definition",      "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Slide articulation — the notes stop being a 'brown blur' and become a line"},
            {"hz": "3–5 kHz",      "note": "Rasp/bite",       "type": "char",    "db": -2,  "db_lo": -5, "db_hi": +3, "filter": "Parametric EQ", "label": "Brassy rasp — push for an aggressive ska/funk bone, cut when it fights the vocal"},
            {"hz": "8+ kHz",       "note": "Air",             "type": "cut",     "db": -2,  "filter": "High-shelf",    "label": "Little useful content up here — a small shelf cut removes hiss and mic air without dulling the tone"},
        ],
        "tip": "The trombone is the horn that fights the BASS, not the vocal — it sits 100–600 Hz right on top of the bass guitar and the low guitars. Decide who owns 100–250 Hz: if the bass does, high-pass the bone higher (120 Hz) and let it live 300 Hz–2 kHz instead. In a horn section it is the foundation, so keep it a touch darker than the trumpet and let the trumpet take the top."
    },
    {
        "id": "saxophone",
        "group": "Keys & Winds",
        "name": "Saxophone",
        "sub": "Alto / tenor / baritone — a REED, not brass",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 100 Hz",     "note": "Rumble/key noise","type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — mic rumble and key-pad thumps. Baritone sax? Move it down to ~60 Hz, it really does go that low"},
            {"hz": "150–350 Hz",   "note": "Body/honk",       "type": "char",    "db": +1,  "db_lo": -4, "db_hi": +3, "filter": "Parametric EQ", "label": "Tenor/bari body. Boost for a big warm subtone; cut it when the sax crowds the bass and low guitars"},
            {"hz": "400–800 Hz",   "note": "Woody box",       "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Where a sax gets boxy/wooden and muddies the mids — a wide 3 dB dip usually does it"},
            {"hz": "1–2 kHz",      "note": "Reed core",       "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The reed's actual voice — the range that makes it recognisable as a sax rather than a synth pad"},
            {"hz": "3–5 kHz",      "note": "Bite/growl",      "type": "char",    "db": +2,  "db_lo": -4, "db_hi": +4, "filter": "Parametric EQ", "label": "The growl that cuts through a band. Push it when the sax takes a solo, cut it hard when it plays under a vocal"},
            {"hz": "6–9 kHz",      "note": "Breath/squawk",   "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Air noise, reed squawk and mouthpiece hiss — narrow dip, not a shelf, or the instrument goes dead"},
            {"hz": "10+ kHz",      "note": "Air",             "type": "char",    "db": +1,  "db_lo": -2, "db_hi": +2, "filter": "High-shelf",    "label": "Small lift for a modern polished sax; leave flat for a smoky, close, vintage tone"},
        ],
        "tip": "A saxophone is a reed instrument and behaves like a VOCAL, not like a trumpet: same 1–5 kHz territory, same dynamic swings, same need for compression. That means it is the single most dangerous instrument to put behind a singer — pick one to own 3–5 kHz at a time and duck the sax under the vocal. Baritone: treat the low end like a bass part and decide who owns 100–250 Hz. Alto: it sits higher and thinner, so it fights the vocal even harder — pan it away and let it answer the phrases rather than play under them."
    },
    {
        "id": "horn_section",
        "group": "Brass",
        "name": "Horn Section",
        "sub": "Trumpet + sax + trombone together (stabs, pads, sampled section)",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 80–100 Hz",  "note": "Rumble",          "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass the whole section together — nothing useful below the trombone's floor"},
            {"hz": "200–400 Hz",   "note": "Section body",    "type": "char",    "db": 0,   "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "Three horns stack here and it adds up fast — cut when the mix is full, boost only for a fat exposed section"},
            {"hz": "500 Hz–1 kHz", "note": "Blare/pile-up",   "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Where a section turns into one honking block — this cut is what makes horns sound arranged instead of loud"},
            {"hz": "2–4 kHz",      "note": "Section presence","type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The punch of a stab; keep it under the vocal's 3–5 kHz if a singer is present"},
            {"hz": "5–7 kHz",      "note": "Harshness",       "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Combined brass edge — this is the band that makes a horn section fatiguing at volume"},
            {"hz": "10+ kHz",      "note": "Air",             "type": "char",    "db": +1,  "db_lo": -2, "db_hi": +2, "filter": "High-shelf",    "label": "Gentle air ties the section together; too much and the mouthpiece noise comes with it"},
        ],
        "tip": "Mix a horn section as ONE instrument, not three: put them on a bus, glue-compress the bus (2:1, 1–3 dB) and do the tonal work THERE. Per-horn EQ is only for fixing one bad note or one bad mic. If you also have the individual Trumpet / Sax / Trombone channels ticked, then this card is your BUS — do the section cuts here and keep the channel EQs minimal, or you will cut 500 Hz–1 kHz twice."
    },
    {
        "id": "harmonica",
        "group": "Keys & Winds",
        "name": "Harmonica",
        "sub": "Diatonic blues harp / chromatic — clean or amped",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 150–200 Hz", "note": "Rumble/pop",      "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass hard — hand cupping and breath pops make a lot of useless low noise"},
            {"hz": "200–500 Hz",   "note": "Body/warmth",     "type": "char",    "db": +1,  "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Body of a cupped harp. Boost for a fat Chicago tone through an amp; cut for a clean acoustic folk sound"},
            {"hz": "800 Hz–2 kHz", "note": "Reed core",       "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Where the melody actually lives — the harmonica's recognisable voice"},
            {"hz": "2–4 kHz",      "note": "Cut/wail",        "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The wail that carries over a band; this is also exactly the vocal's slot, so choose one at a time"},
            {"hz": "4–7 kHz",      "note": "Shrill/harsh",    "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "A harmonica gets painful here faster than any other instrument — cut 3–5 dB and it stops being fatiguing"},
            {"hz": "10+ kHz",      "note": "Air",             "type": "cut",     "db": -3,  "filter": "High-shelf",    "label": "Almost nothing musical up here, plenty of breath hiss — shelve it down"},
        ],
        "tip": "A harmonica is a small, LOUD, midrange instrument that lands on the same spot as the singer — which is why the classic arrangement has the harp answering between vocal lines, not underneath them. Cut 4–7 kHz to fix harshness, duck it under the vocal, and pan it off-centre. Amped harp is already distorted, so compress lightly and let the amp do the sustain."
    },
    {
        "id": "woodwind",
        "group": "Keys & Winds",
        "name": "Woodwinds",
        "sub": "Clarinet, oboe, bassoon",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 150 Hz",     "note": "Low end",       "type": "cut",     "db": -12, "filter": "High-pass",     "label": "High-pass — varies by instrument range"},
            {"hz": "300–600 Hz",   "note": "Warmth",        "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Wooden reed body warmth and resonance"},
            {"hz": "1–3 kHz",      "note": "Reed/definition","type": "boost",  "db": +4,  "filter": "Parametric EQ", "label": "Reed articulation and note definition"},
            {"hz": "5–8 kHz",      "note": "Breath/presence","type": "boost",  "db": +3,  "filter": "Parametric EQ", "label": "Breathiness and forward presence"},
        ],
        "tip": "Woodwinds live in 300 Hz–4 kHz. Avoid cutting too hard — they need their warmth to avoid sounding plasticky."
    },
    {
        "id": "clarinet",
        "group": "Keys & Winds",
        "name": "Clarinet",
        "sub": "Bb / A clarinet — solo or section (SWAM Clarinet)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 120–140 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — a Bb clarinet's lowest note is about 147 Hz (written E), so everything below is key thump and room"},
            {"hz": "200–400 Hz", "note": "Chalumeau body", "type": "char", "db": +1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The dark, hollow low register — boost for a woody close tone, cut when it clouds the guitars"},
            {"hz": "500–900 Hz", "note": "Hollow/boxy", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "A clarinet is built from odd harmonics, which is why it sounds hollow; a wide dip here stops it sounding like a tube in a box"},
            {"hz": "1–3 kHz", "note": "Reed/definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Where the line reads as a clarinet and not a synth pad — note definition and articulation"},
            {"hz": "3–5 kHz", "note": "Edge/squeak", "type": "char", "db": -2, "db_lo": -5, "db_hi": +2, "filter": "Parametric EQ", "label": "Reed edge in the upper (clarion) register — cut for a soft classical tone, leave for a clarinet that has to cut through"},
            {"hz": "6–10 kHz", "note": "Breath/key noise", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Breath, key clicks and reed hiss — a narrow dip, not a shelf, or the tone goes dead"},
            {"hz": "10+ kHz", "note": "Air", "type": "char", "db": +1, "db_lo": -2, "db_hi": +2, "filter": "High-shelf", "label": "A small lift for a modern, open sound; leave flat for a warm vintage one"},
        ],
        "tip": "A clarinet has two voices: the dark chalumeau register below about 500 Hz and the bright clarion register above it, and one EQ curve rarely suits both. Keep the warmth, dip the hollow 500–900 Hz and give the note definition at 1–3 kHz. It sits in the same slot as a vocal's lower half, so it yields to the singer and answers between the lines."
    },
    {
        "id": "oboe",
        "group": "Keys & Winds",
        "name": "Oboe",
        "sub": "Oboe / English horn — solo double reed (SWAM Oboe)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 200 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — the lowest oboe note is about 233 Hz, so everything below is room and key noise (English horn: move it down to ~150 Hz)"},
            {"hz": "250–500 Hz", "note": "Body", "type": "char", "db": +1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Small amount of body; an oboe has very little low end to lose"},
            {"hz": "1–1.5 kHz", "note": "Nasal honk", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "The pinched, nasal core of the reed — a narrow dip makes a close-mic'd or sampled oboe sound less like a duck call"},
            {"hz": "2–4 kHz", "note": "Reed presence", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The oboe's voice: strong overtones here carry it through a whole orchestra. Boost for a lead, cut under a vocal"},
            {"hz": "4–7 kHz", "note": "Edge/rasp", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Reed buzz and rasp that gets fatiguing fast — the standard cut"},
            {"hz": "8+ kHz", "note": "Air/breath", "type": "char", "db": +1, "db_lo": -3, "db_hi": +2, "filter": "High-shelf", "label": "A touch of air is fine; there is little music up here, mostly breath and key noise"},
        ],
        "tip": "An oboe cuts through because most of its energy is concentrated at 1–4 kHz — the same slot as a lead vocal, and it is the one woodwind that wins that fight. So treat it as a LEAD voice: one at a time with the singer, duck it under the vocal, and tame the 1–1.5 kHz nasal core and the 4–7 kHz rasp before you reach for a compressor."
    },
    {
        "id": "bassoon",
        "group": "Keys & Winds",
        "name": "Bassoon",
        "sub": "Bassoon — solo or section (SWAM Bassoon)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 50 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — the lowest bassoon note is about 58 Hz, so cut just under it and leave the body alone"},
            {"hz": "80–200 Hz", "note": "Weight", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The bassoon's warm foundation — boost when it plays the bass line, cut when a bass guitar or cello already owns it"},
            {"hz": "250–500 Hz", "note": "Mud/box", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Where a bassoon gets woolly and boxy — the standard cut"},
            {"hz": "500–800 Hz", "note": "Formant core", "type": "char", "db": +0, "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "The reedy, vowel-like formant that makes it a bassoon — leave it flat, trim 2–3 dB if it honks"},
            {"hz": "1–2.5 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Articulation: without this the notes smear into a brown blur, especially staccato"},
            {"hz": "3–6 kHz", "note": "Rasp/key clack", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Reed buzz and key noise — cut for a smooth classical tone"},
            {"hz": "8+ kHz", "note": "Air", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Almost no music up here; a shelf removes hiss without dulling the tone"},
        ],
        "tip": "A bassoon is a tenor/bass voice with a reed's edge: weight at 80–200 Hz, a woody formant around 500 Hz, and definition at 1–2.5 kHz. It lives where the cello, trombone and bass guitar live, so decide who owns 100–250 Hz and high-pass the others. Keep the low end centred."
    },
    {
        "id": "contrabassoon",
        "group": "Keys & Winds",
        "name": "Contrabassoon",
        "sub": "Contrabassoon — the lowest woodwind (SWAM Contrabassoon)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 25–30 Hz", "note": "Sub rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — the lowest note is about 29 Hz (written Bb0); anything under 25 Hz is rumble"},
            {"hz": "35–80 Hz", "note": "Fundamental", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The weight of the instrument. Boost for a dark, floor-shaking bed; cut when a bass or kick owns this range"},
            {"hz": "100–250 Hz", "note": "Mud/boom", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Boom and woolliness — cut it first when the mix sounds thick"},
            {"hz": "300–700 Hz", "note": "Buzz/reed", "type": "char", "db": +0, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The reed's buzzy growl; this is what you hear on small speakers"},
            {"hz": "1–2 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Articulation. A contrabassoon is mostly rumble, so this band is what lets the notes be heard as notes"},
            {"hz": "4+ kHz", "note": "Noise", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Hardly any musical content up here — shelve reed noise and key clicks away"},
        ],
        "tip": "Treat the contrabassoon like a bass instrument that happens to have a reed: high-pass at 25–30 Hz, keep everything below 150 Hz mono and centred, give the notes definition at 1–2 kHz (otherwise a phone speaker plays nothing), and decide who owns 40–100 Hz with the bass guitar, double bass and kick. It is rarely a solo — mostly a colour under the cellos."
    },
    {
        "id": "flugelhorn",
        "group": "Brass",
        "name": "Flugelhorn",
        "sub": "Flugelhorn — the mellow cousin of the trumpet (SWAM Flugelhorn)",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 150 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — a Bb flugelhorn goes down to about 165 Hz, so everything below is room and breath"},
            {"hz": "200–400 Hz", "note": "Warmth", "type": "char", "db": +2, "db_lo": -2, "db_hi": +4, "filter": "Parametric EQ", "label": "The dark, round body of a conical bore — boost for a fat, close, smoky tone; cut when it sits in a full band"},
            {"hz": "600–900 Hz", "note": "Boxy/honk", "type": "cut", "db": -2, "filter": "Parametric EQ", "label": "A small dip stops the flugelhorn sounding stuffed and nasal"},
            {"hz": "1–2.5 kHz", "note": "Presence", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Where the line is heard as a melody. A flugelhorn has less of it than a trumpet, so it often needs a little help"},
            {"hz": "3–5 kHz", "note": "Edge", "type": "char", "db": +0, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "A flugelhorn has far less blare than a trumpet — leave flat, or lift 1–2 dB for more bite; never cut hard"},
            {"hz": "8–12 kHz", "note": "Air", "type": "char", "db": +1, "db_lo": -2, "db_hi": +2, "filter": "High-shelf", "label": "Gentle air to stop it sounding muffled; skip it for a close, vintage tone"},
        ],
        "tip": "A flugelhorn is a trumpet with the sharp edges sanded off: a conical bore gives it the dark warmth and takes away most of the 3–6 kHz blare. So do the opposite of the trumpet card — keep the warmth, add a little 1–2.5 kHz presence, and go easy on the cut. It is still loud, so duck it under the lead vocal and pan it off-centre."
    },
    {
        "id": "french_horn",
        "group": "Brass",
        "name": "Horn French",
        "sub": "French horn in F / Bb — solo or section (SWAM French Horn)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 55–60 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — the lowest useful horn note is around 62 Hz (written B1)"},
            {"hz": "100–250 Hz", "note": "Warmth", "type": "char", "db": +1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The round body of the low register — boost for a big mellow sound, cut when it competes with the bass"},
            {"hz": "300–500 Hz", "note": "Mud", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Where a horn turns into a fog that clouds the guitars"},
            {"hz": "500 Hz–1 kHz", "note": "Mellow core", "type": "char", "db": +1, "db_lo": -2, "db_hi": +2, "filter": "Parametric EQ", "label": "The horn's rounded vowel-like voice — a small boost makes it sound like a horn rather than a trumpet"},
            {"hz": "1.5–3 kHz", "note": "Brightness", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "Clarity of the line. In loud passages a horn turns brassy here — then it needs a cut instead"},
            {"hz": "3–6 kHz", "note": "Brassy edge", "type": "char", "db": -2, "db_lo": -5, "db_hi": +3, "filter": "Parametric EQ", "label": "Only appears when it is played loud or hand-stopped; cut to keep it mellow, leave it for heroic calls"},
            {"hz": "8+ kHz", "note": "Air", "type": "cut", "db": -2, "filter": "High-shelf", "label": "Almost no music up here — and the bell points BACKWARDS, so a close mic hears mostly the player's room"},
        ],
        "tip": "The horn is the glue of the brass section: mellow enough to blend with woodwinds and strong enough to join brass. Its bell points backwards, which is why it always sounds slightly distant and why a touch of room is part of the tone — don't dry it out. It rarely fights a vocal; it fills 200 Hz–2 kHz, so cut 300–500 Hz when it sits with trombones and cellos."
    },
    {
        "id": "tuba",
        "group": "Brass",
        "name": "Tuba",
        "sub": "Bass tuba / Eb tuba / euphonium — brass bass line (SWAM Tuba)",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 28–30 Hz", "note": "Sub rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — a bass tuba goes down to about 36 Hz (a contrabass tuba to 29 Hz); below that it is stage rumble"},
            {"hz": "40–80 Hz", "note": "Fundamental", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The weight of the instrument — boost for a big oompah foundation, cut when the bass guitar or kick owns this range"},
            {"hz": "100–250 Hz", "note": "Boom/mud", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "A tuba gets boomy in the low mids and covers the bass guitar's fundamental"},
            {"hz": "400–800 Hz", "note": "Honk/bark", "type": "char", "db": -2, "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "The bark of the bell — cut for a smooth sound, leave it for a punchy one"},
            {"hz": "1–2 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Articulation and attack — without it a tuba is rumble on a phone speaker"},
            {"hz": "3–5 kHz", "note": "Brass edge", "type": "char", "db": -1, "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "The little brass shimmer of the upper partials — a light cut keeps it mellow"},
            {"hz": "6+ kHz", "note": "Noise", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Valve and breath noise; no musical content"},
        ],
        "tip": "A tuba is a bass instrument: high-pass at 28–30 Hz, keep it mono and centred, and give it its own 40–80 Hz or let the bass guitar have it — never both. In an oompah or marching mix the tuba IS the bass; with a bass guitar it is the second bass, so high-pass one of them higher and split the octaves. Definition at 1–2 kHz is what makes it audible on small speakers."
    },
    {
        "id": "english_horn",
        "group": "Keys & Winds",
        "name": "English Horn",
        "sub": "Cor anglais — the alto oboe (SWAM English Horn)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 150 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — the lowest note is about 165 Hz (E3), so everything below is room and key noise"},
            {"hz": "200–500 Hz", "note": "Body", "type": "char", "db": +1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The warm, dark body that makes it an English horn and not a small oboe"},
            {"hz": "700 Hz–1.2 kHz", "note": "Nasal honk", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "The pinched, nasal core of the double reed — a narrow dip makes a sampled one sound less like a duck call"},
            {"hz": "1.5–3 kHz", "note": "Reed presence", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "Where the line is heard. Weaker than on an oboe, so it often needs a little lift to carry"},
            {"hz": "4–7 kHz", "note": "Edge/rasp", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Reed buzz and rasp — the standard cut"},
            {"hz": "8+ kHz", "note": "Air/breath", "type": "char", "db": +0, "db_lo": -3, "db_hi": +2, "filter": "High-shelf", "label": "There is little music up here; a gentle shelf either way is enough"},
        ],
        "tip": "The English horn is a darker, slower, more melancholy oboe, and it is quieter. Where the oboe wins the 1-4 kHz fight with a vocal, the English horn usually loses it - so it sits as a colour line between the vocal phrases. Keep the warmth, dip the nasal 700 Hz-1.2 kHz, and use less compression than on an oboe."
    },
    {
        "id": "euphonium",
        "group": "Brass",
        "name": "Euphonium",
        "sub": "Tenor tuba / baritone horn — a mellow tenor-register brass (SWAM Euphonium)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 70–80 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — the lowest useful note is about 82 Hz (E2), so cut just under it"},
            {"hz": "100–250 Hz", "note": "Warmth/weight", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The round body of a conical bore — boost when it carries the low horn line, cut when a bass or cello already owns it"},
            {"hz": "300–600 Hz", "note": "Mud/box", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Where a euphonium turns woolly and clouds the guitars"},
            {"hz": "800 Hz–1.2 kHz", "note": "Honk", "type": "char", "db": -1, "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "A bit of bark in loud passages - leave flat, trim if it honks"},
            {"hz": "1.5–3 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Articulation: the notes stop being a brown blur and become a line"},
            {"hz": "3–5 kHz", "note": "Brass edge", "type": "char", "db": -1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Much less blare than a trumpet - leave flat, or lift a little for bite"},
            {"hz": "8+ kHz", "note": "Air", "type": "cut", "db": -2, "filter": "High-shelf", "label": "Little music up here; a small shelf cut removes hiss and mic air"},
        ],
        "tip": "A euphonium is a flugelhorn's big brother: same conical bore and the same mellow, round tone, but an octave lower, in the trombone's register. So it fights the bass and trombone, not the vocal. A held, steady note that wobbles or shakes is vibrato in the sound engine (mod wheel / vibrato setting), not the EQ. Decide who owns 100-250 Hz."
    },
    {
        "id": "bass_clarinet",
        "group": "Keys & Winds",
        "name": "Clarinet Bass",
        "sub": "Bass clarinet in Bb — the dark, woody low reed (SWAM Bass Clarinet)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 60–70 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass — the lowest note is about 69 Hz (D2 sounding), so cut just under it"},
            {"hz": "100–250 Hz", "note": "Body", "type": "char", "db": +1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The dark, woody low register — boost for a close, warm tone, cut when it sits with bass and cello"},
            {"hz": "300–600 Hz", "note": "Hollow/boxy", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "A bass clarinet is built from odd harmonics and sounds hollow; a wide dip stops it sounding like a tube in a box"},
            {"hz": "1–3 kHz", "note": "Reed/definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Where the line reads as a clarinet and not a low drone - note definition and articulation"},
            {"hz": "3–5 kHz", "note": "Edge/squeak", "type": "char", "db": -2, "db_lo": -5, "db_hi": +2, "filter": "Parametric EQ", "label": "Reed edge in the upper register - cut for a soft tone, leave when it has to cut through"},
            {"hz": "6+ kHz", "note": "Breath/key noise", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Breath, key clicks and reed hiss"},
        ],
        "tip": "A bass clarinet is a clarinet an octave lower: dark, woody and hollow. It is a bass-and-cello neighbour, so it needs a clear owner for 100-250 Hz and definition at 1-3 kHz to be heard as a melody instead of a rumble. It is a colour, not a lead: let it answer, not compete."
    },
    {
        "id": "contrabass_clarinet",
        "group": "Keys & Winds",
        "name": "Clarinet Contrabass",
        "sub": "Contrabass clarinet — the lowest clarinet (SWAM Contrabass Clarinet)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 30–35 Hz", "note": "Sub rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - it sounds down to roughly 30-40 Hz (depending on the model), so anything under that is rumble"},
            {"hz": "40–90 Hz", "note": "Fundamental", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The weight of the instrument. Boost for a dark floor, cut when a bass or kick owns this range"},
            {"hz": "100–250 Hz", "note": "Mud/boom", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Boom and woolliness - cut it first when the mix sounds thick"},
            {"hz": "300–700 Hz", "note": "Hollow/buzz", "type": "char", "db": +0, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The hollow reed colour that makes it a clarinet and not a synth bass"},
            {"hz": "1–2 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Articulation. Without it, a phone speaker plays almost nothing"},
            {"hz": "4+ kHz", "note": "Noise", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Hardly any musical content up here - shelve key clicks and breath away"},
        ],
        "tip": "Treat the contrabass clarinet like a bass instrument with a reed: high-pass at 30-35 Hz, keep everything below 150 Hz mono and centred, give the notes definition at 1-2 kHz, and decide who owns 40-100 Hz with the bass guitar, double bass and kick. Rarely a solo - mostly a dark colour under the clarinets."
    },
    {
        "id": "piccolo",
        "group": "Keys & Winds",
        "name": "Piccolo",
        "sub": "Piccolo — the highest woodwind (SWAM Piccolo)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 450–500 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 587 Hz (D5), so everything below is room and handling noise"},
            {"hz": "600 Hz–1.2 kHz", "note": "Body", "type": "char", "db": +0, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The thin lower body - a piccolo has very little of it; leave flat or add a touch for a fuller tone"},
            {"hz": "2–4 kHz", "note": "Shrill", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "A piccolo is brightest and most piercing here - a wide dip is the standard fix for 'it hurts'"},
            {"hz": "4–8 kHz", "note": "Brilliance", "type": "char", "db": +0, "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "The sparkle of the top register; boost for a bright solo, cut when it fights the cymbals and hi-hat"},
            {"hz": "10+ kHz", "note": "Air", "type": "char", "db": +0, "db_lo": -3, "db_hi": +2, "filter": "High-shelf", "label": "Breath and shimmer; skip it, a piccolo already has plenty"},
        ],
        "tip": "A piccolo is the loudest, shrillest thing in the top octave, so the job is to calm it, not to brighten it: high-pass at 450 Hz, dip 2-4 kHz, and let it sit above the cymbals. It fights the hi-hat and ride for the same range, so decide who owns 6-10 kHz."
    },
    {
        "id": "alto_flute",
        "group": "Keys & Winds",
        "name": "Flute Alto",
        "sub": "Alto flute in G — a dark, breathy flute (SWAM Alto Flute)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 170–180 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 196 Hz (G3)"},
            {"hz": "250–500 Hz", "note": "Body", "type": "char", "db": +1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The round, dark body - boost for an intimate close tone, cut if it clouds the guitars"},
            {"hz": "800 Hz–1.5 kHz", "note": "Core tone", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "The flute's main tone - what makes it heard as a melody"},
            {"hz": "2–4 kHz", "note": "Presence", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "A quiet instrument that needs a little lift to carry over a band"},
            {"hz": "5–8 kHz", "note": "Breath noise", "type": "char", "db": -2, "db_lo": -5, "db_hi": +1, "filter": "Parametric EQ", "label": "The airy chuff - cut for a clean tone, leave for an intimate, breathy one"},
            {"hz": "10+ kHz", "note": "Air", "type": "char", "db": +1, "db_lo": -2, "db_hi": +2, "filter": "High-shelf", "label": "A touch of air; skip it for a close tone"},
        ],
        "tip": "An alto flute is a flute an octave and a bit lower: dark, breathy and quiet. It never competes with a vocal for loudness, only for space, so it needs a little presence and a clean low cut. Short, light reverb - a wet alto flute disappears."
    },
    {
        "id": "bass_flute",
        "group": "Keys & Winds",
        "name": "Flute Bass",
        "sub": "Bass flute in C — the lowest common flute (SWAM Bass Flute)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 110–120 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 131 Hz (C3)"},
            {"hz": "150–400 Hz", "note": "Body", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The warm, hollow body; it is weak in projection, so a little lift helps"},
            {"hz": "500 Hz–1 kHz", "note": "Chuff/hollow", "type": "cut", "db": -2, "filter": "Parametric EQ", "label": "The hollow, tube-like part of the tone; a gentle dip helps clarity"},
            {"hz": "1–3 kHz", "note": "Presence", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "A bass flute is easy to lose; presence here is what lets it be heard"},
            {"hz": "4–8 kHz", "note": "Breath noise", "type": "char", "db": -2, "db_lo": -5, "db_hi": +1, "filter": "Parametric EQ", "label": "Breath noise - tolerable up close, an issue in a dense mix"},
            {"hz": "10+ kHz", "note": "Air", "type": "cut", "db": -1, "filter": "High-shelf", "label": "Little music up here; a small shelf cut removes hiss"},
        ],
        "tip": "A bass flute is the quietest flute and the easiest to bury: it needs presence at 1-3 kHz and a clean space, not extra volume. Keep it out of the bass's way (150-250 Hz) and give it a short room, never a long hall."
    },
    {
        "id": "soprano_sax",
        "group": "Keys & Winds",
        "name": "Saxophone Soprano",
        "sub": "Soprano sax — the straight, nasal one (SWAM Soprano Sax)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 170–180 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 208 Hz (Ab3)"},
            {"hz": "300–600 Hz", "note": "Body", "type": "char", "db": +0, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Less body than the bigger saxes; boost a little for warmth"},
            {"hz": "700 Hz–1.2 kHz", "note": "Nasal", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "The nasal, oboe-like character - a narrow dip for a smoother tone"},
            {"hz": "1.5–3 kHz", "note": "Reed core", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "The reed's voice, brighter than an alto"},
            {"hz": "3.5–6 kHz", "note": "Bite/squeal", "type": "char", "db": -3, "db_lo": -6, "db_hi": +2, "filter": "Parametric EQ", "label": "Where soprano sax gets squeaky and harsh - cut it, then lift only for a deliberate cutting solo"},
            {"hz": "7–10 kHz", "note": "Breath/squawk", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Air noise and reed squawk - a narrow dip, not a shelf"},
        ],
        "tip": "A soprano sax is the brightest sax and sits where a lead vocal's upper half does. It behaves like a second singer: dip 3.5-6 kHz, duck it under the vocal and answer the phrases rather than play under them."
    },
    {
        "id": "alto_sax",
        "group": "Keys & Winds",
        "name": "Saxophone Alto",
        "sub": "Alto sax — the lead sax (SWAM Alto Sax)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 120–130 Hz", "note": "Rumble/key noise", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 139 Hz (Db3)"},
            {"hz": "150–350 Hz", "note": "Body", "type": "char", "db": +1, "db_lo": -4, "db_hi": +3, "filter": "Parametric EQ", "label": "Warm body - boost for a big tone, cut when it crowds the guitars"},
            {"hz": "400–800 Hz", "note": "Woody box", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Where a sax gets boxy - a wide dip usually fixes it"},
            {"hz": "1–2 kHz", "note": "Reed core", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "The reed's voice - what makes it a sax and not a synth"},
            {"hz": "3–5 kHz", "note": "Bite/growl", "type": "char", "db": +1, "db_lo": -4, "db_hi": +4, "filter": "Parametric EQ", "label": "Cutting edge for a solo; cut hard when it plays under a vocal"},
            {"hz": "6–9 kHz", "note": "Breath/squawk", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Reed squawk and mouthpiece hiss - narrow dip"},
            {"hz": "10+ kHz", "note": "Air", "type": "char", "db": +0, "db_lo": -2, "db_hi": +2, "filter": "High-shelf", "label": "Small lift for a modern polished sound"},
        ],
        "tip": "The alto sax is the classic lead sax and behaves like a vocal: same range, same dynamics, same need for compression. It sits higher and thinner than a tenor and fights the singer harder, so pick one to own 3-5 kHz at a time, pan it away and let it answer."
    },
    {
        "id": "tenor_sax",
        "group": "Keys & Winds",
        "name": "Saxophone Tenor",
        "sub": "Tenor sax — the big, warm one (SWAM Tenor Sax)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 90–100 Hz", "note": "Rumble/key noise", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 104 Hz (Ab2)"},
            {"hz": "120–300 Hz", "note": "Body", "type": "char", "db": +2, "db_lo": -4, "db_hi": +3, "filter": "Parametric EQ", "label": "The tenor's warm, big body - boost for a rich tone, cut when it crowds the bass and guitars"},
            {"hz": "400–800 Hz", "note": "Woody box", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Where a tenor turns boxy and muddy"},
            {"hz": "1–2 kHz", "note": "Reed core", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "The reed's voice"},
            {"hz": "3–5 kHz", "note": "Growl/bite", "type": "char", "db": +1, "db_lo": -4, "db_hi": +4, "filter": "Parametric EQ", "label": "The growl that cuts through; cut under a vocal"},
            {"hz": "6–9 kHz", "note": "Breath/squawk", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Reed squawk and mouthpiece hiss"},
        ],
        "tip": "A tenor sax is a male vocal in brass clothing: warm, big and almost exactly the vocal's range. Cut 400-800 Hz, keep the reed core at 1-2 kHz, compress it like a voice, and give it its own space away from the singer."
    },
    {
        "id": "baritone_sax",
        "group": "Keys & Winds",
        "name": "Saxophone Baritone",
        "sub": "Baritone sax — the low, gruff one (SWAM Baritone Sax)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 55–60 Hz", "note": "Rumble/key noise", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - it really does go down to about 65 Hz (C2)"},
            {"hz": "80–200 Hz", "note": "Weight", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The baritone's whole point is weight - boost it when it plays the line, cut when a bass guitar owns it"},
            {"hz": "250–500 Hz", "note": "Mud/honk", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Where a baritone gets woolly and honky"},
            {"hz": "700 Hz–1.5 kHz", "note": "Reed core", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "The reed's voice, lower than on the other saxes"},
            {"hz": "2–4 kHz", "note": "Growl/bite", "type": "char", "db": +0, "db_lo": -4, "db_hi": +4, "filter": "Parametric EQ", "label": "Growl for a solo or a riff; trim when it fights the vocal"},
            {"hz": "6+ kHz", "note": "Breath/squawk", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Reed squawk and hiss - little music up here"},
        ],
        "tip": "A baritone sax is a bass-register reed: it sits with the bass guitar and trombone, not with the vocal. Decide who owns 100-250 Hz, keep its low end centred, and treat the growl as the featured sound."
    },
    {
        "id": "piccolo_trumpet",
        "group": "Brass",
        "name": "Trumpet Piccolo",
        "sub": "Piccolo trumpet — the bright Baroque trumpet (SWAM Piccolo Trumpet)",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 280–300 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 330 Hz, so everything below is room and breath"},
            {"hz": "400–800 Hz", "note": "Body", "type": "char", "db": +0, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Thinner than a Bb trumpet; a touch of warmth helps"},
            {"hz": "1.5–3 kHz", "note": "Brilliance", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "Where the line reads as a melody"},
            {"hz": "3–6 kHz", "note": "Blare/edge", "type": "char", "db": -3, "db_lo": -6, "db_hi": +2, "filter": "Parametric EQ", "label": "Brighter and edgier than a Bb trumpet - cut to tame it"},
            {"hz": "8–12 kHz", "note": "Air", "type": "char", "db": +0, "db_lo": -3, "db_hi": +2, "filter": "High-shelf", "label": "Little needed; skip for a vintage tone"},
        ],
        "tip": "A piccolo trumpet is a trumpet an octave brighter: the same loudness problem, shifted up. It lives at 330 Hz-1 kHz fundamentals and a very bright 3-6 kHz edge, so tame that band, duck it under the lead vocal and pan it off-centre."
    },
    {
        "id": "tenor_trombone",
        "group": "Brass",
        "name": "Trombone Tenor",
        "sub": "Tenor trombone in Bb - the standard trombone (SWAM Tenor Trombone)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 70-80 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the tenor trombone goes down to about 82 Hz, so cut just under that, not higher"},
            {"hz": "100-250 Hz", "note": "Weight/body", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The trombone's whole point is weight - boost when it carries the low horn line, CUT it when a bass guitar is already there"},
            {"hz": "300-600 Hz", "note": "Mud/box", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Where a bone turns woolly and clouds the guitars - the standard cut"},
            {"hz": "1-2 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Slide articulation - the notes stop being a brown blur and become a line"},
            {"hz": "3-5 kHz", "note": "Rasp/bite", "type": "char", "db": -2, "db_lo": -5, "db_hi": +3, "filter": "Parametric EQ", "label": "Brassy rasp - push for an aggressive ska/funk bone, cut when it fights the vocal"},
            {"hz": "8+ kHz", "note": "Air", "type": "cut", "db": -2, "filter": "High-shelf", "label": "Little useful content up here - a small shelf cut removes hiss and mic air without dulling the tone"},
        ],
        "tip": "The tenor trombone is the horn that fights the BASS, not the vocal - it sits 100-600 Hz right on top of the bass guitar and the low guitars. Decide who owns 100-250 Hz: if the bass does, high-pass the bone higher (120 Hz) and let it live 300 Hz-2 kHz instead. In a horn section it is the foundation, so keep it a touch darker than the trumpet and let the trumpet take the top."
    },
    {
        "id": "tenor_bass_trombone",
        "group": "Brass",
        "name": "Trombone Tenor-Bass",
        "sub": "Tenor-bass trombone (tenor with a trigger) - the heavy tenor bone (SWAM Tenor Bass Trombone)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 55-60 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - with its trigger it goes down to about 60 Hz, so cut just under that"},
            {"hz": "90-220 Hz", "note": "Weight/body", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "More weight than a plain tenor bone - boost when it carries the low horn line, cut when a bass guitar owns it"},
            {"hz": "250-550 Hz", "note": "Mud/box", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Where a bone turns woolly and clouds the guitars - the standard cut"},
            {"hz": "1-2 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Slide articulation - the notes become a line, not a brown blur"},
            {"hz": "3-5 kHz", "note": "Rasp/bite", "type": "char", "db": -2, "db_lo": -5, "db_hi": +3, "filter": "Parametric EQ", "label": "Brassy rasp - push for an aggressive bone, cut when it fights the vocal"},
            {"hz": "8+ kHz", "note": "Air", "type": "cut", "db": -2, "filter": "High-shelf", "label": "Little useful content up here - a small shelf cut removes hiss without dulling the tone"},
        ],
        "tip": "A tenor-bass trombone is a tenor bone with a bigger bore and a trigger for the low notes, so it leans on the bass guitar a little more than a plain tenor. Decide who owns 80-200 Hz; if the bass does, high-pass the bone at 120 Hz and let it live from 250 Hz up."
    },
    {
        "id": "double_bass_trombone",
        "group": "Brass",
        "name": "Trombone Double Bass",
        "sub": "Double-bass (contrabass) trombone - the lowest bone (SWAM Double Bass Trombone)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 30-35 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest notes are about 35-40 Hz, so cut just under that"},
            {"hz": "50-140 Hz", "note": "Weight", "type": "char", "db": +2, "db_lo": -4, "db_hi": +3, "filter": "Parametric EQ", "label": "The weight of the lowest horn - boost when it carries the bottom line, cut hard when a bass guitar or a tuba owns it"},
            {"hz": "180-400 Hz", "note": "Mud/boom", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Boom and woolliness - the standard cut"},
            {"hz": "800 Hz-1.5 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Articulation: without it a double-bass trombone is only a rumble"},
            {"hz": "2.5-4 kHz", "note": "Rasp/bite", "type": "char", "db": -2, "db_lo": -5, "db_hi": +3, "filter": "Parametric EQ", "label": "Brassy rasp - push for a hard-hitting stab, cut when it fights the vocal"},
            {"hz": "5+ kHz", "note": "Noise", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Valve and breath noise; no musical content"},
        ],
        "tip": "A double-bass trombone is below the whole horn section and fights the bass guitar and the kick, not the vocal. Give it one job: either it doubles the bass an octave above, or it is the bass - never both. High-pass the bass guitar or the bone, and keep its low end centred."
    },
    {
        "id": "alto_trombone",
        "group": "Brass",
        "name": "Trombone Alto",
        "sub": "Alto trombone in Eb — the bright trombone (SWAM Alto Trombone)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 90–100 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - the lowest note is about 110 Hz"},
            {"hz": "150–350 Hz", "note": "Weight/body", "type": "char", "db": +1, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "A bit less weight than a tenor trombone; boost if it needs it"},
            {"hz": "400–700 Hz", "note": "Mud/box", "type": "cut", "db": -3, "filter": "Parametric EQ", "label": "Where a bone turns woolly"},
            {"hz": "1–2.5 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Slide articulation - the notes become a line"},
            {"hz": "3–5 kHz", "note": "Rasp/bite", "type": "char", "db": -2, "db_lo": -5, "db_hi": +3, "filter": "Parametric EQ", "label": "Brassy rasp - push for aggression, cut when it fights the vocal"},
            {"hz": "8+ kHz", "note": "Air", "type": "cut", "db": -2, "filter": "High-shelf", "label": "Little music up here"},
        ],
        "tip": "An alto trombone is a lighter, brighter trombone in the register of a horn or trumpet's lower half. It fights the vocal more than a tenor bone does, so keep it a little darker than a trumpet and let the trumpet take the top."
    },
    {
        "id": "bass_trombone",
        "group": "Brass",
        "name": "Trombone Bass",
        "sub": "Bass trombone / contrabass trombone — the low bone (SWAM Bass Trombone)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 50–55 Hz", "note": "Rumble", "type": "cut", "db": -18, "filter": "High-pass", "label": "High-pass - with its trigger it goes down to about 58 Hz, and pedal tones go lower"},
            {"hz": "70–200 Hz", "note": "Weight", "type": "char", "db": +2, "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "The weight of a bass trombone - boost when it carries the low line, cut when a bass guitar owns it"},
            {"hz": "250–500 Hz", "note": "Mud/boom", "type": "cut", "db": -4, "filter": "Parametric EQ", "label": "Boom and woolliness - the standard cut"},
            {"hz": "1–2 kHz", "note": "Definition", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Articulation: without it a bass trombone is a rumble"},
            {"hz": "3–5 kHz", "note": "Rasp/bite", "type": "char", "db": -2, "db_lo": -5, "db_hi": +3, "filter": "Parametric EQ", "label": "Brassy rasp - push for a hard-hitting stab, cut when it fights the vocal"},
            {"hz": "6+ kHz", "note": "Noise", "type": "cut", "db": -3, "filter": "High-shelf", "label": "Valve and breath noise; no musical content"},
        ],
        "tip": "A bass trombone is the bottom of the horn section and fights the bass guitar, not the vocal. Decide who owns 80-200 Hz; if the bass does, high-pass the bone at 120 Hz and let it live from 250 Hz up. Keep its low end centred."
    },
    {
        "id": "synth_pad",
        "group": "Keys & Winds",
        "name": "Synth Pad (long)",
        "sub": "Sustained / calm pad — organ- or flute-like",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 80–120 Hz",  "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — a sustained bed needs no true low end (bass/keys own it)"},
            {"hz": "150–400 Hz",   "note": "Warmth/lush",   "type": "char",    "db": +1,  "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "Body of the pad — small boost for lushness, cut if it clouds the mix"},
            {"hz": "400–800 Hz",   "note": "Mud/congestion","type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Sustained chords pile up here — cut so the pad doesn't mask the mids"},
            {"hz": "3–5 kHz",      "note": "Lead-vocal zone","type": "cut",    "db": -3,  "filter": "Parametric EQ", "label": "Dip the lead-vocal presence range so the pad stays a calm BED behind it"},
            {"hz": "8–14 kHz",     "note": "Air/sheen",     "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "High-shelf air for an open, wide, calm sheen"},
        ],
        "tip": "Treat like an organ/flute bed: high-pass, cut 400–800 Hz mud, carve 3–5 kHz so the vocal cuts through, then add air. Keep it wide and calm — automate it down under vocals."
    },
    {
        "id": "synth_pluck",
        "group": "Keys & Winds",
        "name": "Synth Pluck / Stab (short)",
        "sub": "Short 'plopp' — usually bright (not always)",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 80–100 Hz",  "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — short plucks have no useful low end"},
            {"hz": "100–250 Hz",   "note": "Body",          "type": "char",    "db": +1,  "db_lo": -2, "db_hi": +2, "filter": "Parametric EQ", "label": "Body/weight — small boost for a fuller pluck, cut if it muds the low-mids"},
            {"hz": "300–500 Hz",   "note": "Boxiness",      "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Cut boxy mud so the 'plopp' stays clean"},
            {"hz": "1–3 kHz",      "note": "Presence",      "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Note presence so the pluck reads as pitched, not just a click"},
            {"hz": "3–6 kHz",      "note": "Attack/snap",   "type": "char",    "db": +3,  "db_lo": -2, "db_hi": +4, "filter": "Parametric EQ", "label": "The bright 'plopp' snap — boost for a bright pluck, ease it for a darker one"},
            {"hz": "8–12 kHz",     "note": "Air/zing",      "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "Air/zing on top — gentle, and skip it for a dark pluck"},
        ],
        "tip": "Bright short stabs live in 2–6 kHz + air; high-pass and cut 300–500 Hz. If THIS pluck is a dark/soft one, pull back the 3–6 kHz snap and the high-shelf air instead."
    },
    {
        "id": "synth_mallet",
        "group": "Keys & Winds",
        "name": "Synth Mallet",
        "sub": "Xylophone / marimba / bell-like tonal hits",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 150–200 Hz", "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass hard — mallet/bell tones carry almost nothing down low"},
            {"hz": "200–500 Hz",   "note": "Wood/body",     "type": "char",    "db": 0,   "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "A little body — boost for marimba warmth, cut for a pure glassy bell"},
            {"hz": "800 Hz–2 kHz", "note": "Fundamental",   "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The pitched tone of each hit — its core character"},
            {"hz": "3–6 kHz",      "note": "Mallet ping",   "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "The hard 'ping'/attack of the mallet — the defining transient"},
            {"hz": "8–14 kHz",     "note": "Bell shimmer",  "type": "boost",   "db": +3,  "filter": "High-shelf",    "label": "Glassy bell shimmer — keep gentle, it stacks with cymbals/hi-hats"},
        ],
        "tip": "Xylophone/bell tones are all attack + shimmer: high-pass hard, lift the fundamental (~1 kHz) and the mallet ping (3–6 kHz). Watch the >8 kHz buildup against cymbals/hi-hats — keep the air subtle."
    },
    # ---- STRINGS ----
    {
        "id": "violin",
        "group": "Strings",
        "name": "Violin",
        "sub": "Solo / section violin",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 180–200 Hz", "note": "Rumble/low end", "type": "cut",   "db": -18, "filter": "High-pass",     "label": "High-pass — the violin has no useful content below its lowest string (G3 ≈196 Hz)"},
            {"hz": "200–300 Hz",   "note": "Body/warmth",    "type": "char",   "db": +1,  "db_lo": -2, "db_hi": +2, "filter": "Parametric EQ", "label": "Body resonance — small boost for warmth, cut if it sounds tubby"},
            {"hz": "400–600 Hz",   "note": "Boxiness",       "type": "cut",    "db": -3,  "filter": "Parametric EQ", "label": "Boxy/nasal honk — sweep and cut 2–4 dB if congested"},
            {"hz": "1–3 kHz",      "note": "Presence/bite",  "type": "boost",  "db": +3,  "filter": "Parametric EQ", "label": "Forward presence and articulation of the bow"},
            {"hz": "3–6 kHz",      "note": "Scratch/rosin",  "type": "char",   "db": -2,  "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "Bow scratch / rosin edge — cut if harsh, boost a touch for intimacy"},
            {"hz": "8–12 kHz",     "note": "Air/sheen",      "type": "boost",  "db": +3,  "filter": "High-shelf",    "label": "Silky air and shimmer on top — keep gentle"},
        ],
        "tip": "Violin lives in 1–6 kHz. High-pass at ~180 Hz. Tame 3–5 kHz if the bow sounds scratchy; a gentle high-shelf adds 'expensive' silk. This card is the SOLO/melody role. Holding long notes behind the song instead? Use Violin (background) — it cuts the very band this one boosts."
    },
    {
        "id": "violin_bg",
        "group": "Strings",
        "name": "Violin (background)",
        "sub": "Held / sustained violin behind the song — the filler role",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 180–200 Hz", "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — nothing below the G string (≈196 Hz), bed or solo"},
            {"hz": "200–300 Hz",   "note": "Body",          "type": "char",    "db": 0,   "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Body resonance — a held bed may keep a touch more than a solo, but cut it the moment the mix fills up"},
            {"hz": "400–600 Hz",   "note": "Boxiness",      "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Boxy honk — cut harder than the solo card: a bed sits on the same note for bars at a time, and so does its box"},
            {"hz": "1–3 kHz",      "note": "Melody zone",   "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "THE band. The Violin card boosts this +3; a bed cuts it — this is where whatever carries the tune needs to live"},
            {"hz": "3–6 kHz",      "note": "Vocal zone",    "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "The lead-vocal presence range, and the bow’s edge with it — carve the whole region evenly so the singer comes through"},
            {"hz": "8–12 kHz",     "note": "Silk",          "type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "Silk — less than the solo's +3, and most of what makes a held violin read as a pad instead of a player"},
        ],
        "tip": "A sustained violin behind the song is a bed, and beds are defined by what they give up. It gives up 1–3 kHz (the solo card's signature boost), it gives up 3–6 kHz to the singer, and it keeps only enough silk to stay open. If you have a whole ensemble rather than one player, use String Section instead — this card is one violin holding notes. Level it (a solo violin wants its bow dynamics; a bed must sit still) and duck it under the vocal."
    },
    {
        "id": "viola",
        "group": "Strings",
        "name": "Viola",
        "sub": "Solo / section viola",
        "color": C_NEUTRAL,
        "bands": [
            {"hz": "< 120 Hz",     "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — lowest string is C3 (≈131 Hz)"},
            {"hz": "200–500 Hz",   "note": "Warm body",     "type": "boost",   "db": +2,  "filter": "Parametric EQ", "label": "The viola's warm, dark body — its main character"},
            {"hz": "600–900 Hz",   "note": "Nasal/boxy",    "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Nasal honk — cut if it sounds congested"},
            {"hz": "1.5–3 kHz",    "note": "Presence",      "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Definition and bow articulation"},
            {"hz": "4–7 kHz",      "note": "Bow noise",     "type": "char",    "db": -2,  "db_lo": -4, "db_hi": +1, "filter": "Parametric EQ", "label": "Bow/rosin noise — cut if harsh"},
            {"hz": "10+ kHz",      "note": "Air",           "type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "Gentle air to open up the dark tone"},
        ],
        "tip": "Darker and lower than violin — emphasise 200–500 Hz warmth. Don't over-brighten or it just sounds like a violin."
    },
    {
        "id": "viola_front",
        "group": "Strings",
        "name": "Viola (front)",
        "sub": "Viola carrying the tune - the front / melody role (no Pair or Prio needed)",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 120 Hz",     "note": "Rumble",        "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — lowest string is C3 (≈131 Hz)"},
            {"hz": "200–500 Hz",   "note": "Warm body",     "type": "char",    "db": 0,   "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "Keep the dark body, but a viola in front is where the mix clouds first: hold it level, cut if the band gets muddy"},
            {"hz": "600–900 Hz",   "note": "Nasal/boxy",    "type": "cut",     "db": -3,  "filter": "Parametric EQ", "label": "Nasal honk — cut it, a melody is heard for longer than a bed"},
            {"hz": "1.5–3 kHz",    "note": "The tune",      "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "THE band. The Viola bed gives this away; a viola that carries the tune has to own it"},
            {"hz": "4–7 kHz",      "note": "Bow noise",     "type": "char",    "db": -2,  "db_lo": -4, "db_hi": +1, "filter": "Parametric EQ", "label": "Bow/rosin noise — cut if harsh, a front instrument shows every scratch"},
            {"hz": "10+ kHz",      "note": "Air",           "type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "Gentle air to open up the dark tone"},
        ],
        "tip": "The viola in the FRONT / melody role: it is placed like a solo violin (mid, nearly centre, close) instead of as an inner voice, and it owns 1.5–3 kHz. Use it when the viola plays the tune or a counter-melody; use Viola (the card above) for the held inner voice. Both ticked = the same player in two roles, so high-pass the front one and let the bed give up the tune band."
    },
    {
        "id": "cello",
        "group": "Strings",
        "name": "Cello",
        "sub": "Solo / section cello",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 50–60 Hz",   "note": "Sub rumble",    "type": "cut",     "db": -12, "filter": "High-pass",     "label": "High-pass below the low C (≈65 Hz) to remove floor/stage rumble"},
            {"hz": "80–120 Hz",    "note": "Chest/body",    "type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "The rich chest and body weight of the cello"},
            {"hz": "200–400 Hz",   "note": "Mud",           "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Classic mud zone — cut to keep the low end defined"},
            {"hz": "400–800 Hz",   "note": "Warmth",        "type": "char",    "db": 0,   "db_lo": -3, "db_hi": +2, "filter": "Parametric EQ", "label": "Woody warmth — boost for intimacy, cut if boxy in a dense mix"},
            {"hz": "1–3 kHz",      "note": "Bow definition","type": "boost",   "db": +3,  "filter": "Parametric EQ", "label": "Bow articulation and note clarity"},
            {"hz": "5–8 kHz",      "note": "Rosin/scrape",  "type": "char",    "db": -2,  "db_lo": -4, "db_hi": +1, "filter": "Parametric EQ", "label": "Rosin scrape — cut if harsh, leave for an intimate close-miked feel"},
            {"hz": "10+ kHz",      "note": "Air",           "type": "boost",   "db": +2,  "filter": "High-shelf",    "label": "A little air for openness"},
        ],
        "tip": "Cello spans a huge range. Boost 80–120 Hz for body, cut 200–400 Hz for mud, lift 1–3 kHz so the bowing stays articulate."
    },
    {
        "id": "double_bass",
        "group": "Strings",
        "name": "Double Bass",
        "sub": "Upright / contrabass (arco & pizzicato)",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 30–40 Hz",   "note": "Sub rumble",     "type": "cut",    "db": -12, "filter": "High-pass",     "label": "High-pass below the low E (≈41 Hz) to clear stage rumble"},
            {"hz": "60–100 Hz",    "note": "Body/weight",    "type": "boost",  "db": +3,  "filter": "Parametric EQ", "label": "Fundamental weight and warmth"},
            {"hz": "200–300 Hz",   "note": "Mud",            "type": "cut",    "db": -4,  "filter": "Parametric EQ", "label": "Cut mud so it doesn't fight the cello/kick"},
            {"hz": "700 Hz–1 kHz", "note": "Growl/finger",   "type": "char",   "db": +1,  "db_lo": -2, "db_hi": +3, "filter": "Parametric EQ", "label": "Finger/growl character — boost for a jazzy voice, cut if honky"},
            {"hz": "2–4 kHz",      "note": "Pizz attack",    "type": "boost",  "db": +3,  "filter": "Parametric EQ", "label": "Pizzicato 'thump' attack and string definition"},
            {"hz": "5+ kHz",       "note": "Bow/finger noise","type": "cut",   "db": -3,  "filter": "High-shelf",    "label": "Tame excessive bow or fingerboard noise"},
        ],
        "tip": "Treat like an acoustic bass guitar: high-pass ~30 Hz, body at 60–100 Hz, attack at 2–4 kHz for pizzicato definition."
    },
    {
        "id": "double_bass_section",
        "group": "Strings",
        "name": "Double Bass Section",
        "sub": "Several basses together - the bass desk (SWAM Double Bass section)",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 35–40 Hz", "note": "Sub rumble", "type": "cut", "db": -12, "filter": "High-pass", "label": "High-pass below the low E (~41 Hz); a section multiplies stage and floor rumble"},
            {"hz": "50–100 Hz", "note": "Body/weight", "type": "boost", "db": +2, "filter": "Parametric EQ", "label": "The fundamental weight of the desk - the part that makes it a section and not one player"},
            {"hz": "200–300 Hz", "note": "Mud", "type": "cut", "db": -5, "filter": "Parametric EQ", "label": "Several basses stack mud fast; cut harder than for a solo bass"},
            {"hz": "400–700 Hz", "note": "Boom/box", "type": "cut", "db": -2, "filter": "Parametric EQ", "label": "Wooden box resonance multiplied by the number of players"},
            {"hz": "700 Hz–1 kHz", "note": "Growl/finger", "type": "char", "db": +1, "db_lo": -2, "db_hi": +3, "filter": "Parametric EQ", "label": "Finger/growl character - lift for a jazzy section, trim if it honks"},
            {"hz": "2–4 kHz", "note": "Attack", "type": "boost", "db": +3, "filter": "Parametric EQ", "label": "Bow attack and pizzicato 'thump' - what lets the section be heard as notes"},
            {"hz": "5+ kHz", "note": "Bow/finger noise", "type": "cut", "db": -4, "filter": "High-shelf", "label": "A section adds bow scrape from many players - shelve it down"},
        ],
        "tip": "A bass section is one low instrument made of several players: keep everything below about 100 Hz mono and centred, cut the mud harder than for a solo bass (it adds up with every player), and let the width come from the 1-4 kHz bow and attack. It replaces the root bass in the low end - if a bass guitar plays too, one of them owns the sub and the other is high-passed."
    },
    {
        "id": "string_section",
        "group": "Strings",
        "name": "String Section",
        "sub": "Ensemble / orchestral strings",
        "color": C_CHAR,
        "bands": [
            {"hz": "< 80 Hz",      "note": "Low end",        "type": "cut",    "db": -18, "filter": "High-pass",     "label": "High-pass — let bass and cello own the low end"},
            {"hz": "200–400 Hz",   "note": "Warmth",         "type": "char",   "db": +1,  "db_lo": -2, "db_hi": +2, "filter": "Parametric EQ", "label": "Ensemble warmth — boost for lushness, cut if it muddies the mix"},
            {"hz": "400–800 Hz",   "note": "Mud/congestion", "type": "cut",    "db": -3,  "filter": "Parametric EQ", "label": "Cut to keep a large section from clouding the mids"},
            {"hz": "3–6 kHz",      "note": "Presence",       "type": "boost",  "db": +2,  "filter": "Parametric EQ", "label": "Bow articulation so the section stays defined"},
            {"hz": "8–14 kHz",     "note": "Silk/air",       "type": "boost",  "db": +3,  "filter": "High-shelf",    "label": "Lush high-shelf 'silk' — the signature polished string sheen"},
        ],
        "tip": "For a lush pad, high-shelf the air and gently cut 400–800 Hz mud. Layered sections build up low-mids fast — high-pass each layer. This card is the BED: note that it has no 1–3 kHz band at all, which is right for a pad and wrong for a tune. When the section carries the melody, use Strings (lead)."
    },
    {
        "id": "strings_lead",
        "group": "Strings",
        "name": "Strings (lead)",
        "sub": "The section carries the tune — the big melody line, not a bed",
        "color": C_BOOST,
        "bands": [
            {"hz": "< 100 Hz",     "note": "Low end",       "type": "cut",     "db": -18, "filter": "High-pass",     "label": "High-pass — drop it to 60–80 Hz ONLY if the tune really lives in the cello register; a violin melody has nothing below 196 Hz"},
            {"hz": "200–400 Hz",   "note": "Body",          "type": "char",    "db": 0,   "db_lo": -3, "db_hi": +3, "filter": "Parametric EQ", "label": "Ensemble warmth — a melody needs less of it than a bed does; cut when the mix is full, boost only for an exposed line"},
            {"hz": "400–800 Hz",   "note": "Mud",           "type": "cut",     "db": -4,  "filter": "Parametric EQ", "label": "Cut harder than the bed: this is what stops a section line from congealing into one warm block"},
            {"hz": "1–3 kHz",      "note": "Note core",     "type": "boost",   "db": +4,  "filter": "Parametric EQ", "label": "Where a string melody reads as a melody — the String Section card has no band here at all, because a bed does not need one"},
            {"hz": "3–6 kHz",      "note": "Bow/rosin",     "type": "char",    "db": -1,  "db_lo": -4, "db_hi": +2, "filter": "Parametric EQ", "label": "Bow articulation against rosin scratch — a touch up for bite when the line is alone, down when a singer is in"},
            {"hz": "8–14 kHz",     "note": "Silk/air",      "type": "boost",   "db": +1,  "filter": "High-shelf",    "label": "Far less silk than the bed gets: air is most of what makes a section sound big and FAR AWAY, and a melody must not be far away"},
        ],
        "tip": "A string section playing the tune is not a string pad, and the difference is almost all in two bands: it needs the 1–3 kHz note core the bed card does not even have, and it must give up most of the 8–14 kHz silk that makes the bed sound expensive. Keep the reverb short and the section fairly centred — width and a long hall are what put a bed behind the band, and they will do exactly the same to your melody. If the tune sits low, this is a cello line: move the high-pass down to 60–80 Hz and use the Cello card's body advice with these mids."
    },
]

# ---- HIDDEN INSTRUMENTS ------------------------------------------------------
# Instruments you never use. They are filtered out of EQ_DATA here, so they
# disappear from every tab, plan, popup and preset run at once. All their data
# (bands, LOWCUT, DEPTH, SMARTEQ_GROUP, …) is still in the file untouched —
# delete an id from this set to bring the instrument straight back.
HIDDEN_INSTRUMENT_IDS = {
    "guitar_lead",      # you never use a lead guitar
}
EQ_DATA = [x for x in EQ_DATA if x["id"] not in HIDDEN_INSTRUMENT_IDS]

# ---- LIST ORDER (v3.24) --------------------------------------------------------
# EQ_DATA order IS the order of the tabs, the Song Variants list and the Selected
# Instruments panel (GROUPS and GROUP_MAP below are built from it), so the order is
# fixed HERE, once, instead of by moving 40 dicts around in the data:
#   * the sections: Vocals, Drums & Percussion, Bass, Guitar (his order, untouched),
#     then Brass, Keys & Winds, Strings - A to Z;
#   * inside Brass, Keys & Winds and Strings: A to Z by name, which is why the role
#     now stands AFTER the instrument ('Organ (lead)', not 'Lead Organ');
#   * Drums: Toms, then Percussion, then Cymbals (Hand Drums stays last);
#   * Vocals, Bass and Guitar keep the order they are written in.
# v3.27: 'Keys & Winds' is split into Winds, Keys (organ, piano, accordion) and Other
# (synths, harmonica). The cards are still written with group 'Keys & Winds'; they are
# sorted into the four tabs right here, so no card has to be edited.
KEYS_TAB_IDS  = ("accordion", "accordion_lead", "organ", "organ_lead", "organ_melody",
                 "piano_bg", "piano_riff")
OTHER_TAB_IDS = ("harmonica", "synth_mallet", "synth_pad", "synth_pluck")
for _x in EQ_DATA:
    if _x["group"] == "Keys & Winds":
        _x["group"] = ("Keys" if _x["id"] in KEYS_TAB_IDS
                       else "Other" if _x["id"] in OTHER_TAB_IDS else "Winds")
GROUP_ORDER   = ("Vocals", "Drums & Percussion", "Bass", "Guitar",
                 "Brass", "Winds", "Keys", "Other", "Strings")
ALPHA_GROUPS  = ("Brass", "Winds", "Keys", "Other", "Strings")
DRUM_ORDER    = ("kick", "snare", "hihat", "ride", "toms", "percussion",
                 "cymbals", "hand_drums")
_WRITTEN_POS  = {x["id"]: i for i, x in enumerate(EQ_DATA)}


def _list_order_key(x):
    g = x["group"]
    rank = GROUP_ORDER.index(g) if g in GROUP_ORDER else len(GROUP_ORDER)
    if g in ALPHA_GROUPS:
        return (rank, x["name"].lower(), 0)
    if g == "Drums & Percussion" and x["id"] in DRUM_ORDER:
        return (rank, "", DRUM_ORDER.index(x["id"]))
    return (rank, "", _WRITTEN_POS[x["id"]])


EQ_DATA.sort(key=_list_order_key)

# Vocals LAST in the Selected Instruments panel (his wish, v3.24): the picker keeps
# them first, the panel on the right shows the band first and the singers at the end.
INST_GROUP = {x["id"]: x["group"] for x in EQ_DATA}


def vocals_last(ids):
    """`ids` with the Vocals group moved to the end; everything else keeps its order."""
    ids = list(ids)
    return ([i for i in ids if INST_GROUP.get(i) != "Vocals"]
            + [i for i in ids if INST_GROUP.get(i) == "Vocals"])

# ---- BED / LEAD PAIRS ------------------------------------------------------
# The same instrument in two roles: a FILLER that holds the harmony down, and a
# MELODY LINE that carries the tune. They want opposite EQ — that is why each
# pair is two entries in the chart and not one entry with a footnote. Every
# place that has something to say about "the same instrument twice" reads this
# tuple, so adding a fourth pair is one line here plus the two EQ_DATA cards.
#   (bed id, lead id, high-pass the LEAD when the bed plays too, what to say)
BED_LEAD_PAIRS = (
    ("organ", "organ_lead", 250.0,
     "The bed keeps the low drawbars and the rotary width; high-pass the lead at 200–300 Hz, "
     "cut its 300–600 Hz harder, and let ONLY the lead own 1–3 kHz. Same side of the stage — "
     "it is one player, not two."),
    ("organ", "organ_melody", 200.0,
     "The bed keeps the low drawbars and the rotary width; the melody organ high-passes at about "
     "200 Hz, cuts 300–600 Hz a little harder and owns part of 1–3 kHz with the singer. Same "
     "side of the stage — it is one player, not two."),
    ("brass", "brass_lead", 200.0,
     "Stabs and a tune are not the same job. The stabs keep the 200–400 Hz body and the 2–5 kHz "
     "punch; the melody line gives that body away and buys 1.5–3 kHz with it, and cuts the "
     "500 Hz–1 kHz honk far harder than any stab needs."),
    ("string_section", "strings_lead", 160.0,
     "The bed is allowed the 8–14 kHz silk and the long hall — that is exactly what makes it "
     "sound big and far away. A melody must not be far away: half the air, half the reverb, and "
     "a 1–3 kHz note core the bed does not even have a band for."),
    ("accordion", "accordion_lead", 120.0,
     "The padding accordion keeps the left-hand reeds and lives on the 800 Hz–2 kHz wash; the "
     "lead gives the body away and LIFTS that same reed core the padding card cuts. If both "
     "play, one of them has to stop playing the bass side — that is an arrangement fix, not EQ."),
    # NOTE the direction: here the LEAD is the card that already existed. A
    # Flute card that says "Transverse flute / solo" IS the melody entry, so
    # what was missing was the bed, not the lead.
    ("flute_bg", "flute", 300.0,
     "The bed keeps the breath BODY and gives up the 4–8 kHz breath and the air — which is "
     "precisely what the solo card is built on. Held for four bars, that breath is hiss. Dip "
     "3–5 kHz on the bed so the singer, and the solo flute, still cut through."),
    ("violin_bg", "violin", 250.0,
     "One band tells the whole story: the Violin card BOOSTS 1–3 kHz +3 and the bed CUTS it −3. "
     "A held violin carrying the solo curve is the reason a tune underneath it disappears."),
    ("viola", "viola_front", 150.0,
     "The same player in two roles: the bed keeps the dark 200-500 Hz body and gives up 1.5-3 kHz; "
     "the front viola owns 1.5-3 kHz and is placed like a solo violin. One player, one side of the stage."),
)

# Build lookup by group
GROUPS = []
GROUP_MAP = {}
for inst in EQ_DATA:
    g = inst["group"]
    if g not in GROUP_MAP:
        GROUPS.append(g)
        GROUP_MAP[g] = []
    GROUP_MAP[g].append(inst)

TYPE_LABEL = {
    "boost":   "BOOST",
    "cut":     "CUT",
    "char":    "TRY",
    "neutral": "NEUTRAL",
}
TYPE_COLOR = {
    "boost":   C_BOOST,
    "cut":     C_CUT,
    "char":    C_CHAR,
    "neutral": C_NEUTRAL,
}

# ---- FREQUENCY BAND INFO (for the clickable band bar) -----------------------
# Each band: name, range_str, color, characteristics, instruments, danger,
#            corrective (list of tips), enhancement (list), creative (list),
#            additive_note, subtractive_note

FREQ_BAND_DATA = {
    "sub": {
        "name":        "Sub-Bass",
        "range":       "20 – 60 Hz",
        "color":       "#a855f7",
        "char":        (
            "Physical sensation more than sound — felt through a subwoofer or "
            "a club system more than consciously heard through speakers. "
            "The power, rumble, and chest-punch of an 808 or deep synth bass lives here."
        ),
        "instruments": [
            "808s and synth subs",
            "Sub-kick reinforcement",
            "Deep synth bass fundamentals",
        ],
        "danger": (
            "Too much sub creates a flabby, undefined low end that eats headroom. "
            "On laptop speakers or earbuds this range is often completely inaudible — "
            "a sub-heavy mix will sound thin on small speakers. "
            "High-pass filtering most non-bass instruments below 60 Hz is standard practice."
        ),
        "corrective": [
            "High-pass filter everything except kick, bass, and sub synths below 40–60 Hz.",
            "Remove sub-rumble from room mics, overheads, and guitars.",
        ],
        "enhancement": [
            "A gentle boost on the kick or bass around 50–60 Hz adds weight on systems that can reproduce it.",
        ],
        "creative": [
            "Sub-bass synthesis: layer a pure sine wave an octave below a bass note for an 808-style sub.",
        ],
        "additive_note":     "Use sparingly — large boosts eat headroom fast.",
        "subtractive_note":  "High-pass most instruments here. Preferred approach.",
    },
    "bass": {
        "name":        "Bass",
        "range":       "60 – 250 Hz",
        "color":       "#3b82f6",
        "char":        (
            "The bottom of your mix — the thump, boom, and fatness that gives music "
            "weight and impact. Bass guitar body, kick drum fundamentals, and the "
            "low-end warmth of piano all live primarily in this region."
        ),
        "instruments": [
            "Kick drum fundamental (60–80 Hz)",
            "Bass guitar body (80–200 Hz)",
            "Piano low notes",
            "Synth bass",
        ],
        "danger": (
            "Too much energy in the 100–200 Hz region causes a boomy, overwhelming low end "
            "where kick and bass mask each other. "
            "One of the most common problems in untreated home studio rooms, where bass "
            "frequencies build up in corners and cause artificial-sounding peaks."
        ),
        "corrective": [
            "Cut 200–300 Hz on bass guitar to clean up the overlap with the kick drum.",
            "Notch out any resonant boom from the room (often 80–150 Hz).",
        ],
        "enhancement": [
            "Boost 60–80 Hz on kick for deep thump.",
            "Boost 60–100 Hz on bass guitar for body and weight.",
        ],
        "creative": [
            "A wide boost around 100 Hz can give synth bass a 'pillowy' vintage feel.",
        ],
        "additive_note":     "Wide Q (0.5–1). Coordinate kick and bass so they don't peak at the same Hz.",
        "subtractive_note":  "Cut narrow where boom or mud builds up (100–200 Hz).",
    },
    "lomid": {
        "name":        "Lo-Mid",
        "range":       "250 – 500 Hz",
        "color":       "#06b6d4",
        "char":        (
            "If your mix sounds 'muddy', this is almost certainly where the problem is hiding. "
            "Responsible for both the warmth of instruments and the dreaded 'cardboard box' "
            "sound that plagues amateur recordings."
        ),
        "instruments": [
            "Snare drum body and boxiness",
            "Vocal warmth and mud",
            "Guitar lower midrange",
            "Piano lower register",
            "Bass guitar mud zone",
        ],
        "danger": (
            "The single most common culprit for a muddy mix. "
            "When every instrument has untouched energy between 250–500 Hz, "
            "they all compete for the same space and none cut through clearly. "
            "Strategic cuts here — 'mud cuts' — are one of the most powerful "
            "and immediate mix-cleanup moves available."
        ),
        "corrective": [
            "Cut 300–500 Hz on kick to remove 'cardboard box' sound.",
            "Cut 250–400 Hz on snare to remove hollow, boxy tone.",
            "Cut 200–400 Hz on bass guitar — the classic mud zone.",
            "Cut 100–250 Hz on rhythm guitar to remove low-mid boom.",
        ],
        "enhancement": [
            "A slight boost (1–2 dB) around 300–400 Hz can add warmth to acoustic guitar or vocals.",
        ],
        "creative": [
            "A bandpass centred around 300–500 Hz gives a 'telephone' or vintage midrange character.",
        ],
        "additive_note":     "Use very carefully — this range fills up fast.",
        "subtractive_note":  "Most powerful tool here. Narrow Q (2–4) for surgical mud removal.",
    },
    "mid": {
        "name":        "Midrange",
        "range":       "500 Hz – 2 kHz",
        "color":       "#10b981",
        "char":        (
            "Where the character of most instruments truly lives — and where the human voice "
            "sits most prominently. Our ears are highly attuned to this range, making it both "
            "the most expressive and most problematic frequency region in a mix."
        ),
        "instruments": [
            "Vocals (fundamental body)",
            "Electric guitars (character)",
            "Synths and keyboards",
            "Snare midrange presence",
            "Bass guitar attack and grind",
        ],
        "danger": (
            "Buildup around 800 Hz–1.5 kHz produces the classic 'honky' sound — "
            "like cupping your hands over your mouth. "
            "Too many elements competing here creates a dense, congested, fatiguing mix."
        ),
        "corrective": [
            "Cut 500–800 Hz on guitars to remove 'honky' nasal tone.",
            "Cut 700 Hz–1 kHz on bass guitar if the pick/finger attack is too pronounced.",
        ],
        "enhancement": [
            "Boost 1–2 kHz on lead guitar to give the solo a strong 'voice' in the mix.",
            "Boost 800 Hz–1 kHz on bass guitar for audibility on small speakers.",
        ],
        "creative": [
            "A narrow boost at 1 kHz on vocals can give a retro AM-radio character.",
        ],
        "additive_note":     "Boosts here add forwardness and presence — very audible.",
        "subtractive_note":  "Cuts here fix honk, congestion, and 'boxy' character.",
    },
    "himid": {
        "name":        "Hi-Mid",
        "range":       "2 – 6 kHz",
        "color":       "#f59e0b",
        "char":        (
            "The most sensitive region of human hearing — where our ears are naturally most acute, "
            "an evolutionary adaptation for understanding speech. "
            "Presence, attack, clarity, and edge live here. "
            "Also where listening fatigue and harshness breed fastest."
        ),
        "instruments": [
            "Vocal clarity and intelligibility",
            "Snare snap (4–7 kHz)",
            "Guitar pick attack and bite",
            "Piano transients",
            "Kick drum beater click (2–4 kHz)",
        ],
        "danger": (
            "Because our ears are so sensitive here, even modest boosts can quickly produce "
            "a fatiguing, sharp sound. This zone is most responsible for listeners feeling "
            "'tired' after a session. A gentle cut somewhere between 3–5 kHz is the classic "
            "fix for a harsh mix."
        ),
        "corrective": [
            "Cut 3–5 kHz to tame harshness and listening fatigue.",
            "Cut 6–8 kHz on cymbals if they sound piercing.",
            "Use a de-esser around 5–8 kHz to control vocal sibilance.",
        ],
        "enhancement": [
            "Boost 2–4 kHz on kick to bring out beater click on small speakers.",
            "Boost 1–3 kHz on snare for crack and cut through guitars.",
            "Boost 3–5 kHz on lead guitar to cut through the full mix.",
        ],
        "creative": [
            "Emphasising 3–5 kHz heavily creates an aggressive, 'in your face' rock character.",
        ],
        "additive_note":     "Wide Q (0.7–1.5). Even +1–2 dB is very audible here.",
        "subtractive_note":  "Narrow Q for sibilance and resonance. Broad cut for fatigue.",
    },
    "highs": {
        "name":        "Highs",
        "range":       "6 – 20 kHz",
        "color":       "#ef4444",
        "char":        (
            "Shimmer, definition, sparkle, and 'air'. "
            "A well-executed high-shelf boost above 10 kHz is a hallmark of polished, "
            "expensive-sounding productions and can transform a flat vocal or mix "
            "into something that breathes and opens up."
        ),
        "instruments": [
            "Cymbals and hi-hats (sizzle and air)",
            "Vocal breathiness and sibilance (6–8 kHz)",
            "Acoustic guitar sparkle",
            "Orchestral strings shimmer",
        ],
        "danger": (
            "Excess above 8 kHz sounds hissy, brittle, and piercing. "
            "Sibilance — the harshness on 's' and 'sh' sounds in vocals — "
            "lives around 6–8 kHz and is best managed with a de-esser or dynamic EQ "
            "rather than a static cut that dulls the overall top end."
        ),
        "corrective": [
            "High-shelf cut above 12–16 kHz to reduce digital harshness or tape hiss.",
            "Narrow cut at 6–8 kHz for vocal sibilance (or use a de-esser).",
        ],
        "enhancement": [
            "High-shelf boost +1–2 dB above 10 kHz adds 'air' and openness to vocals.",
            "Boost 8–12 kHz on cymbals/overheads for shimmer and definition.",
            "Boost 10 kHz+ on hi-hat for airy openness.",
        ],
        "creative": [
            "An extreme high-shelf boost (+6–10 dB) combined with saturation gives a "
            "hyped, modern pop/electronic top-end sheen.",
            "A steep low-pass filter at 8–12 kHz creates a lo-fi, vintage telephone effect.",
        ],
        "additive_note":     "High-shelf is most common here. Keep boosts gentle (1–3 dB).",
        "subtractive_note":  "High-shelf cut or low-pass filter to control harshness.",
    },
}

class _PairedDict(dict):
    """A table whose lookups first look in `layer`.

    v3.25: parts the user has put in a PAIR (Song Variants, Pair + Prio) share ONE
    level. The base table below stays exactly as written; the pair layer is filled
    in by EQApp._pair_sync() for the parts that are ticked and paired, and every
    existing .get() / [] in the program sees it without being touched."""

    def __init__(self, *a, **k):
        dict.__init__(self, *a, **k)
        self.layer = {}

    def get(self, key, default=None):
        if key in self.layer:
            return self.layer[key]
        return dict.get(self, key, default)

    def __getitem__(self, key):
        if key in self.layer:
            return self.layer[key]
        return dict.__getitem__(self, key)

    def base(self, key, default=None):
        """The table's own answer, ignoring the pair layer."""
        return dict.get(self, key, default)


# *************** DEL 02b - SMART:EQ GROUP PLACEMENT **************************
# Sonible smart:EQ 4's cross-channel ("group") feature resolves masking
# automatically, but it needs to know WHO WINS when two members overlap — a
# priority ranking. That ranking is a discrete ARRANGEMENT decision (a role),
# not a frequency curve, so the cheat sheet can advise it exactly:
#   front = high priority  → stays present; others yield to it
#   mid   = supporting layer
#   back  = low priority    → carved to make room (pads, beds, background)
# This is NOT spatial placement (pan/depth) and NOT ducking — see the Help.
SMARTEQ_GROUP = _PairedDict({
    # id: (tier, role note)
    "vocals_lead":      ("front", "The reference element — everything yields to it in the mids."),
    "vocals_backing":   ("back",  "Support; rank below the lead so the lead stays clear."),
    "vocals_choir_pad": ("back",  "Held vocal pad; yields to the lead vocal."),
    "vocals_extra":     ("back",  "Ooh/aah, whisper or trailing word; it is colour, so it yields to the lead and to the backing vocals."),
    "kick":             ("front", "Owns the low thump. Split 60–100 Hz with the bass AND sidechain (smart:EQ won't fix the time-domain low-end clash)."),
    "snare":            ("front", "Backbeat anchor — its crack must stay up front."),
    "hihat":            ("mid",   "Rhythmic top; not masking-critical."),
    "ride":             ("mid",   "Timekeeper used instead of the hi-hat → MID, like the hat. (Occasional wash/crash instead? Use Cymbals = Back.)"),
    "cymbals":          ("back",  "Crash/overhead wash — air/top; let it yield. BUT a RIDE carrying the rhythm is a timekeeper → treat it like the hi-hat: MID, not Back."),
    "toms":             ("mid",   "Fills; mid priority."),
    "percussion":       ("back",  "Texture; yields."),
    "hand_drums":       ("mid",   "A real rhythm part with a real fundamental \u2014 mid tier, not "
                                  "texture. Splits the low mids with the toms."),
    "bass_root":        ("front", "Owns the low foundation (and Front overall if the bass is your lead). Split 60–100 Hz with the kick AND sidechain."),
    "bass_loop":        ("mid",   "Yields to the root bass in the lows."),
    "guitar_rhythm":    ("mid",   "Rhythmic bed; mid priority."),
    "guitar_chords":    ("mid",   "Harmonic bed; mid (drop to Back if it's just a wash)."),
    "guitar_lead":      ("front", "Lead/solo — rank high when it plays."),
    "guitar_single_low":("mid",   "Supporting line."),
    "guitar_acoustic":  ("mid",   "Texture layer in a band. Push it to FRONT when the acoustic IS the arrangement (solo/duo); drop it to BACK when it is only strummed glue behind electrics."),
    "organ":            ("back",  "Sustained bed; yields to vocals/leads. (Playing the TUNE on it? That is the Organ (lead) entry, and it is not a Back part.)"),
    "organ_lead":       ("mid",   "Melody line — MID so it still yields to the vocal, FRONT only in the bars where the organ carries the tune. Same rule as the saxophone."),
    "organ_melody":     ("mid",   "A line or harmony among other lines - MID, so it neither hides behind the vocal like a bed nor pushes in front of it like a lead."),
    "accordion_lead":   ("mid",   "The accordion carrying the tune — MID against a vocal, FRONT in the bars where the reeds ARE the song."),
    "flute_bg":         ("back",  "A held flute is a bed and ranks like one. (The plain Flute card is the solo and stays MID.)"),
    "violin_bg":        ("back",  "A held violin is a bed — this is the 'Back if it's a sustained bed' case the Violin card only mentions in passing."),
    "accordion":        ("mid",   "Mid-range bed by default. Push it to FRONT when the accordion carries the melody; drop it to BACK when it is only chordal padding behind a vocal."),
    "piano_bg":         ("back",  "Background comp; yields."),
    "piano_riff":       ("mid",   "Hook; mid (push to Front when it IS the hook)."),
    "flute":            ("mid",   "Melodic; mid priority."),
    "brass":            ("mid",   "Section stabs; mid. (Horns playing the TUNE? That is Brass (lead).)"),
    "brass_lead":       ("mid",   "The horns carrying the melody — MID against a vocal, FRONT in the bars where the line IS the song. Same rule as the trumpet."),
    "trumpet":          ("mid",   "Loud melodic line — MID by default because it must yield to the vocal. Push to FRONT only in the sections where the trumpet carries the tune."),
    "trombone":         ("mid",   "Low horn line; mid. Its real fight is with the bass in 100–600 Hz, not with the vocal."),
    "tenor_trombone":         ("mid",   "Low horn line; mid. Its real fight is with the bass in 100–600 Hz, not with the vocal."),
    "tenor_bass_trombone":         ("mid",   "Low horn line; mid. Its real fight is with the bass in 100–600 Hz, not with the vocal."),
    "saxophone":        ("mid",   "Behaves like a second vocal — MID so the real singer wins. FRONT only during a sax solo."),
    "horn_section":     ("mid",   "The section as one body. Rank the SECTION here and leave the individual horns unranked, or you spend three slots on one idea."),
    "harmonica":        ("mid",   "Answer-phrase instrument; mid. It lands on the vocal's 2–4 kHz, so it yields whenever the singer is in."),
    "woodwind":         ("mid",   "Reed line; mid."),
    "clarinet":         ("mid",   "Reed line sharing the vocal's lower half; mid, and it yields to the singer."),
    "oboe":             ("mid",   "Cuts through everything at 1-4 kHz; mid by default, FRONT only in the bars where the oboe really is the tune."),
    "bassoon":          ("mid",   "Tenor/bass reed voice; mid, yields to the bass guitar for 100-250 Hz."),
    "contrabassoon":    ("mid",   "Low colour under the cellos; mid, and it yields to the real bass."),
    "flugelhorn":       ("mid",   "Mellow horn line; mid so the vocal wins, FRONT only for a flugelhorn solo."),
    "french_horn":      ("mid",   "Glue of the brass section; mid."),
    "tuba":             ("mid",   "Low brass support; yields to the root bass and the kick."),
    "english_horn":     ("mid",   "Dark colour line, quieter than an oboe; mid, and it yields to the vocal."),
    "euphonium":        ("mid",   "Tenor brass line; mid, its real fight is with the bass and trombone."),
    "bass_clarinet":    ("mid",   "Low reed colour; mid, yields to the bass."),
    "contrabass_clarinet": ("mid", "Low colour under the clarinets; mid, and it yields to the real bass."),
    "double_bass_section": ("mid", "Low support from a whole desk; yields to the root bass."),
    "piccolo": ("mid", "Shrill and piercing; mid, and it yields to the vocal."),
    "alto_flute": ("mid", "Quiet and dark; mid, and it needs help to be heard."),
    "bass_flute": ("mid", "The quietest flute; mid, and it needs presence not volume."),
    "soprano_sax": ("mid", "Behaves like a second vocal - MID so the real singer wins. FRONT only during a soprano solo."),
    "alto_sax": ("mid", "Behaves like a second vocal - MID so the real singer wins. FRONT only during a sax solo."),
    "tenor_sax": ("mid", "Behaves like a male voice - MID so the real singer wins. FRONT only during a tenor solo."),
    "baritone_sax": ("mid", "Low reed; mid, and it yields to the bass for 100-250 Hz."),
    "piccolo_trumpet": ("mid", "Loud and bright; mid, and it must yield to the vocal."),
    "alto_trombone": ("mid", "Bright bone line; mid, yields to the vocal and the trumpet."),
    "bass_trombone": ("mid", "Low brass line; mid, its real fight is with the bass guitar."),
    "double_bass_trombone": ("mid", "Low brass line; mid, its real fight is with the bass guitar."),
    "synth_pad":        ("back",  "The classic 'make room' pad — lowest priority."),
    "synth_pluck":      ("mid",   "Rhythmic/melodic stab; mid."),
    "synth_mallet":     ("mid",   "Bell line; mid."),
    "strings_lead":     ("mid",   "A string melody — MID so the singer still wins; FRONT when the section carries the tune on its own."),
    "violin":           ("mid",   "Melodic; mid (Back if it's a sustained bed)."),
    "viola":            ("mid",   "A viola is the violin's PARTNER: MID like it, so it neither yields to the violin nor ends up behind it. (A held bed of violas? Use String Section or Violin (bg) = Back.)"),
    "viola_front":      ("mid",   "A viola with the tune: MID like a solo violin; FRONT if it carries the tune alone."),
    "cello":            ("mid",   "Low-mid support."),
    "double_bass":      ("mid",   "Low support; yields to the root bass."),
    "string_section":   ("back",  "Lush bed; yields."),
})

# Tier glyph, colour, label (colours reuse the app palette).
SMARTEQ_TIER = {
    "front": ("▲", C_BOOST,   "FRONT"),   # high priority — green
    "mid":   ("■", C_ACCENT,  "MID"),     # supporting   — blue
    "back":  ("▼", C_NEUTRAL, "BACK"),    # yields       — gray
}


# ---- PARTNER-DEPENDENT NOTES -----------------------------------------------
# Some advice only makes sense when a PARTNER instrument is actually in the song
# ("split 60–100 Hz with the kick", "pair with the kick sidechain"). In a song
# with bass and piano and no drums at all, that advice is simply wrong. Each
# entry maps (table, instrument) -> (partner ids, the note to print INSTEAD when
# none of those partners is in the song). With no selection at all (reference
# mode) the original note is always used.
PARTNER_NOTES = {
    ("smarteq", "kick"): (
        ("bass_root", "bass_loop", "double_bass", "double_bass_section"),
        "Owns the low thump. No bass part in this song, so there is nothing to "
        "split 60–100 Hz with — let the kick have the low end."),
    ("smarteq", "bass_root"): (
        ("kick",),
        "Owns the low foundation outright — no kick in this song, so nothing "
        "shares 60–100 Hz with it and there is nothing to side-chain to. Keep "
        "it mono and let it carry the bottom alone."),
    ("smarteq", "bass_loop"): (
        ("bass_root",),
        "The only bass part here — treat it as the foundation rather than as a "
        "second layer."),
    ("comp", "kick"): (
        ("bass_root", "bass_loop", "double_bass", "double_bass_section"),
        "Slow attack (20–30 ms) keeps the beater click; medium release for "
        "groove. Or skip comp and just clip the peaks."),
    ("comp", "bass_root"): (
        ("kick",),
        "Consistency is everything — every note the same level. There is no "
        "kick to side-chain against, so the compressor alone keeps the low end "
        "steady. Multiband if only the lows jump."),
    # The 💡 card tips that name a partner instrument.
    ("tip", "kick"): (
        ("bass_root", "bass_loop", "double_bass", "double_bass_section"),
        "High-pass below 40 Hz. Cut 300–500 Hz to fix 'boxiness'. No bass part "
        "in this song, so the kick has the low end to itself — nothing to "
        "side-chain against it."),
    ("tip", "bass_root"): (
        ("kick",),
        "High-pass below 30–40 Hz. With no kick in the song the bass owns the "
        "whole low end on its own — keep it mono and even (compression, not "
        "ducking), and nothing needs to take turns down there."),
    ("tip", "bass_loop"): (
        ("kick",),
        "No kick here, so nothing fights it in the lows: high-pass it and let "
        "the bass line carry the bottom. Keep 500 Hz–3 kHz for the riff so it "
        "still speaks on small speakers."),
    ("tip", "vocals_choir_pad"): (
        ("vocals_lead",),
        "It needs its OWN EQ — not the lead-vocal recipe. Treat it like an "
        "organ pad made of voices: tame 400–800 Hz mud, then add air. There is "
        "no lead vocal in this song, so nothing has to be carved out of it — "
        "let the pad be the voice."),
}


def partner_note(table, iid, note, selected_ids):
    """Swap in the 'partner is missing' wording when the note names a partner
    instrument that is not in this song. selected_ids None/empty = reference
    mode, where the full note always stands."""
    if not selected_ids or iid not in selected_ids:
        return note
    entry = PARTNER_NOTES.get((table, iid))
    if not entry:
        return note
    partners, alt = entry
    return note if any(p in selected_ids for p in partners) else alt


def smarteq_group_for(iid, selected_ids=None):
    """Return (glyph, colour, label, note) for an instrument's smart:EQ group
    priority, or None if it has no entry. Pass the current selection to get the
    partner-aware wording (see partner_note)."""
    g = SMARTEQ_GROUP.get(iid)
    if not g:
        return None
    tier, note = g
    glyph, colour, label = SMARTEQ_TIER.get(tier, SMARTEQ_TIER["mid"])
    return glyph, colour, label, partner_note("smarteq", iid, note, selected_ids)


# *************** DEL 02d - DUCKING / SIDECHAIN (Trackspacer · Kickstart) *****
# smart:EQ group fixes SPECTRAL masking; it does NOT fix two parts colliding in
# TIME. Ducking does. Two tools the user owns:
#   • Wavesfactory TRACKSPACER — reactive 32-band EQ. Insert on the track that
#     should YIELD; feed the dominant part to its side-chain; it carves out
#     exactly the side-chain's frequencies, only while that part plays. Its
#     low-cut/high-cut sliders LIMIT the band it works in (default = full range:
#     low-cut at minimum, high-cut at maximum). Frequency-specific & transparent.
#   • Cableguys/Nicky Romero KICKSTART — tempo-synced VOLUME duck (a beat-locked
#     curve, NOT side-chain-triggered). Zero routing, but only musical when the
#     trigger (the kick) is steady on the beat. Broadband (ducks the whole level).
# Rule of thumb baked in below:
#   - duck-under-KICK  → Trackspacer with HIGH-CUT pulled to the lows, OR Kickstart
#                        (if the kick is on the beat).
#   - duck-under-VOCAL → Trackspacer only (a voice isn't metronomic, so Kickstart
#                        does not apply).
# IMPORTANT — START GENTLE (these Amounts are intentionally LOW): ducking is far
# easier to over-do than to under-do. Begin at the LOW end of the range and raise
# it only until you JUST notice the masked part open up. If the ducked part (a
# guitar, a bass) seems to DISAPPEAR or pump, you have gone too far — pull the
# Amount back down. You rarely need more than ~20%; a value of 30–40% will usually
# swallow the part whole. When in doubt, less is better.
# A DUCK IS ONLY ADVICE IF THE SOURCE IS ACTUALLY IN THE SONG. "Duck the bass
# under the kick" is nonsense in a song that has no kick (bass + piano only) —
# so every duck names the instrument id(s) that can trigger it (DUCK_SOURCE_IDS
# below) and every view filters on the current selection. See ducking_for().
# Fields per instrument:
#   src  = what to side-chain to (also names the header)
#   set  = the key Trackspacer numbers — shown in COLLAPSED (Low cut/band + Amount)
#   why  = one-line reason (EXPANDED only)
#   kickstart = optional Kickstart note (EXPANDED only; usually just Trackspacer)
DUCKING = {
    # vs the KICK (take turns in the low end)
    "bass_root": {"src": "Kick",
        "set": "High Cut ~150 Hz · Amount ~12–20% (start at 12)",
        "why": "High Cut ~150 Hz so ONLY the 60–100 Hz clash ducks, not the whole bass. Raise only until the kick pokes through — if the bass vanishes, back off.",
        "kickstart": "On-beat kick? 'Classic' curve, 1/4 notes, gentle depth — no routing."},
    "bass_loop": {"src": "Kick",
        "set": "High Cut ~150 Hz · Amount ~12–18% (start at 12)",
        "why": "Only the low clash with the kick ducks. Keep it subtle — too much and the loop disappears.",
        "kickstart": "On-beat kick? 'Classic' curve, 1/4 notes, gentle depth."},
    "double_bass": {"src": "Kick",
        "set": "High Cut ~150–200 Hz · Amount ~10–18% (start at 10)",
        "why": "Keep it to the low end and gentle.",
        "kickstart": "On-beat kick? 'Classic' curve, 1/4 notes, light depth."},
    # vs the LEAD VOCAL (open up under the voice) — Trackspacer only
    "vocals_backing": {"src": "Lead Vocal",
        "set": "Band 250 Hz–6 kHz · Amount ~12–18% (start at 12)",
        "why": "Focus the mids so the doubles open under the lead — a small amount is enough.",
        "kickstart": None},
    "vocals_choir_pad": {"src": "Lead Vocal",
        "set": "Band 300 Hz–6 kHz · Amount ~12–18%",
        "why": "Open the pad under the voice; keep it gentle so the pad still supports.",
        "kickstart": None},
    "vocals_extra": {"src": "Lead Vocal",
        "set": "Band 300 Hz–6 kHz · Amount ~15–22% (start at 15)",
        "why": "Opens a hole under the lead, and the layer swells back up when the lead stops - which is exactly what a trailing word after a line wants.",
        "kickstart": None},
    "organ": {"src": "Lead Vocal",
        "set": "Band 300 Hz–5 kHz · Amount ~12–18%",
        "why": "Carve the vocal range out of the organ — only as much as you need to hear the words.",
        "kickstart": None},
    "accordion_lead": {"src": "Lead Vocal",
        "set": "Band 500 Hz–4 kHz · Amount ~15–22% (start at 15)",
        "why": "Harder than the padding accordion needs, because a reed melody sits right on the words and it is the one instrument here that sounds like a second singer.",
        "kickstart": None},
    "flute_bg": {"src": "Lead Vocal",
        "set": "Band 500 Hz–6 kHz · Amount ~12–18%",
        "why": "The plain Flute card has NO duck entry at all — a solo does not duck. A held one does: it is sitting in the singer's breath range for whole bars.",
        "kickstart": None},
    "violin_bg": {"src": "Lead Vocal",
        "set": "Band 500 Hz–5 kHz · Amount ~12–18%",
        "why": "Same reason as the flute bed: the solo Violin card never ducks, and a sustained one has to.",
        "kickstart": None},
    "brass_lead": {"src": "Lead Vocal",
        "set": "Band 500 Hz–5 kHz · Amount ~15–22% (start at 15)",
        "why": "A horn line is the loudest melodic thing in the mix and it sits on the voice. Duck the band the words need — and if it has to duck all the way through, the horns should be answering the singer, not playing over them.",
        "kickstart": None},
    "strings_lead": {"src": "Lead Vocal",
        "set": "Band 500 Hz–5 kHz · Amount ~15–20%",
        "why": "Less than the horns need, because a string line is smoother — but it is still a melody sitting where the words are.",
        "kickstart": None},
    "viola_front": {"src": "Lead Vocal",
        "set": "Band 500 Hz–5 kHz · Amount ~15–20%",
        "why": "A viola that carries the tune sits where the words are, a little less than the horns need because a string line is smoother.",
        "kickstart": None},
    "organ_lead": {"src": "Lead Vocal",
        "set": "Band 500 Hz–5 kHz · Amount ~15–22% (start at 15)",
        "why": "A lead organ sits exactly where the voice sits, and it is louder about it than the bed is — so it ducks harder. But if it has to duck through the whole song, the honest fix is arrangement: let it play in the gaps.",
        "kickstart": None},
    "organ_melody": {"src": "Lead Vocal",
        "set": "Band 400 Hz–5 kHz · Amount ~12–18% (start at 12)",
        "why": "Between the bed and the lead: it shares the voice's range for part of the time, so it ducks a little less than a lead organ - the point of this card is that it is allowed to stay audible while the singer sings.",
        "kickstart": None},
    "accordion": {"src": "Lead Vocal",
        "set": "Band 300 Hz–4 kHz · Amount ~12–20% (start at 12)",
        "why": "The accordion's reedy core sits right on top of the voice — duck exactly that band so the words come through, and leave the rest of the accordion alone.",
        "kickstart": None},
    "piano_bg": {"src": "Lead Vocal",
        "set": "Band 300 Hz–5 kHz · Amount ~10–15%",
        "why": "Very gentle — it's already in the background.",
        "kickstart": None},
    "synth_pad": {"src": "Lead Vocal",
        "set": "Band 300 Hz–5 kHz · Amount ~12–18%",
        "why": "Opens up under the voice; a light touch keeps the bed intact.",
        "kickstart": None},
    "string_section": {"src": "Lead Vocal",
        "set": "Band 300 Hz–5 kHz · Amount ~12–18%",
        "why": "Make a little room for the lead in the mids — don't gut the section.",
        "kickstart": None},
    "guitar_rhythm": {"src": "Lead Vocal",
        "set": "Band 500 Hz–4 kHz · Amount ~10–15% (only if it crowds)",
        "why": "Only if it crowds the voice — keep it small so the guitar doesn't pump or drop out.",
        "kickstart": None},
    "guitar_chords": {"src": "Lead Vocal",
        "set": "Band 500 Hz–4 kHz · Amount ~10–15% (only if it crowds)",
        "why": "Only if it crowds the voice — keep it small so the guitar doesn't pump or drop out.",
        "kickstart": None},
    "guitar_acoustic": {"src": "Lead Vocal",
        "set": "Band 500 Hz–5 kHz · Amount ~10–18% (start at 10)",
        "why": "A strummed acoustic covers the whole vocal range at once. Ducking exactly that band keeps the strum audible while the words come through — far kinder than EQ-ing the sparkle away.",
        "kickstart": None},
    "trumpet": {"src": "Lead Vocal",
        "set": "Band 1–6 kHz · Amount ~18–28% (start at 18)",
        "why": "The trumpet is louder than the singer in the exact band the singer needs. This is one of the few places a BIG duck is right — it only acts while the vocal sounds, so the horn stays full in the gaps.",
        "kickstart": None},
    "saxophone": {"src": "Lead Vocal",
        "set": "Band 800 Hz–6 kHz · Amount ~18–25% (start at 18)",
        "why": "A sax is effectively a second voice in the same range. Duck it firmly under the lead — or better, arrange it to answer between the lines instead of playing under them.",
        "kickstart": None},
    "harmonica": {"src": "Lead Vocal",
        "set": "Band 800 Hz–5 kHz · Amount ~18–25%",
        "why": "Small, loud and right on the voice. Duck it hard while the singer sings; it comes straight back for the answer phrases.",
        "kickstart": None},
    "horn_section": {"src": "Lead Vocal",
        "set": "Band 1–6 kHz · Amount ~15–25% — ONE Trackspacer on the horn BUS",
        "why": "Duck the whole section from one instance on its bus. Three separate duckers on three horns just means three different amounts of wrong.",
        "kickstart": None},
    "trombone": {"src": "Kick",
        "set": "High Cut ~250 Hz · Amount ~10–15% (start at 10)",
        "why": "A low horn line sits on the kick and bass, not on the vocal. Duck only its low end so the kick still lands — and if you also have a bass part, high-pass the bone instead of ducking it twice.",
        "kickstart": None},
    "tenor_trombone": {"src": "Kick",
        "set": "High Cut ~250 Hz · Amount ~10–15% (start at 10)",
        "why": "A low horn line sits on the kick and bass, not on the vocal. Duck only its low end so the kick still lands — and if you also have a bass part, high-pass the bone instead of ducking it twice.",
        "kickstart": None},
    "tenor_bass_trombone": {"src": "Kick",
        "set": "High Cut ~250 Hz · Amount ~10–15% (start at 10)",
        "why": "A low horn line sits on the kick and bass, not on the vocal. Duck only its low end so the kick still lands — and if you also have a bass part, high-pass the bone instead of ducking it twice.",
        "kickstart": None},
    "tuba": {"src": "Kick",
        "set": "High Cut ~200 Hz - Amount ~10-15% (start at 10)",
        "why": "A tuba sits on the kick and the bass, not on the vocal. Duck only its low end so the kick still lands - and if you also have a bass part, high-pass one of them instead of ducking twice.",
        "kickstart": None},
    "contrabassoon": {"src": "Kick",
        "set": "High Cut ~150 Hz - Amount ~10-15% (start at 10)",
        "why": "Keep it to the low end and gentle - the contrabassoon is a colour under the bass, not a bass line of its own.",
        "kickstart": None},
    "flugelhorn": {"src": "Lead Vocal",
        "set": "Band 1-5 kHz - Amount ~12-20% (start at 12)",
        "why": "A flugelhorn is quieter than a trumpet but sits on exactly the same part of the voice. A small duck is enough; it only acts while the vocal sounds.",
        "kickstart": None},
    "oboe": {"src": "Lead Vocal",
        "set": "Band 1.5-4 kHz - Amount ~15-22% (start at 15)",
        "why": "The oboe wins the 1-4 kHz fight with almost anything, so it has to be told to yield. It stays full in the gaps between the vocal lines.",
        "kickstart": None},
    "euphonium": {"src": "Kick",
        "set": "High Cut ~250 Hz - Amount ~10-15% (start at 10)",
        "why": "A low brass line sits on the kick and bass, not on the vocal. Duck only its low end so the kick still lands - and if you also have a bass part, high-pass one of them instead of ducking twice.",
        "kickstart": None},
    "contrabass_clarinet": {"src": "Kick",
        "set": "High Cut ~150 Hz - Amount ~10-15% (start at 10)",
        "why": "Keep it to the low end and gentle - a colour under the bass, not a bass line of its own.",
        "kickstart": None},
    "double_bass_section": {"src": "Kick",
        "set": "High Cut ~150-200 Hz - Amount ~10-18% (start at 10)",
        "why": "Keep it to the low end and gentle.",
        "kickstart": "On-beat kick? 'Classic' curve, 1/4 notes, light depth."},
    "piccolo": {"src": "Lead Vocal",
        "set": "Band 2-6 kHz - Amount ~12-18% (start at 12)",
        "why": "A piccolo is louder than the singer in the upper half of the voice. A small duck is enough; it only acts while the vocal sounds.",
        "kickstart": None},
    "soprano_sax": {"src": "Lead Vocal",
        "set": "Band 1-6 kHz - Amount ~18-25% (start at 18)",
        "why": "A soprano sax is effectively a second voice in the same range. Duck it firmly under the lead - or better, arrange it to answer between the lines.",
        "kickstart": None},
    "alto_sax": {"src": "Lead Vocal",
        "set": "Band 800 Hz-6 kHz - Amount ~18-25% (start at 18)",
        "why": "A sax is effectively a second voice in the same range. Duck it firmly under the lead - or better, arrange it to answer between the lines.",
        "kickstart": None},
    "tenor_sax": {"src": "Lead Vocal",
        "set": "Band 600 Hz-5 kHz - Amount ~15-22% (start at 15)",
        "why": "A tenor sax lands right on the male voice. Duck it under the lead, or write it to answer the phrases.",
        "kickstart": None},
    "baritone_sax": {"src": "Kick",
        "set": "High Cut ~200 Hz - Amount ~10-15% (start at 10)",
        "why": "A baritone sax sits on the kick and bass, not on the vocal. Duck only its low end so the kick still lands.",
        "kickstart": None},
    "piccolo_trumpet": {"src": "Lead Vocal",
        "set": "Band 1.5-6 kHz - Amount ~18-26% (start at 18)",
        "why": "A piccolo trumpet is louder than the singer in exactly the band the singer needs. This is one of the few places a BIG duck is right.",
        "kickstart": None},
    "bass_trombone": {"src": "Kick",
        "set": "High Cut ~250 Hz - Amount ~10-15% (start at 10)",
        "why": "A low bone sits on the kick and bass, not on the vocal. Duck only its low end so the kick still lands.",
        "kickstart": None},
    "double_bass_trombone": {"src": "Kick",
        "set": "High Cut ~250 Hz - Amount ~10-15% (start at 10)",
        "why": "A low bone sits on the kick and bass, not on the vocal. Duck only its low end so the kick still lands.",
        "kickstart": None},
}


# Which instrument id(s) can BE a given side-chain source. If none of them is in
# the song, the duck is not advice — it is noise, and it is hidden.
DUCK_SOURCE_IDS = {
    "Kick":       ("kick",),
    "Lead Vocal": ("vocals_lead",),
}


def duck_source_present(src, selected_ids):
    """True if the side-chain source 'src' exists in this selection. An unknown
    source name is never hidden (fail-open, so new sources still show)."""
    ids = DUCK_SOURCE_IDS.get(src)
    if not ids:
        return True
    return any(i in selected_ids for i in ids)


def ducking_for(iid, selected_ids=None):
    """Return the ducking advice dict for an instrument, or None.

    selected_ids = the instruments in the current song. Pass it and the duck is
    suppressed when its SOURCE is not in that song (no kick -> no 'duck the bass
    under the kick'). Pass None (the default) for reference mode, where every
    instrument card shows what it would duck under in a full arrangement."""
    d = DUCKING.get(iid)
    if not d:
        return None
    if selected_ids is not None and not duck_source_present(d["src"], selected_ids):
        return None
    return d


# ---- DEPTH (front/back via reverb send) ------------------------------------
# Spatial DEPTH is a reverb-SEND decision, not something an auto reverb decides.
# Sonible smart:reverb auto-tunes the reverb's CHARACTER; YOU still set how much
# each track sends = how far back it sits. Workflow (least hassle): one
# smart:reverb on an FX/send channel; vary each track's send by the tier below;
# let smart:reverb auto-tune the room. Low-end sources stay DRY (reverb on
# kick/bass = mud). Leads can take reverb if you add PRE-DELAY so words/notes
# stay clear and up front.
#   dry  = no/almost no send   near = light send   mid = medium   far = heavy
DEPTH = _PairedDict({
    "kick":             ("dry",  "Keep DRY — reverb on the kick muddies the low end."),
    "snare":            ("near", "Light send — a short room/plate adds snap-space; keep it tight."),
    "hihat":            ("near", "Light send."),
    "ride":             ("near", "Light send — like the hi-hat; keep the ping tight."),
    "cymbals":          ("mid",  "Medium send for crash/overhead air. A RIDE keeping time wants LESS — NEAR, like the hi-hat, so the ping stays tight."),
    "toms":             ("near", "Light send — a short room."),
    "percussion":       ("mid",  "Medium send for stereo space."),
    "hand_drums":       ("near", "Close, like the toms \u2014 they are being played in the room, "
                                 "not sprinkled over it."),
    "bass_root":        ("dry",  "Keep DRY — reverb on the bass muddies everything."),
    "bass_loop":        ("dry",  "Keep DRY."),
    "double_bass":      ("dry",  "Dry — a touch of short room at most."),
    "vocals_lead":      ("front", "The focal point — right up front (Distance ~15). Keep it very close/dry + pre-delay 60–120 ms so the words stay crisp; give it its OWN reverb instance (don't bury the lyrics)."),
    "vocals_backing":   ("far",  "More send — sits behind the lead, glued with space."),
    "vocals_choir_pad": ("far",  "Lots of space — it's a bed."),
    "vocals_extra":     ("far",  "Lots of space - it is colour, not words. A trailing word can take a little less than an ooh."),
    "guitar_rhythm":    ("near", "Light–medium send."),
    "guitar_chords":    ("mid",  "Medium send."),
    "guitar_lead":      ("mid",  "Medium send + pre-delay so it stays present in solos."),
    "guitar_single_low":("near", "Light send."),
    "guitar_acoustic":  ("near", "Light send — an acoustic is already full of its own body resonance; drown it and the strum turns to mush."),
    "organ":            ("mid",  "Medium send; keep some clarity."),
    "organ_lead":       ("near", "Light–medium send — LESS than the background organ. Same room (it is one player in one building), just less of it, so the line stays in front of its own pad."),
    "organ_melody":     ("near", "Light–medium send, the same room as the other organ - a little more than the lead organ gets, a little less than the bed, so the line sits between them in depth."),
    "accordion":        ("mid",  "Medium send — a little room keeps the reeds from sounding dry and boxy."),
    "accordion_lead":   ("near", "Light–medium send + pre-delay — less than the padding accordion, so the line keeps its edge."),
    "flute_bg":         ("far",  "Heavy send. A held flute is allowed the depth the solo flute is not — depth is most of what makes it read as a bed."),
    "violin_bg":        ("far",  "Heavy send — same reason: the bed gets the room, whatever carries the tune does not."),
    "piano_bg":         ("mid",  "Medium–more send — sits back."),
    "piano_riff":       ("near", "Light–medium send + pre-delay (it's a hook)."),
    "flute":            ("mid",  "Medium send."),
    "brass":            ("near", "Light–medium send — stabs stay punchy."),
    "brass_lead":       ("near", "Light–medium send + pre-delay 40–80 ms so the front of every note stays sharp — a wet horn line loses its consonants the same way a vocal does."),
    "trumpet":          ("near", "Light–medium send + pre-delay 40–80 ms so the attack of each note stays sharp."),
    "trombone":         ("near", "Light send — a wet trombone turns into low-mid soup."),
    "tenor_trombone":         ("near", "Light send — a wet trombone turns into low-mid soup."),
    "tenor_bass_trombone":         ("near", "Light send — a wet trombone turns into low-mid soup."),
    "saxophone":        ("mid",  "Medium send — a little room is what makes a sax sound played rather than sampled; use pre-delay so the reed attack survives."),
    "horn_section":     ("near", "Light–medium send, ONE send for the whole section bus — a shared room is exactly what makes three horns sound like one section."),
    "harmonica":        ("mid",  "Medium send (plus a slap delay if it is answering the vocal) — space is most of the classic harp sound."),
    "woodwind":         ("mid",  "Medium send."),
    "clarinet":         ("mid",  "Medium send; a clarinet wants a little hall around the hollow tone. Pre-delay 20-40 ms keeps the reed attack."),
    "oboe":             ("mid",  "Medium send; pre-delay 30-50 ms so the reed does not wash. Too much room and the nasal core blurs."),
    "bassoon":          ("near", "Light-medium send - a wet bassoon turns into low-mid soup."),
    "contrabassoon":    ("dry",  "Dry - a touch of short room at most; reverb on a contrabassoon is low-end mud."),
    "flugelhorn":       ("near", "Light-medium send with pre-delay 40-80 ms so the attack stays clear - a flugelhorn is already round."),
    "french_horn":      ("mid",  "Medium send - the horn's bell points backwards, so a bit of room is part of its tone."),
    "tuba":             ("dry",  "Dry - a touch of short room at most; reverb on a tuba covers the bass guitar."),
    "english_horn":     ("mid",  "Medium send; pre-delay 30-50 ms so the reed does not wash."),
    "euphonium":        ("near", "Light-medium send - a wet euphonium turns into low-mid soup."),
    "bass_clarinet":    ("near", "Light-medium send - the low register blurs quickly in a long reverb."),
    "contrabass_clarinet": ("dry", "Dry - a touch of short room at most; reverb on a contrabass clarinet is low-end mud."),
    "double_bass_section": ("dry", "Dry - a touch of short room at most; the section already carries its own space. Keep the lows out of any reverb send."),
    "piccolo": ("mid", "Medium send, short room; a long hall makes the shrill top worse."),
    "alto_flute": ("mid", "Short, light room - a wet alto flute disappears."),
    "bass_flute": ("near", "Light, short room; a long hall buries it."),
    "soprano_sax": ("mid", "Medium send; a little room makes a sax sound played rather than sampled. Pre-delay keeps the reed attack."),
    "alto_sax": ("mid", "Medium send; a little room makes a sax sound played rather than sampled. Pre-delay keeps the reed attack."),
    "tenor_sax": ("mid", "Medium send; a little room makes a sax sound played rather than sampled. Pre-delay keeps the reed attack."),
    "baritone_sax": ("near", "Light-medium send - a wet baritone is low-mid soup."),
    "piccolo_trumpet": ("near", "Light-medium send with pre-delay 40-80 ms so the attack stays sharp."),
    "alto_trombone": ("near", "Light send - a wet trombone turns into low-mid soup."),
    "bass_trombone": ("near", "Light send - a wet bass trombone covers the bass guitar."),
    "double_bass_trombone": ("near", "Light send - a wet double-bass trombone covers the bass guitar."),
    "synth_pad":        ("far",  "Heavy send — the deepest bed."),
    "synth_pluck":      ("mid",  "Medium send; ping-pong delay also adds depth."),
    "synth_mallet":     ("mid",  "Medium send."),
    "strings_lead":     ("near", "Light–medium send + pre-delay. The string BED is the one thing allowed a long hall; put a melody in that hall and it stops being a melody."),
    "violin":           ("mid",  "Medium send."),
    "viola":            ("mid",  "Medium send, the same as the violin: the two are partners and must sit at the same depth. (A lush bed? Use String Section or Violin (bg).)"),
    "viola_front":      ("near", "Light–medium send: a viola with the tune must not sit in the bed's long hall."),
    "cello":            ("mid",  "Medium send."),
    "string_section":   ("far",  "Lush and deep — heavy send."),
})

# Per-tier smart:reverb starting NUMBERS (Distance & Size on a 0–100 scale;
# smart:reverb's Size default is ≈40). KEY: LOW Distance = near / up front,
# HIGH Distance = far back. Character on the Room↔Hall axis (Spring/Plate are
# vintage effect colours, not natural depth).
DEPTH_COLOUR = "#9fe0e0"   # cyan, distinct from the green smart:EQ line
# Width (default ≈80) = stereo spread of the reverb; narrower keeps centred
# sources focused, wider suits stereo beds. These are per-tier starting points.
DEPTH_SPEC = {
    "dry":   {"label": "DRY",   "plain": "no reverb",        "distance": None, "size": None, "width": None, "char": None},
    "front": {"label": "FRONT", "plain": "right up front",   "distance": 15,   "size": 25,   "width": 60,   "char": "Room"},
    "near":  {"label": "NEAR",  "plain": "close, up front",  "distance": 25,   "size": 30,   "width": 70,   "char": "Room"},
    "mid":   {"label": "MID",   "plain": "mid-depth",         "distance": 50,   "size": 40,   "width": 80,   "char": "Room↔Hall"},
    "far":   {"label": "FAR",   "plain": "far back",          "distance": 78,   "size": 65,   "width": 95,   "char": "Hall"},
}


def depth_for(iid):
    """Return (tier, spec_dict, note) for an instrument's reverb-depth, or None.
    spec has: label, plain, distance, size, char (numbers are starting points)."""
    d = DEPTH.get(iid)
    if not d:
        return None
    tier, note = d
    return tier, DEPTH_SPEC.get(tier, DEPTH_SPEC["mid"]), note


# ---- LEAD VOCAL ON ITS OWN (decided 2026-10-21) ----------------------------
# With backing vocals the lead stays dry and the backing wash behind it makes the
# depth - the contrast does the work. A lead with NO other voice has nothing to be
# contrasted with, so it has to carry the room itself: a little more reverb and a
# little more echo. Everything else about the lead (EQ, compressor, stage
# position, smart:EQ tier) is the same either way. "Company" = any other vocal
# layer in the song.
LEAD_COMPANY = ("vocals_backing", "vocals_extra", "vocals_choir_pad")
LEAD_ALONE_DEPTH = {"distance": 6, "size": 8}
LEAD_ALONE_NOTE = ("Lead vocal on its own: no backing vocals to make the depth "
                   "behind it, so it carries the room itself - a little more "
                   "reverb and echo than when it has company (Dist +%d, Size +%d; "
                   "the Corridor and Cascadia presets are the '(alone)' ones)."
                   % (LEAD_ALONE_DEPTH["distance"], LEAD_ALONE_DEPTH["size"]))


def lead_alone(sel):
    """True when the lead vocal is in the song and no other vocal layer is."""
    sel = set(sel or ())
    return "vocals_lead" in sel and not any(i in sel for i in LEAD_COMPANY)


def depth_for_sel(iid, sel=None):
    """depth_for() that knows about the line-up: (tier, spec, note, alone_flag) or None."""
    info = depth_for(iid)
    if not info:
        return None
    tier, spec, note = info
    if iid == "vocals_lead" and tier != "dry" and lead_alone(sel):
        spec = dict(spec)
        spec["distance"] = spec["distance"] + LEAD_ALONE_DEPTH["distance"]
        spec["size"] = spec["size"] + LEAD_ALONE_DEPTH["size"]
        return tier, spec, note, True
    return tier, spec, note, False


# ---- LOW CUT (Lowtility high-pass: corner Hz + slope 12/24/36/48 dB/oct) ----
# A clean high-pass utility, used FIRST in the channel chain (before Kirchhoff /
# comp / reverb) so everything downstream works on an already-clean low end.
# Per instrument: where to start the cut and how steep. Bass/kick keep their
# weight (very low corner); sources with no low end (hats, cymbals, perc) are
# cut high and steep. When Lowtility does this, skip Kirchhoff's High-Pass band.
LOWCUT_COLOUR = "#e6b85c"   # gold, distinct from the other footnote colours
LOWCUT = {
    # id: (corner_Hz, slope_dB_per_oct)
    "kick":             (30,  24),
    "snare":            (90,  24),
    "hihat":            (300, 36),
    "ride":             (250, 24),
    "cymbals":          (300, 24),
    "toms":             (60,  24),
    "percussion":       (400, 36),
    "hand_drums":       (50,  24),
    "bass_root":        (30,  24),
    "bass_loop":        (60,  24),
    "double_bass":      (40,  24),
    "vocals_lead":      (90,  24),
    "vocals_backing":   (150, 24),
    "vocals_choir_pad": (130, 24),
    "vocals_extra":     (170, 24),
    "guitar_rhythm":    (100, 24),
    "guitar_chords":    (110, 24),
    "guitar_lead":      (100, 24),
    "guitar_single_low":(80,  24),
    "guitar_acoustic":  (100, 24),
    "organ":            (80,  24),
    "organ_lead":       (150, 24),
    "organ_melody":     (120, 24),
    "strings_lead":     (100, 24),
    "accordion_lead":   (120, 24),
    "flute_bg":         (200, 24),
    "violin_bg":        (190, 24),
    "accordion":        (80,  24),
    "piano_bg":         (90,  24),
    "piano_riff":       (90,  24),
    "flute":            (250, 24),
    "brass":            (130, 24),
    "brass_lead":       (120, 24),
    "trumpet":          (170, 24),
    "trombone":         (75,  24),
    "tenor_trombone":         (75,  24),
    "tenor_bass_trombone":         (62, 24),
    "saxophone":        (100, 24),
    "horn_section":     (90,  24),
    "harmonica":        (180, 36),
    "woodwind":         (180, 24),
    "clarinet":         (130, 24),
    "oboe":             (200, 24),
    "bassoon":          (50,  24),
    "contrabassoon":    (25,  24),
    "flugelhorn":       (150, 24),
    "french_horn":      (55,  24),
    "tuba":             (28,  24),
    "english_horn":     (150, 24),
    "euphonium":        (70,  24),
    "bass_clarinet":    (60,  24),
    "contrabass_clarinet": (30, 24),
    "double_bass_section": (38, 24),
    "piccolo": (450, 24),
    "alto_flute": (170, 24),
    "bass_flute": (110, 24),
    "soprano_sax": (180, 24),
    "alto_sax": (120, 24),
    "tenor_sax": (90, 24),
    "baritone_sax": (55, 24),
    "piccolo_trumpet": (280, 24),
    "alto_trombone": (95, 24),
    "bass_trombone": (55, 24),
    "double_bass_trombone": (38, 24),
    "synth_pad":        (120, 24),
    "synth_pluck":      (100, 24),
    "synth_mallet":     (250, 24),
    "violin":           (180, 24),
    "viola":            (150, 24),
    "viola_front":      (150, 24),
    "cello":            (70,  24),
    "string_section":   (90,  24),
}


def lowcut_for(iid):
    """Return (corner_Hz, slope) for an instrument's Lowtility high-pass, or None."""
    return LOWCUT.get(iid)


# *************** DEL 02e2 - SUBMASS (tracked sub-harmonic 'feel') ***********
# DSPTone SubMass tracks the fundamental of the signal and adds a synthesised
# sub layer under it (the 'Amp'/'Feel' amount), keeps that sub CENTRED (Center
# %) and can force everything below a chosen Hz to mono. Reverse-engineered
# from the user's own "Feel a 100" seed export (verified against its 5 knobs):
#   Amp    0-12   knob  -> norm = amp/12      (how much sub is added)
#   Freq   0-350  Hz    -> norm = hz/350      (the tracked/anchor frequency)
#   Center 0-150  %     -> norm = pct/150     (how hard the sub is pulled to
#                                              the centre — 100% = fully mono'd
#                                              at the anchor frequency itself)
#   Level, Mono — NOT patched (no second verified data point yet): the seed's
#   own values are left untouched. Dial Mono (the 'force mono below X Hz'
#   threshold) and Level by ear in the plugin itself once loaded.
# NOT every sound wants this — only sources whose LOW-END WEIGHT matters and
# that can spare a centred, mono sub reinforcement. A bright rhythm guitar or
# a hi-hat gains nothing from it.
SUBMASS_COLOUR = "#6ec6ff"   # sky blue, distinct from the other footnote colours

# id -> (amp 0-12, freq_hz, center_pct, note)
SUBMASS = {
    "kick": (6, 60, 100,
             "Reinforces the kick's 60 Hz thud with a tracked sub layer, glued "
             "dead centre — extra weight on systems that reproduce it, without "
             "adding stereo width down low."),
    "bass_root": (7, 80, 100,
                  "The foundation instrument — the obvious SubMass candidate. "
                  "Tracks the bass note and reinforces/centres its fundamental "
                  "so the low end stays solid even on small speakers."),
    "bass_loop": (5, 100, 85,
                  "Lighter amount than the root bass — this is support, not the "
                  "foundation; keep it from competing for the same sub weight."),
    "double_bass": (6, 70, 100,
                    "Same idea as an electric/synth root bass: track the low "
                    "fundamental and centre it for a solid, mono low end."),
}


def submass_for(iid):
    """Return (amp, freq_hz, center_pct, note) for an instrument's SubMass
    settings, or None if this sound isn't a good SubMass candidate."""
    return SUBMASS.get(iid)


def submass_tier(amp):
    """Amp (0-12) -> a short intensity label, purely for the footnote header
    (LIGHT/MEDIUM/STRONG) — mirrors the FAR/NEAR/... tier word smart:reverb
    shows, so the two footnotes read the same way at a glance."""
    if amp >= 7:
        return "STRONG"
    elif amp >= 6:
        return "MEDIUM"
    else:
        return "LIGHT"


# *************** DEL 02e3 - KNOCK (Plugins That Knock: KNOCK 1 and KNOCK 2) ***********
# KNOCK is a drum / punch processor (transient shaper, saturator, sub generator, air EQ, clipper in one). Two
# versions are installed and BOTH are supported - the setting 'knock_version' (Options > Knock version) decides
# which one Generate > Knock presets writes:
#   KNOCK 1  (Plugins That Knock)  one chain, 25 parameters, 10.7 ms latency, XML state.
#            Folder: Documents\VST3 Presets\Plugins That Knock\KNOCK
#   KNOCK 2  (Knock Audio)         six modules (Punch Comp Sub Saturate Air Clip) in a changeable order, five
#            modes each, binary state, 64 ms latency in 'Mixed' phase mode (0 ms in 'Minimum').
#            Folder: Documents\VST3 Presets\Knock Audio\KNOCK 2   (the plug-in's own ProgramData\...\User stays empty)
# THE 24 KNOCK 1 PRESETS are the ones he already had (made 2026-08-15 / 2026-10-31, '003---Knock---Kick---Tight
# Punch' ...). They are kept EXACTLY: knock1_vstpreset() rebuilds each file byte for byte (checked 2026-11-08).
# Known quirks of those values, kept on purpose and shown honestly in the footnote: TILT beyond +-3 dB, SATURATION
# beyond 30 dB and SATURATIONCOLOR beyond 2 are clamped by the plug-in itself (so every saturation colour is 'Hard'),
# and LOWGAIN -30 dB means the sub generator is off.
# THE KNOCK 2 TWINS were designed 2026-11-08 by rendering a test signal per instrument kind through each KNOCK 1
# preset and adjusting Punch / Saturate / Clip / Air / Tone / Sub in KNOCK 2 until the band levels (20-120, 120-500,
# 500-2k, 2k-6k, 6k+ Hz) and the crest factor matched within ~1-3 dB, then Output gain to the same loudness. They are
# a SOUND-ALIKE starting point, not a copy; KNOCK 2's own modes (Tube, Tape, Velvet ...) are there to try on top.
# The KNOCK 2 file format (decoded from his two saved presets + the 128 factory .k2p, which re-serialise byte for byte):
#   state = tree of nodes  name\0 count {prop\0 value}* count {child}*   (count = 00 or 01 n);
#   value = 01 size type data  (4 = float64, 5 = string, 7 = array);  70 PARAM nodes {id, value} hold the settings in
#   PLAIN units (dB, %, Hz) and mode INDEXES; dsp_order_id is the module order; the Comp chunk ends with a 60-byte JUCE tail.
# ToDo: save a Knock-2-only 'Tube' / 'Tape' variant per bus preset once he has listened; read a preset back to the footnote.
KNOCK_COLOUR = "#ff9f6e"          # warm orange - heat / punch, apart from the blues and violets
KNOCK_MODE_NAMES = {"saturate_mode": ("Classic", "Clean", "Tube", "Broken Tube", "Tape")}
KNOCK_K1_CONST = {"CLIPBYPASS": 0.0, "EQBYPASS": 0.0, "EQCOLOUR": 0.0, "GAINSTAGING": 0.0, "INPUT": 0.0, "LOWPITCH": 41.20339965820313, "LOWPITCHNOTES": 4.0, "OUTPUT": 0.0, "OVERSAMPLING": 0.0, "SATBYPASS": 0.0, "SUBBYPASS": 0.0, "SUBONLY": 0.0, "TRANSBYPASS": 0.0}
KNOCK_K1_VARKEYS = ('AIRGAIN', 'ATTACK', 'COLOR', 'KNOCK', 'LOWCUTCUTOFF', 'LOWGAIN', 'LOWPASS', 'SATURATION', 'SATURATIONCOLOR', 'SUBDECAY', 'TILT', 'WET')
KNOCK_PRESETS = [
    {"key": "kick_tight_punch", "cat": "Kick", "name": "Tight Punch",
     "role": "Short, tight kick: a little clipping for the click, high end rolled off at 12 kHz.",
     "k1": {"AIRGAIN": 1.0, "ATTACK": 45.0, "COLOR": 15.0, "KNOCK": 6.5, "LOWCUTCUTOFF": 30.0, "LOWGAIN": -30.0, "LOWPASS": 12000.0, "SATURATION": 8.0, "SATURATIONCOLOR": 20.0, "SUBDECAY": 120.0, "TILT": -2.0, "WET": 45.0},
     "k2": {"punch_amount": 42.0, "clip_amount": 43.0, "clip_crunch": 15.0, "saturate_amount": 0.0, "saturate_mode": 0.0, "air_amount": 30.0, "tone": -20.0, "hpf": 30.0, "lpf": 12000.0, "mix": 45.0, "sub_amount": 60.0, "sub_length": -68.0, "output_gain": 1.3}},
    {"key": "kick_sub_heavy_808", "cat": "Kick", "name": "Sub Heavy 808",
     "iname": "Kick Sub Heavy",
     "role": "Long 808-style kick: heavy low end, top rolled off at 8 kHz, high mix.",
     "k1": {"AIRGAIN": 0.5, "ATTACK": 15.0, "COLOR": 10.0, "KNOCK": 8.0, "LOWCUTCUTOFF": 20.0, "LOWGAIN": -20.0, "LOWPASS": 8000.0, "SATURATION": 15.0, "SATURATIONCOLOR": 30.0, "SUBDECAY": 320.0, "TILT": -6.0, "WET": 65.0},
     "k2": {"punch_amount": 12.0, "clip_amount": 53.0, "clip_crunch": 10.0, "saturate_amount": 45.0, "saturate_mode": 0.0, "air_amount": 5.0, "tone": -45.0, "hpf": 20.0, "lpf": 8000.0, "mix": 65.0, "sub_amount": 49.0, "sub_length": -9.0, "output_gain": 0.7}},
    {"key": "kick_dirty_distorted", "cat": "Kick", "name": "Dirty Distorted",
     "role": "Kick with grit: strong saturation and a hard clip curve. Use when it must cut through distorted guitars.",
     "k1": {"AIRGAIN": 3.0, "ATTACK": 35.0, "COLOR": 70.0, "KNOCK": 7.0, "LOWCUTCUTOFF": 25.0, "LOWGAIN": -25.0, "LOWPASS": 15000.0, "SATURATION": 35.0, "SATURATIONCOLOR": 60.0, "SUBDECAY": 200.0, "TILT": -1.0, "WET": 70.0},
     "k2": {"punch_amount": 18.0, "clip_amount": 47.0, "clip_crunch": 70.0, "saturate_amount": 100.0, "saturate_mode": 0.0, "air_amount": 0.0, "tone": 20.0, "hpf": 25.0, "lpf": 15000.0, "mix": 70.0, "sub_amount": 74.0, "sub_length": -37.0, "output_gain": -0.5}},
    {"key": "snare_crisp_pop", "cat": "Snare", "name": "Crisp Pop",
     "role": "Bright, snappy snare: lots of attack and air, low cut at 120 Hz.",
     "k1": {"AIRGAIN": 6.0, "ATTACK": 70.0, "COLOR": 40.0, "KNOCK": 4.0, "LOWCUTCUTOFF": 120.0, "LOWGAIN": -30.0, "LOWPASS": 14000.0, "SATURATION": 6.0, "SATURATIONCOLOR": 10.0, "SUBDECAY": 90.0, "TILT": 5.0, "WET": 40.0},
     "k2": {"punch_amount": 45.0, "clip_amount": 37.0, "clip_crunch": 40.0, "saturate_amount": 0.0, "saturate_mode": 0.0, "air_amount": 60.0, "tone": 20.0, "hpf": 120.0, "lpf": 14000.0, "mix": 40.0, "sub_amount": 0.0, "sub_length": -85.0, "output_gain": 0.5}},
    {"key": "snare_fat_backbeat", "cat": "Snare", "name": "Fat Backbeat",
     "role": "Full backbeat snare: medium attack, some saturation for body.",
     "k1": {"AIRGAIN": 3.0, "ATTACK": 40.0, "COLOR": 60.0, "KNOCK": 6.0, "LOWCUTCUTOFF": 60.0, "LOWGAIN": -28.0, "LOWPASS": 10000.0, "SATURATION": 14.0, "SATURATIONCOLOR": 25.0, "SUBDECAY": 140.0, "TILT": 1.0, "WET": 55.0},
     "k2": {"punch_amount": 20.0, "clip_amount": 40.0, "clip_crunch": 60.0, "saturate_amount": 47.0, "saturate_mode": 0.0, "air_amount": 30.0, "tone": 20.0, "hpf": 60.0, "lpf": 10000.0, "mix": 55.0, "sub_amount": 86.0, "sub_length": -59.0, "output_gain": 0.3}},
    {"key": "snare_lo_fi_crushed", "cat": "Snare", "name": "Lo-Fi Crushed",
     "role": "Crushed lo-fi snare: heavy saturation and a hard clip, top cut at 6 kHz. A special effect, not a default.",
     "k1": {"AIRGAIN": 1.0, "ATTACK": 50.0, "COLOR": 100.0, "KNOCK": 5.0, "LOWCUTCUTOFF": 90.0, "LOWGAIN": -25.0, "LOWPASS": 6000.0, "SATURATION": 45.0, "SATURATIONCOLOR": 70.0, "SUBDECAY": 100.0, "TILT": 2.0, "WET": 80.0},
     "k2": {"punch_amount": 5.0, "clip_amount": 33.0, "clip_crunch": 100.0, "saturate_amount": 80.0, "saturate_mode": 0.0, "air_amount": 30.0, "tone": 80.0, "hpf": 90.0, "lpf": 6000.0, "mix": 80.0, "sub_amount": 0.0, "sub_length": -79.0, "output_gain": -0.7}},
    {"key": "tom_deep_boom", "cat": "Tom", "name": "Deep Boom",
     "role": "Floor / low toms: low end and long decay.",
     "k1": {"AIRGAIN": 1.5, "ATTACK": 30.0, "COLOR": 25.0, "KNOCK": 6.5, "LOWCUTCUTOFF": 40.0, "LOWGAIN": -20.0, "LOWPASS": 9000.0, "SATURATION": 12.0, "SATURATIONCOLOR": 20.0, "SUBDECAY": 250.0, "TILT": -3.0, "WET": 55.0},
     "k2": {"punch_amount": 15.0, "clip_amount": 43.0, "clip_crunch": 25.0, "saturate_amount": 40.0, "saturate_mode": 0.0, "air_amount": 55.0, "tone": -20.0, "hpf": 40.0, "lpf": 9000.0, "mix": 55.0, "sub_amount": 89.0, "sub_length": -24.0, "output_gain": 0.5}},
    {"key": "tom_tight_attack", "cat": "Tom", "name": "Tight Attack",
     "role": "Rack toms, congas, percussion: tight attack, short decay.",
     "k1": {"AIRGAIN": 2.0, "ATTACK": 55.0, "COLOR": 15.0, "KNOCK": 5.0, "LOWCUTCUTOFF": 55.0, "LOWGAIN": -28.0, "LOWPASS": 11000.0, "SATURATION": 8.0, "SATURATIONCOLOR": 15.0, "SUBDECAY": 140.0, "TILT": -1.0, "WET": 42.0},
     "k2": {"punch_amount": 28.0, "clip_amount": 33.0, "clip_crunch": 15.0, "saturate_amount": 27.0, "saturate_mode": 0.0, "air_amount": 60.0, "tone": 0.0, "hpf": 55.0, "lpf": 11000.0, "mix": 42.0, "sub_amount": 86.0, "sub_length": -59.0, "output_gain": 1.1}},
    {"key": "hihat_airy_closed", "cat": "Hihat", "name": "Airy Closed",
     "role": "Closed hi-hat: very little clipping, much air, low cut at 300 Hz.",
     "k1": {"AIRGAIN": 5.5, "ATTACK": 80.0, "COLOR": 20.0, "KNOCK": 1.0, "LOWCUTCUTOFF": 300.0, "LOWGAIN": -30.0, "LOWPASS": 20000.0, "SATURATION": 4.0, "SATURATIONCOLOR": 10.0, "SUBDECAY": 40.0, "TILT": 8.0, "WET": 30.0},
     "k2": {"punch_amount": 40.0, "clip_amount": 7.0, "clip_crunch": 20.0, "saturate_amount": 0.0, "saturate_mode": 0.0, "air_amount": 50.0, "tone": 85.0, "hpf": 300.0, "lpf": 20000.0, "mix": 30.0, "sub_amount": 0.0, "sub_length": -100.0, "output_gain": 1.6}},
    {"key": "hihat_bright_open", "cat": "Hihat", "name": "Bright Open",
     "role": "Open hi-hat / ride: more air and a touch of saturation.",
     "k1": {"AIRGAIN": 6.0, "ATTACK": 65.0, "COLOR": 35.0, "KNOCK": 1.5, "LOWCUTCUTOFF": 250.0, "LOWGAIN": -30.0, "LOWPASS": 20000.0, "SATURATION": 10.0, "SATURATIONCOLOR": 25.0, "SUBDECAY": 60.0, "TILT": 7.0, "WET": 38.0},
     "k2": {"punch_amount": 32.0, "clip_amount": 0.0, "clip_crunch": 35.0, "saturate_amount": 33.0, "saturate_mode": 0.0, "air_amount": 80.0, "tone": 40.0, "hpf": 250.0, "lpf": 20000.0, "mix": 38.0, "sub_amount": 0.0, "sub_length": -100.0, "output_gain": 0.2}},
    {"key": "cymbal_crash_sheen", "cat": "Cymbal", "name": "Crash Sheen",
     "role": "Crashes: only a little shine on top, low cut at 400 Hz.",
     "k1": {"AIRGAIN": 6.0, "ATTACK": 90.0, "COLOR": 10.0, "KNOCK": 0.5, "LOWCUTCUTOFF": 400.0, "LOWGAIN": -30.0, "LOWPASS": 20000.0, "SATURATION": 3.0, "SATURATIONCOLOR": 5.0, "SUBDECAY": 30.0, "TILT": 9.0, "WET": 25.0},
     "k2": {"punch_amount": 55.0, "clip_amount": 0.0, "clip_crunch": 10.0, "saturate_amount": 0.0, "saturate_mode": 0.0, "air_amount": 20.0, "tone": 80.0, "hpf": 400.0, "lpf": 20000.0, "mix": 25.0, "sub_amount": 0.0, "sub_length": -100.0, "output_gain": 0.9}},
    {"key": "bass_sub_reinforce", "cat": "Bass", "name": "Sub Reinforce",
     "role": "Bass or 808: adds weight and saturation under the fundamental.",
     "k1": {"AIRGAIN": 1.0, "ATTACK": 20.0, "COLOR": 20.0, "KNOCK": 7.5, "LOWCUTCUTOFF": 25.0, "LOWGAIN": -22.0, "LOWPASS": 8000.0, "SATURATION": 18.0, "SATURATIONCOLOR": 30.0, "SUBDECAY": 280.0, "TILT": -4.0, "WET": 60.0},
     "k2": {"punch_amount": 10.0, "clip_amount": 50.0, "clip_crunch": 20.0, "saturate_amount": 60.0, "saturate_mode": 0.0, "air_amount": 10.0, "tone": -50.0, "hpf": 25.0, "lpf": 8000.0, "mix": 60.0, "sub_amount": 0.0, "sub_length": -17.0, "output_gain": 1.4}},
    {"key": "drum_bus_glue_and_air", "cat": "Drum Bus", "name": "Glue And Air",
     "role": "ONE instance on the drum bus: gentle glue, a little air.",
     "k1": {"AIRGAIN": 2.5, "ATTACK": 40.0, "COLOR": 20.0, "KNOCK": 3.0, "LOWCUTCUTOFF": 35.0, "LOWGAIN": -30.0, "LOWPASS": 16000.0, "SATURATION": 6.0, "SATURATIONCOLOR": 15.0, "SUBDECAY": 150.0, "TILT": 0.0, "WET": 25.0},
     "k2": {"punch_amount": 20.0, "clip_amount": 30.0, "clip_crunch": 20.0, "saturate_amount": 0.0, "saturate_mode": 0.0, "air_amount": 10.0, "tone": 30.0, "hpf": 35.0, "lpf": 16000.0, "mix": 25.0, "sub_amount": 0.0, "sub_length": -54.0, "output_gain": 0.5}},
    {"key": "bass_guitar_pick_attack", "cat": "Bass Guitar", "name": "Pick Attack",
     "role": "Bass guitar / low single-note lines: brings out the pick attack.",
     "k1": {"AIRGAIN": 2.0, "ATTACK": 30.0, "COLOR": 15.0, "KNOCK": 5.0, "LOWCUTCUTOFF": 30.0, "LOWGAIN": -25.0, "LOWPASS": 10000.0, "SATURATION": 10.0, "SATURATIONCOLOR": 15.0, "SUBDECAY": 180.0, "TILT": -2.0, "WET": 45.0},
     "k2": {"punch_amount": 0.0, "clip_amount": 33.0, "clip_crunch": 15.0, "saturate_amount": 33.0, "saturate_mode": 0.0, "air_amount": 20.0, "tone": -30.0, "hpf": 30.0, "lpf": 10000.0, "mix": 45.0, "sub_amount": 0.0, "sub_length": -44.0, "output_gain": 1.0}},
    {"key": "electric_guitar_rhythm_punch", "cat": "Electric Guitar", "name": "Rhythm Punch",
     "role": "Rhythm guitar: saturation and attack, low cut at 150 Hz.",
     "k1": {"AIRGAIN": 3.0, "ATTACK": 50.0, "COLOR": 45.0, "KNOCK": 2.5, "LOWCUTCUTOFF": 150.0, "LOWGAIN": -30.0, "LOWPASS": 12000.0, "SATURATION": 20.0, "SATURATIONCOLOR": 35.0, "SUBDECAY": 80.0, "TILT": 2.0, "WET": 30.0},
     "k2": {"punch_amount": 20.0, "clip_amount": 37.0, "clip_crunch": 45.0, "saturate_amount": 27.0, "saturate_mode": 0.0, "air_amount": 100.0, "tone": -20.0, "hpf": 150.0, "lpf": 12000.0, "mix": 30.0, "sub_amount": 0.0, "sub_length": -92.0, "output_gain": -0.3}},
    {"key": "strings_low_warmth", "cat": "Strings", "name": "Low Warmth",
     "role": "Low strings: warmth, slow attack, nothing aggressive.",
     "k1": {"AIRGAIN": 1.5, "ATTACK": 90.0, "COLOR": 10.0, "KNOCK": 1.5, "LOWCUTCUTOFF": 45.0, "LOWGAIN": -28.0, "LOWPASS": 14000.0, "SATURATION": 6.0, "SATURATIONCOLOR": 10.0, "SUBDECAY": 300.0, "TILT": -1.0, "WET": 20.0},
     "k2": {"punch_amount": 25.0, "clip_amount": 10.0, "clip_crunch": 10.0, "saturate_amount": 0.0, "saturate_mode": 0.0, "air_amount": 10.0, "tone": -40.0, "hpf": 45.0, "lpf": 14000.0, "mix": 20.0, "sub_amount": 6.0, "sub_length": -13.0, "output_gain": 0.4}},
    {"key": "brass_horn_stab", "cat": "Brass", "name": "Horn Stab",
     "role": "Brass: bite on the stabs, medium saturation.",
     "k1": {"AIRGAIN": 3.5, "ATTACK": 35.0, "COLOR": 30.0, "KNOCK": 4.5, "LOWCUTCUTOFF": 100.0, "LOWGAIN": -28.0, "LOWPASS": 13000.0, "SATURATION": 16.0, "SATURATIONCOLOR": 25.0, "SUBDECAY": 110.0, "TILT": 1.0, "WET": 40.0},
     "k2": {"punch_amount": 0.0, "clip_amount": 30.0, "clip_crunch": 30.0, "saturate_amount": 53.0, "saturate_mode": 0.0, "air_amount": 75.0, "tone": -30.0, "hpf": 100.0, "lpf": 13000.0, "mix": 40.0, "sub_amount": 0.0, "sub_length": -73.0, "output_gain": 0.9}},
    {"key": "organ_sub_pedal_grit", "cat": "Organ", "name": "Sub Pedal Grit",
     "role": "Organ: grit and low-end weight (pedals).",
     "k1": {"AIRGAIN": 2.0, "ATTACK": 60.0, "COLOR": 25.0, "KNOCK": 3.0, "LOWCUTCUTOFF": 25.0, "LOWGAIN": -22.0, "LOWPASS": 11000.0, "SATURATION": 22.0, "SATURATIONCOLOR": 30.0, "SUBDECAY": 220.0, "TILT": -2.0, "WET": 35.0},
     "k2": {"punch_amount": 10.0, "clip_amount": 20.0, "clip_crunch": 25.0, "saturate_amount": 73.0, "saturate_mode": 0.0, "air_amount": 20.0, "tone": -30.0, "hpf": 25.0, "lpf": 11000.0, "mix": 35.0, "sub_amount": 23.0, "sub_length": -32.0, "output_gain": -0.0}},
    {"key": "vocal_lead_warmth", "cat": "Vocal", "name": "Lead Warmth",
     "role": "Lead vocal: a very light touch of warmth and air. Almost nothing - that is the point.",
     "k1": {"AIRGAIN": 4.0, "ATTACK": 70.0, "COLOR": 20.0, "KNOCK": 0.5, "LOWCUTCUTOFF": 200.0, "LOWGAIN": -30.0, "LOWPASS": 18000.0, "SATURATION": 8.0, "SATURATIONCOLOR": 15.0, "SUBDECAY": 50.0, "TILT": 4.0, "WET": 20.0},
     "k2": {"punch_amount": 0.0, "clip_amount": 3.0, "clip_crunch": 20.0, "saturate_amount": 27.0, "saturate_mode": 0.0, "air_amount": 40.0, "tone": 100.0, "hpf": 200.0, "lpf": 18000.0, "mix": 20.0, "sub_amount": 0.0, "sub_length": -100.0, "output_gain": -0.6}},
    {"key": "vocal_rap_chest_weight", "cat": "Vocal", "name": "Rap Chest Weight",
     "role": "Spoken / rapped vocal: chest weight and a little more saturation.",
     "k1": {"AIRGAIN": 2.5, "ATTACK": 45.0, "COLOR": 30.0, "KNOCK": 3.5, "LOWCUTCUTOFF": 90.0, "LOWGAIN": -25.0, "LOWPASS": 14000.0, "SATURATION": 14.0, "SATURATIONCOLOR": 25.0, "SUBDECAY": 130.0, "TILT": 0.0, "WET": 35.0},
     "k2": {"punch_amount": 10.0, "clip_amount": 43.0, "clip_crunch": 30.0, "saturate_amount": 0.0, "saturate_mode": 0.0, "air_amount": 15.0, "tone": 50.0, "hpf": 90.0, "lpf": 14000.0, "mix": 35.0, "sub_amount": 34.0, "sub_length": -63.0, "output_gain": 0.2}},
    {"key": "vocal_bgv_glue", "cat": "Vocal", "name": "BGV Glue",
     "role": "Backing vocals: glue and a little air; very light.",
     "k1": {"AIRGAIN": 3.0, "ATTACK": 80.0, "COLOR": 15.0, "KNOCK": 0.3, "LOWCUTCUTOFF": 250.0, "LOWGAIN": -30.0, "LOWPASS": 17000.0, "SATURATION": 6.0, "SATURATIONCOLOR": 10.0, "SUBDECAY": 40.0, "TILT": 3.0, "WET": 18.0},
     "k2": {"punch_amount": 0.0, "clip_amount": 2.0, "clip_crunch": 15.0, "saturate_amount": 20.0, "saturate_mode": 0.0, "air_amount": 30.0, "tone": 100.0, "hpf": 250.0, "lpf": 17000.0, "mix": 18.0, "sub_amount": 0.0, "sub_length": -100.0, "output_gain": -0.5}},
    {"key": "piano_percussive_attack", "cat": "Piano", "name": "Percussive Attack",
     "role": "Piano: brings out the hammer attack.",
     "k1": {"AIRGAIN": 2.0, "ATTACK": 40.0, "COLOR": 20.0, "KNOCK": 2.5, "LOWCUTCUTOFF": 60.0, "LOWGAIN": -28.0, "LOWPASS": 15000.0, "SATURATION": 10.0, "SATURATIONCOLOR": 15.0, "SUBDECAY": 150.0, "TILT": -1.0, "WET": 30.0},
     "k2": {"punch_amount": 10.0, "clip_amount": 22.0, "clip_crunch": 20.0, "saturate_amount": 28.0, "saturate_mode": 0.0, "air_amount": 30.0, "tone": -15.0, "hpf": 60.0, "lpf": 15000.0, "mix": 30.0, "sub_amount": 6.0, "sub_length": -54.0, "output_gain": 0.3}},
    {"key": "synth_lead_analog_bite", "cat": "Synth Lead", "name": "Analog Bite",
     "role": "Synth lead / lead guitar / plucks: analog bite and saturation.",
     "k1": {"AIRGAIN": 3.0, "ATTACK": 25.0, "COLOR": 40.0, "KNOCK": 3.0, "LOWCUTCUTOFF": 80.0, "LOWGAIN": -28.0, "LOWPASS": 16000.0, "SATURATION": 20.0, "SATURATIONCOLOR": 35.0, "SUBDECAY": 100.0, "TILT": 1.0, "WET": 35.0},
     "k2": {"punch_amount": 10.0, "clip_amount": 20.0, "clip_crunch": 40.0, "saturate_amount": 57.0, "saturate_mode": 0.0, "air_amount": 30.0, "tone": 20.0, "hpf": 80.0, "lpf": 16000.0, "mix": 35.0, "sub_amount": 6.0, "sub_length": -79.0, "output_gain": -0.4}},
    {"key": "full_mix_master_glue", "cat": "Full Mix", "name": "Master Glue",
     "rated": True,
     "role": "Mix bus: only the faintest glue. Put it last, mix at about 12 %.",
     "k1": {"AIRGAIN": 1.5, "ATTACK": 60.0, "COLOR": 10.0, "KNOCK": 1.0, "LOWCUTCUTOFF": 30.0, "LOWGAIN": -30.0, "LOWPASS": 18000.0, "SATURATION": 4.0, "SATURATIONCOLOR": 8.0, "SUBDECAY": 100.0, "TILT": 0.0, "WET": 12.0},
     "k2": {"punch_amount": 0.0, "clip_amount": 7.0, "clip_crunch": 10.0, "saturate_amount": 13.0, "saturate_mode": 0.0, "air_amount": 15.0, "tone": 20.0, "hpf": 30.0, "lpf": 18000.0, "mix": 12.0, "sub_amount": 0.0, "sub_length": -79.0, "output_gain": 0.1}},
]
KNOCK_BY_KEY = {p["key"]: p for p in KNOCK_PRESETS}

# instrument id -> preset keys (the first is the main one, the rest are alternatives).
KNOCK_FOR = {
    "kick":              ["kick_tight_punch", "kick_sub_heavy_808", "kick_dirty_distorted"],
    "snare":             ["snare_fat_backbeat", "snare_crisp_pop", "snare_lo_fi_crushed"],
    "toms":              ["tom_deep_boom", "tom_tight_attack"],
    "percussion":        ["tom_tight_attack"],
    "hand_drums":        ["tom_tight_attack"],
    "hihat":             ["hihat_airy_closed"],
    "ride":              ["hihat_bright_open"],
    "cymbals":           ["cymbal_crash_sheen"],
    "bass_root":         ["bass_sub_reinforce", "bass_guitar_pick_attack"],
    "bass_loop":         ["bass_sub_reinforce"],
    "double_bass":       ["strings_low_warmth"],
    "double_bass_section": ["strings_low_warmth"],
    "guitar_single_low": ["bass_guitar_pick_attack"],
    "guitar_rhythm":     ["electric_guitar_rhythm_punch"],
    "guitar_chords":     ["electric_guitar_rhythm_punch"],
    "organ":             ["organ_sub_pedal_grit"],
    "cello":             ["strings_low_warmth"],
    "viola":             ["strings_low_warmth"],
    "string_section":    ["strings_low_warmth"],
    "brass":             ["brass_horn_stab"],
    "brass_lead":        ["brass_horn_stab"],
    "horn_section":      ["brass_horn_stab"],
    "trumpet":           ["brass_horn_stab"],
    "trombone":          ["brass_horn_stab"],
    "tenor_trombone":          ["brass_horn_stab"],
    "tenor_bass_trombone":          ["brass_horn_stab"],
    "flugelhorn":        ["brass_horn_stab"],
    "french_horn":       ["brass_horn_stab"],
    "alto_trombone":     ["brass_horn_stab"],
    "bass_trombone":     ["brass_horn_stab"],
    "double_bass_trombone":     ["brass_horn_stab"],
    "piccolo_trumpet":   ["brass_horn_stab"],
    "tuba":              ["brass_horn_stab"],
    "euphonium":         ["brass_horn_stab"],
    "vocals_lead":       ["vocal_lead_warmth", "vocal_rap_chest_weight"],
    "vocals_backing":    ["vocal_bgv_glue"],
    "vocals_extra":      ["vocal_bgv_glue"],
    "piano_bg":          ["piano_percussive_attack"],
    "piano_riff":        ["piano_percussive_attack"],
    "synth_pluck":       ["synth_lead_analog_bite"],
    "synth_mallet":      ["synth_lead_analog_bite"],
}
# Buses have no instrument id: (file label, preset key). Written by 'Generate > Knock presets: All' only.
KNOCK_BUS = [("Drum_Bus", "drum_bus_glue_and_air"), ("Mix_Bus", "full_mix_master_glue")]


def knock_for(iid):
    """[preset, ...] for an instrument (main one first), or []."""
    return [KNOCK_BY_KEY[k] for k in KNOCK_FOR.get(iid, []) if k in KNOCK_BY_KEY]


def knock_version_of(settings):
    v = str((settings or {}).get("knock_version", "1"))
    return v if v in ("1", "2") else "1"


def knock_file_name(label, preset, version):
    return "%s---Knock%s_%s.vstpreset" % (label, version, preset["name"])


def knock_effective(preset):
    """The KNOCK 1 values as the plug-in really uses them (it clamps some)."""
    d = dict(KNOCK_K1_CONST)
    d.update(preset["k1"])
    return {
        "punch": d["ATTACK"], "clip_db": d["KNOCK"], "clip_curve": d["COLOR"],
        "sat_db": min(30.0, d["SATURATION"]),
        "sat_colour": ("Smooth", "Medium", "Hard")[min(2, int(d["SATURATIONCOLOR"]))],
        "air_db": d["AIRGAIN"], "tone": max(-3.0, min(3.0, d["TILT"])),
        "low_cut": d["LOWCUTCUTOFF"], "high_cut": d["LOWPASS"], "mix": d["WET"],
        "sub_db": d["LOWGAIN"], "sub_decay": d["SUBDECAY"],
    }


def knock_bits(preset, version):
    """Short list of the numbers worth typing in (for the footnote and the report)."""
    if version == "2":
        k = preset["k2"]
        bits = ["Punch %g" % k["punch_amount"], "Clip %g (crunch %g)" % (k["clip_amount"], k["clip_crunch"]),
                "Saturate %g (%s)" % (k["saturate_amount"], KNOCK_MODE_NAMES["saturate_mode"][int(k["saturate_mode"])]),
                "Air %g" % k["air_amount"], "Tone %g" % k["tone"]]
        if k.get("sub_amount", 0) > 0:
            bits.append("Sub %g" % k["sub_amount"])
        bits += ["Low cut %g Hz" % k["hpf"], "High cut %g Hz" % k["lpf"], "Mix %g %%" % k["mix"],
                 "Output %+g dB" % k["output_gain"]]
        return bits
    e = knock_effective(preset)
    bits = ["Punch %g %%" % e["punch"], "Clip %g dB (curve %g)" % (e["clip_db"], e["clip_curve"]),
            "Saturation %g dB (%s)" % (e["sat_db"], e["sat_colour"]), "Air %g dB" % e["air_db"],
            "Tone %+g dB" % e["tone"]]
    bits.append("Sub off" if e["sub_db"] <= -30 else "Sub %g dB, decay %g ms" % (e["sub_db"], e["sub_decay"]))
    bits += ["Low cut %g Hz" % e["low_cut"], "High cut %g Hz" % e["high_cut"], "Mix %g %%" % e["mix"]]
    return bits


# ---- the file writers ----------------------------------------------------------------
KN1_CLASS_ID = b"ABCDEF019182FAEB4D616E754333357A"
_KN1_XML_HEAD = '<?xml version="1.0" encoding="UTF-8"?> <Parameters '
_KN1_TAIL_B64 = "eNpjYIACr1Bn14CizLLEklSXxJJEBkZGp8qCxOJiIIOZQRa7IgBupw2P"
_KN1_INFO_B64 = "eNqlkEFrwkAUhM8K/ofl3W3srYdsRdSCBG0K4n2bfdk+mrwtuy9qIP+sh/4k/0LTi/XgQfA2DMM3w5y+f9Lpsa7UHkMkzxoeHyagkAtviZ2GRsrxE0yfR8N0jWJWXPpeD9KZSKD3RlCR1bBGS2bbfiGovaka1LCLkgeMKKCk9zXEPs8OVFkZFzUcAgnmwQsWghaSK9C8atyK50bQ+dCeyS/HbkFRfJB+b7do2dRUxG75dm/TxtT/+7PN6zy7l7hDtj6cmX8mcVTbDyMqY1983l6QJhf3/wK4U5ZF"
_KN1_INFO_RATED_B64 = "eNqlkk1OwzAQRtcgcQfLe2hDf5ESqrRJpSpqCRCyN/EktUhtsCellXKzLjgSV8CVILBoN3RWo9F8740lf+4+3NFmVZI1aCOU9Khz1aYEZKa4kIVHK8wvh3R0e3HuzgHZTObK9meuj6jFc4VABPfoHLhgDwxthJI1KyvwaI8S3L7aRkikJC9ZYTxKW8fSid1tsqnBWIMB/GEYu79nf2PetUCItULIEPhBaFxWxUxOGEKh9LYhTzd1IAwqjfa1dbCVbCUyU4f3p5oWbPV7f7S4m0SnElOQXOmGuR8KaUiyZEgiqbKX/wvSx6TzJMVbBbOgEfjjSRBO286NM7ye+uG4G/SdfjjodTu2egP/iG4pOAdZH7C6rT9f5guTgc5R"      # the same Info block with MediaRating 5 (one preset of his is rated)
KN2_CLASS_ID = b"ABCDEF019182FAEB4B6E416E4B6E4B32"
KN2_MODULES = ("Punch", "Comp", "Sub", "Saturate", "Air", "Clip")


def _knock_wrap(comp, info, class_id):
    """A .vstpreset: header, Comp chunk, Info chunk and the chunk list (Cont is empty and shares Info's offset)."""
    body = b"VST3" + struct.pack("<i", 1) + class_id + struct.pack("<q", 48 + len(comp) + len(info)) + comp + info
    lst = b"List" + struct.pack("<i", 3)
    lst += b"Comp" + struct.pack("<qq", 48, len(comp))
    lst += b"Cont" + struct.pack("<qq", 48 + len(comp), 0)
    lst += b"Info" + struct.pack("<qq", 48 + len(comp), len(info))
    return body + lst


def _kn2_wrap_vstpreset(comp, info):
    return _knock_wrap(comp, info, KN2_CLASS_ID)


def knock1_vstpreset(preset):
    """Bytes of a KNOCK 1 .vstpreset (XML parameter list in a 'VC2!' block)."""
    import zlib as _zl
    vals = dict(KNOCK_K1_CONST)
    vals.update(preset["k1"])
    xml = _KN1_XML_HEAD + 'presetCurrentName="KNOCK - %s">' % preset.get("iname", "%s %s" % (preset["cat"], preset["name"]))
    xml += "".join('<PARAM id="%s" value="%s"/>' % (k, repr(float(vals[k]))) for k in sorted(vals))
    xml += "</Parameters>"
    xb = xml.encode("utf-8")
    comp = b"VC2!" + struct.pack("<I", len(xb)) + xb + _zl.decompress(base64.b64decode(_KN1_TAIL_B64))
    info = _zl.decompress(base64.b64decode(_KN1_INFO_RATED_B64 if preset.get("rated") else _KN1_INFO_B64))
    return _knock_wrap(comp, info, KN1_CLASS_ID)


# ---- KNOCK 2 (embedded from Knock2_format.py; names prefixed _kn2_ / KN2_) ---------------
KN2_JUCE_TAIL_B64 = "eNpjYIAAr1Bn14CizLLEklSXxJJEBkZGp8qCxOJiIIOZQRa7IgBupg2P"
KN2_INFO_XML_B64 = "eNql0LEKwjAQBuBZwXcIt2vVyaFRpCCIWDuIe2yuIRgTSS61fTYHH8lXsJM6OAhux8/Px889bvd00ZwNq9EH7SyHyWgMDG3ppLaKQ6RqOIPFfNBPt0hibSvX3b10SeT1MRIyLTlsUWqxby8IrBYmIodDoMJjQAJGXc4hdH2rgFVGqMDh6jVh4R1hSSgh+YIWJqq1zQShcr59yavmXzIX5/fQTb7LNmz6r3lAK51/q9aVJ7aMUrvf5TT5ePETDlCKhQ=="
KN2_DEFAULT_STATE_B64 = "eNqdl01v0zAYxxPAG2v3UgaCa8WJCxwmxAEBa9Vpl4mtYuyAVCm4idNYdeLgl73cOPIZ+DR8ByTOO3HmyG3YcUrbNKq9Tpq6Zr/nn8f/x35sjzMajvcCLqBAAY48/07E84CyCLHi66t1f81fB32ZhYnnr4EeTXPPb4BTKCRTMZ4PwKkc6o8uZgVBcO6hCAvKAh5CYmQ37nmed32y93vfP+t3P3Tfqzfp55sAYhbAlMpMeOeQSFSy5mcWbRTokEhmAbcKEGfBCOLMwm4UbIovq9ynTs3LUxohpyxpjmxvbhZgTi/Qwnj+7NeQPMGxsI48VO672VmyIStKW2E/zo9+07AxQzyxyG4b1M39hoHt9jdL0O5/maqLryXKlFmR3Sw18d2MbRp2xNQ6sHqlSWevNOzkVQE6eaVJtzloUJnmbsPnBKaOZAZzN/tFwiQXlkw3QEykEMjWJZ6AEaFDSIISD0IpaBzPRV3f3FzOm/u4GsWJWuvVV7U6lfQTykUwvMoh55a0AEjyuMq8rC5HnOVSuMwaAEhFru19+9mpMPZJtQWoFI7v3Ab0HDEO05zgbGSdg3kCOXKZruvAZaZug1x3NLe1ulnCQ0oXZuu7qgMGDRkMxxa3dkrWbWU3S9pehUm6DmZN0nVrhIYVEBNHWZHUdIJKti3AYYzEVUBwioU1iwcKN4cKt9rtTPmhvS21pnTIkLU3zYirRm5LZXdKu5V8expgr/pMLg6FnxmoS+1nxC8QZNb1wuXQdRvUaEgJZdadTZORrCyrtucdLxihQHUK+SJRFl7N0V8b3w+qC1bTbvUw4yIoG4nEDaV6v7AeLjXqcrgsuJraVoplwIyKBfBNp8Z8t3apyeJXlcoyoDUgaFY3ARMcRSgLcsjUyvLvFJ9BBlM0ORAX4uaxinaNLY99KwcXx4uVgnfUFhuwlKueyEZI1Ak8+7FMoAVSOMJhUNxZkIALCp/j+Ne+qwLRZ/+aHO53lg9iqsBQXCfwfOkgHpYCxoRAF6NOZLdzGxF9g6wRebpU5NG8SLEJ1an8XWrp7ryK6ny3H85ks1x1Xv1vt6sJmBawJLYnGQv66qamZq1/t/h2iImKfAt6rwd9Rkcq6gAKODjSd/92V0aYDo6OT3pH7b2BCeSDM47Y4ADFUBLxYryXG9meMkw1Af1P8+CQkkj9rW//hHjeP5m2y6M="


def _kn2_count(n):
    if n >= 256:
        raise ValueError("too many items for one node: %d" % n)
    return b"\0" if n == 0 else bytes([1, n])


def _kn2_v_double(x):
    return b"\x01\x09\x04" + struct.pack("<d", float(x))


def _kn2_v_str(s):
    d = s.encode("utf-8") + b"\0"
    if len(d) + 1 > 255:
        raise ValueError("string too long: %r" % s)
    return bytes([1, len(d) + 1, 5]) + d


def _kn2_v_arr(items):
    payload = _kn2_count(len(items)) + b"".join(_kn2_v_str(s) for s in items)
    return bytes([1, len(payload) + 1, 7]) + payload


def _kn2_v_raw(v):
    return bytes([1, len(v[1]) + 1, int(v[0][4:])]) + v[1]


def _kn2_v_any(v):
    if isinstance(v, float):
        return _kn2_v_double(v)
    if isinstance(v, str):
        return _kn2_v_str(v)
    if isinstance(v, list):
        return _kn2_v_arr(v)
    return _kn2_v_raw(v)


def _kn2_node_to_bytes(node):
    name, props, kids = node
    out = name.encode() + b"\0" + _kn2_count(len(props))
    for k, v in props.items():
        out += k.encode() + b"\0" + _kn2_v_any(v)
    out += _kn2_count(len(kids))
    for c in kids:
        out += _kn2_node_to_bytes(c)
    return out


def _kn2_cstr(b, i):
    j = b.index(b"\0", i)
    return b[i:j].decode("utf-8", "replace"), j + 1


def _kn2_read_val(b, i):
    if b[i] != 1:
        raise ValueError("bad value marker at %d" % i)
    size, t = b[i + 1], b[i + 2]
    data = b[i + 3:i + 2 + size]
    nxt = i + 2 + size
    if t == 4:
        return struct.unpack("<d", data)[0], nxt
    if t == 5:
        return data.rstrip(b"\0").decode("utf-8"), nxt
    if t == 7:
        arr, k = [], 2
        for _ in range(data[1]):
            v, k = _kn2_read_val(data, k)
            arr.append(v)
        return arr, nxt
    return ("type%d" % t, bytes(data)), nxt


def _kn2_read_count(b, i):
    if b[i] == 1:
        return b[i + 1], i + 2
    if b[i] != 0:
        raise ValueError("bad count byte at %d" % i)
    return 0, i + 1


def _kn2_read_node(b, i):
    name, i = _kn2_cstr(b, i)
    n, i = _kn2_read_count(b, i)
    props = {}
    for _ in range(n):
        k, i = _kn2_cstr(b, i)
        v, i = _kn2_read_val(b, i)
        props[k] = v
    nc, i = _kn2_read_count(b, i)
    kids = []
    for _ in range(nc):
        c, i = _kn2_read_node(b, i)
        kids.append(c)
    return (name, props, kids), i


def _kn2_parse_state(state):
    """bytes of a .k2p (or the Comp chunk) -> (node, tail bytes)."""
    node, i = _kn2_read_node(state, 0)
    return node, state[i:]



def _kn2_unz(s):
    import zlib as _zl
    return _zl.decompress(base64.b64decode(s))



def knock2_vstpreset(params, order=None):
    """params = {id: value} (only the ones that differ from the default).  Returns .vstpreset bytes."""
    (name, props, kids), _t = _kn2_parse_state(_kn2_unz(KN2_DEFAULT_STATE_B64))
    known = {k[1]["id"] for k in kids if k[0] == "PARAM"}
    bad = [k for k in params if k not in known]
    if bad:
        raise KeyError("unknown KNOCK 2 parameter(s): %s" % ", ".join(sorted(bad)))
    if order is not None:
        if sorted(order) != sorted(KN2_MODULES):
            raise ValueError("order must be a permutation of %r" % (KN2_MODULES,))
        props["dsp_order_id"] = list(order)
    new_kids = []
    for k in kids:
        if k[0] == "Curr_Preset":
            continue  # a stale file path would only confuse the plug-in's preset browser
        if k[0] == "PARAM" and k[1]["id"] in params:
            k = (k[0], dict(k[1], value=float(params[k[1]["id"]])), k[2])
        new_kids.append(k)
    comp = _kn2_node_to_bytes((name, props, new_kids)) + _kn2_unz(KN2_JUCE_TAIL_B64)
    return _kn2_wrap_vstpreset(comp, _kn2_unz(KN2_INFO_XML_B64))


def knock2_preset_bytes(preset):
    """Bytes of a KNOCK 2 .vstpreset: the default state with this preset's values on top."""
    return knock2_vstpreset(dict(preset["k2"]))


def knock2_k2p(params, order=None):
    """Bytes of a native KNOCK 2 '.k2p' preset (the plug-in's own browser lists these from
    C:\\ProgramData\\Knock Audio\\KNOCK 2\\Presets\\User): the raw state, no VST3 container, no JUCE tail."""
    (name, props, kids), _t = _kn2_parse_state(_kn2_unz(KN2_DEFAULT_STATE_B64))
    known = {k[1]["id"] for k in kids if k[0] == "PARAM"}
    bad = [k for k in params if k not in known]
    if bad:
        raise KeyError("unknown KNOCK 2 parameter(s): %s" % ", ".join(sorted(bad)))
    if order is not None:
        props["dsp_order_id"] = list(order)
    new_kids = []
    for k in kids:
        if k[0] == "Curr_Preset":
            continue
        if k[0] == "PARAM" and k[1]["id"] in params:
            k = (k[0], dict(k[1], value=float(params[k[1]["id"]])), k[2])
        new_kids.append(k)
    return _kn2_node_to_bytes((name, props, new_kids))


def knock_preset_bytes(preset, version):
    return knock2_preset_bytes(preset) if version == "2" else knock1_vstpreset(preset)


# *************** DEL 02f2 - COMPRESSION (per-instrument dynamics) ***********
# Per-instrument compressor STARTING POINTS — ranges, never gospel. The
# compressor sits AFTER the corrective EQ / low-cut and BEFORE the tonal EQ,
# saturation and time effects (chain position ~34, same as the plugin model).
# A true LIMITER is NOT a channel insert here — it lives on the master / a bus;
# the only per-channel "limiter-ish" tool is a clipper on individual drum hits.
#
# Each tier is a dynamics archetype with sane numbers; each instrument adds a
# one-line note (what to listen for / which tool). Tool guidance, per your
# question: reach for Cubase's built-in Channel-Strip compressor for routine
# levelling (zero plugin load, fully recallable) and keep IZotope Neutron's
# Compressor for the few channels that want its visual assistant or multiband
# (lead vocal, bass, mix/group bus).
COMP_COLOUR = "#c9a0ff"   # soft violet, distinct from the other footnote colours

# tier -> starting numbers.  gr = target gain-reduction on the loudest moments.
COMP_SPEC = {
    "none":   {"label": "NONE",    "ratio": "—",        "attack": "—",        "release": "—",            "gr": "0 dB",   "knee": "—",      "plain": "leave it — keep the natural dynamics"},
    "gentle": {"label": "GENTLE",  "ratio": "1.5–2:1",  "attack": "20–30 ms", "release": "auto / 150–300 ms", "gr": "1–3 dB", "knee": "soft",   "plain": "transparent levelling"},
    "vocal":  {"label": "VOCAL",   "ratio": "3–4:1",    "attack": "5–10 ms",  "release": "auto / 60–120 ms",  "gr": "3–6 dB", "knee": "soft",   "plain": "even, up-front level (serial: a slow leveller into a faster peak tamer beats one hard squeeze)"},
    "bass":   {"label": "BASS",    "ratio": "3–5:1",    "attack": "10–20 ms", "release": "60–120 ms",     "gr": "3–6 dB", "knee": "medium", "plain": "steady low end so every note is even"},
    "punch":  {"label": "PUNCH",   "ratio": "4:1",      "attack": "15–30 ms", "release": "80–150 ms / auto", "gr": "3–6 dB", "knee": "medium", "plain": "slow-ish attack lets the transient through, then it clamps"},
    "tame":   {"label": "TAME",    "ratio": "4–6:1",    "attack": "3–10 ms",  "release": "50–100 ms",     "gr": "4–8 dB", "knee": "hard",   "plain": "catch unruly peaks"},
    "glue":   {"label": "GLUE",    "ratio": "2:1",      "attack": "30 ms",    "release": "auto / 300 ms", "gr": "1–3 dB", "knee": "soft",   "plain": "bus glue — the meter should barely move"},
    "control":{"label": "CONTROL", "ratio": "2.5–3:1",  "attack": "10–20 ms", "release": "100 ms",        "gr": "2–4 dB", "knee": "soft",   "plain": "keep it sitting without squashing the life out"},
}

# id -> (tier, note).  Order/instrument logic mirrors the EQ recipes.
COMPRESSION = {
    "vocals_lead":      ("vocal",   "The most important compressor in the mix. Two stages beat one: a slow 2:1 leveller, then a faster 3–4:1 to catch peaks. De-ess AFTER, not before."),
    "vocals_backing":   ("vocal",   "Squeeze a touch harder than the lead so the stack stays even and sits behind it. Bus the harmonies and glue them together too."),
    "vocals_choir_pad": ("gentle",  "It is already a smooth bed — just level it. Heavy comp makes a held pad breathe/pump."),
    "vocals_extra":     ("gentle",  "Level it, do not squeeze it: a held vowel or a whisper breathes with a fast compressor, and the tail of a trailing word is the whole point."),
    "kick":             ("punch",   "Slow attack (20–30 ms) keeps the beater click; medium release for groove. Or skip comp and just clip the peaks. Trigger the bass sidechain from here."),
    "snare":            ("punch",   "Let the crack through (attack 15–30 ms), then clamp the body. Parallel ('New York') comp adds size without killing the hit."),
    "hihat":            ("gentle",  "Usually skip it. A whisker only if the dynamics are wild; cymbals/hats don't want pumping."),
    "ride":             ("gentle",  "Like the hi-hat — usually none. Keep the ping tight; control it on the overhead/drum bus instead."),
    "cymbals":          ("gentle",  "Don't compress crashes on their own — glue them on the drum/overhead bus."),
    "toms":             ("punch",   "Punch them like the snare; gate the bleed first, then compress for body and sustain."),
    "percussion":       ("tame",    "Fast attack to tame stray loud hits so the loop is even; watch for pumping on busy parts."),
    "hand_drums":       ("punch",   "Same as the toms: let the slap through, then catch the ring. A hand player is far more dynamic than a loop, so expect to work harder here than on the shaker channel."),
    "bass_root":        ("bass",    "Consistency is everything — every note the same level. Pair with the kick sidechain (time-domain clash EQ can't fix). Multiband if only the lows jump."),
    "bass_loop":        ("bass",    "Same as the root bass — even it out so the riff is solid under everything."),
    "guitar_rhythm":    ("control", "Light control so strums sit steady; don't over-do it or the chug loses its push. Bus both guitars together."),
    "guitar_chords":    ("control", "Gentle levelling so held chords don't surge. Glue with the other guitars on a bus."),
    "guitar_lead":      ("control", "A bit more than rhythm for sustain in solos; medium attack keeps pick attack. Add the sustain you want, not mush."),
    "guitar_single_low":("control", "Even out the single-note line so it stays present without jumping forward."),
    "guitar_acoustic":  ("control", "A strum is far louder than a picked note — levelling is what makes an acoustic sit still in a band. Medium attack keeps the pick; too much and you hear the room and the fret squeaks come up."),
    "organ":            ("gentle",  "Mostly even already — light glue at most. Heavy comp kills the drawbar swell."),
    "strings_lead":     ("control", "Even the bow out so every note of the line speaks; SLOW attack, or the swell at the front of each phrase is the first thing you flatten."),
    "organ_lead":       ("control", "More than the background organ: a melody has to stay even and forward. Medium attack so the key click/percussion at the front of each note survives — then stop, because the drawbar swell IS the phrasing."),
    "organ_melody":     ("control", "Between the bed and the lead: level the line so every note speaks, medium attack so the key click survives, and stop early - the drawbar swell is the phrasing."),
    "accordion_lead":   ("vocal",   "Treat it like a lead vocal, because that is the job it is doing: a slow leveller into a faster peak tamer. The bellows swing is enormous and an uncompressed reed lead either disappears or takes over."),
    "flute_bg":         ("gentle",  "Unlike the solo flute (which wants NO compressor at all), a bed has to sit still — light levelling, nothing more."),
    "violin_bg":        ("control", "More than the solo violin: a bed must not swell. Slow attack so the bow still speaks."),
    "accordion":        ("control", "Bellows pushes and pulls are not equally loud — light levelling keeps every phrase audible. Don't squash it: the bellows swell IS the expression."),
    "piano_bg":         ("gentle",  "Just level it so it sits back politely; don't squash the dynamics that make it musical."),
    "piano_riff":       ("control", "A hook should stay forward and even — a touch more than the background piano, medium attack to keep the hammer."),
    "flute":            ("none",    "Leave it — flute lives on its breath dynamics. If anything, ride the fader instead of compressing."),
    "brass":            ("punch",   "Tame the stab peaks so they don't spike; then glue the section on a brass bus for one cohesive body."),
    "brass_lead":       ("tame",    "Same problem as the trumpet, and it is a LEVEL problem that no EQ fixes: a played line swings 20 dB between a held note and a stab. Catch the peaks, then ride the fader for the musical shape."),
    "trumpet":          ("tame",    "A played trumpet swings 20 dB between a soft held note and a stab — this is a LEVEL problem, and no EQ fixes a level problem. Catch the peaks, then ride the fader for the musical shape."),
    "trombone":         ("control", "Even out the slide so every note speaks; medium attack keeps the front of the note."),
    "tenor_trombone":         ("control", "Even out the slide so every note speaks; medium attack keeps the front of the note."),
    "tenor_bass_trombone":         ("control", "Even out the slide so every note speaks; medium attack keeps the front of the note."),
    "saxophone":        ("vocal",   "Treat it like a lead vocal: a slow leveller into a faster peak tamer. The breath and growl dynamics are enormous, and an uncompressed sax either disappears or takes over."),
    "horn_section":     ("glue",    "ONE glue comp on the section bus (2:1, 1–3 dB) so the three horns breathe together. Individual comps first only to tame one wild player."),
    "harmonica":        ("tame",    "Very dynamic and very loud in the mids — clamp the peaks so a wail doesn't jump 10 dB over the vocal."),
    "woodwind":         ("gentle",  "Very light — preserve the natural air and dynamics; control the section on a bus if needed."),
    "clarinet":         ("gentle",  "Very light - the dynamic range from chalumeau whisper to clarion shout IS the instrument. Catch only the loudest top notes."),
    "oboe":             ("control", "The oboe is loud and cutting in its top range; a medium attack keeps the reed's front and the compressor catches the peaks."),
    "bassoon":          ("control", "Even out the low notes so every one speaks; medium attack keeps the front of the note."),
    "contrabassoon":    ("bass",    "Even it out like a bass so the foundation is steady; slow-ish attack keeps the articulation."),
    "flugelhorn":       ("control", "Swings 15-20 dB between a soft held note and a stab. Catch the peaks, then ride the fader for the musical shape."),
    "french_horn":      ("control", "Very dynamic - a horn goes from a whisper to a roar. Medium attack, gentle ratio; the section belongs on a bus."),
    "tuba":             ("bass",    "Even it out like a bass so the low foundation is steady; slow-ish attack keeps the front of the note."),
    "english_horn":     ("gentle",  "Very light - it is quiet and slow; preserve the natural dynamics."),
    "euphonium":        ("control", "Even out the low notes so every one speaks; medium attack keeps the front of the note."),
    "bass_clarinet":    ("gentle",  "Light - the dynamic range from whisper to roar is the instrument. Catch only the loudest notes."),
    "contrabass_clarinet": ("bass", "Even it out like a bass so the foundation is steady; slow-ish attack keeps the articulation."),
    "double_bass_section": ("bass", "Even it out like a bass so the low foundation is steady; one gentle compressor on the section bus, not one per player."),
    "piccolo": ("control", "Loud and piercing in the top register; catch the peaks, then ride the fader."),
    "alto_flute": ("gentle", "Very light - preserve the natural breath and dynamics."),
    "bass_flute": ("gentle", "Very light - it is already quiet; preserve the dynamics and ride the fader."),
    "soprano_sax": ("vocal", "Treat it like a lead vocal: a slow leveller into a faster peak tamer. Breath and squeal dynamics are large."),
    "alto_sax": ("vocal", "Treat it like a lead vocal: a slow leveller into a faster peak tamer. An uncompressed sax either disappears or takes over."),
    "tenor_sax": ("vocal", "Treat it like a lead vocal: a slow leveller into a faster peak tamer. Breath and growl dynamics are large."),
    "baritone_sax": ("control", "Even out the low notes so every one speaks; medium attack keeps the front of the note."),
    "piccolo_trumpet": ("tame", "A piccolo trumpet swings widely and is piercing - catch the peaks, then ride the fader."),
    "alto_trombone": ("control", "Even out the slide so every note speaks; medium attack keeps the front of the note."),
    "bass_trombone": ("control", "Even out the low notes so every one speaks; medium attack keeps the front of the note."),
    "double_bass_trombone": ("control", "Even out the low notes so every one speaks; medium attack keeps the front of the note."),
    "synth_pad":        ("glue",    "Usually none — a synth pad is already even. Gentle glue at most so it breathes with the mix."),
    "synth_pluck":      ("punch",   "Treat the stab like a percussive hit — let the pluck transient through, then clamp the tail."),
    "synth_mallet":     ("gentle",  "Light levelling; keep the mallet ping sharp. Don't pump the shimmer."),
    "violin":           ("gentle",  "Solo violin wants its bow dynamics — level gently only. Compress the section on a bus, not each player."),
    "viola":            ("gentle",  "Gentle inner-voice levelling; let the ensemble breathe."),
    "viola_front":      ("control", "Even the bow out so every note of the tune speaks; SLOW attack so the swell at the start of each phrase survives."),
    "cello":            ("gentle",  "Light levelling keeps the low body even without choking the bow."),
    "double_bass":      ("bass",    "Even it out like a bass guitar so the low foundation is steady; slow-ish attack keeps the pluck."),
    "string_section":   ("glue",    "Glue the whole section on ONE bus — slow, low-ratio, 1–3 dB — so it moves as one body. Skip per-player comp."),
}


def compression_for(iid, selected_ids=None):
    """Return (tier, spec_dict, note) for an instrument's compressor, or None.
    spec has: label, ratio, attack, release, gr, knee, plain (all starting points).
    Pass the current selection to get the partner-aware wording."""
    c = COMPRESSION.get(iid)
    if not c:
        return None
    tier, note = c
    return (tier, COMP_SPEC.get(tier, COMP_SPEC["gentle"]),
            partner_note("comp", iid, note, selected_ids))


# *************** DEL 02j - MULTIPLES (one, two or five of the same part) *****
# "Does it make any difference whether I have one or several of an instrument?"
# It makes a LARGE difference, and it is the difference between a mix that gets
# wider and a mix that just gets louder and cloudier. Two facts drive everything
# in this section:
#
#   1) COPY vs PERFORMANCE. Duplicating a track (copy-paste, or the same take
#      twice) adds two IDENTICAL signals: they sum coherently, so you gain
#      +6 dB and ZERO width. That is a volume knob, not an arrangement.
#      Two separate PERFORMANCES of the same part are not identical, so they sum
#      incoherently: about +3 dB, and the differences between them become the
#      stereo width. Every "double the guitars" trick in rock is this second one.
#
#   2) MASKING IS PER BAND, NOT PER TRACK. N copies of the same instrument all
#      boost the SAME band, so that band rises by ~10·log10(N) dB relative to
#      everything else. Three chord guitars do not sound like one chord guitar
#      three times — they sound like a 4.8 dB EQ boost across 200 Hz–4 kHz that
#      you never asked for. The fix is not "turn them down"; it is to give each
#      copy a different home band, a different pan position and a different
#      high-pass, so they cover ground instead of stacking on one spot.
#
# The count comes from the Song Variants tab (and, from v2.5, the spin box on
# every instrument card). Everything below is derived from it.

MULTI_COLOUR = "#ff9ec4"     # pink, distinct from the other footnote colours


def stack_gain_db(n, identical=False):
    """How much louder N copies of the same part are in their shared band.

    identical=False → separate performances, incoherent sum: 10·log10(N)
    identical=True  → the same audio duplicated, coherent sum: 20·log10(N)"""
    n = max(1, int(n))
    if n == 1:
        return 0.0
    return (20.0 if identical else 10.0) * math.log10(n)


# How far apart to spread N copies, as a percentage off centre. The width the
# instrument can take is per-family: guitars go wide, a bass never leaves the
# middle, a kit spreads by where the drum physically sits.
MULTI_SPREAD = {
    "wide":   85,    # guitars, backing vocals, plucks — hard-ish panning is the point
    "medium": 55,    # keys, horns, acoustic layers
    "narrow": 25,    # anything that must stay near the centre
    "mono":   0,     # bass, kick — never spread these
    "duet":  14,     # two lead voices at once: close either side of the middle
}


def multi_pan_ladder(n, spread="medium"):
    """Symmetric pan positions for N copies, e.g. 3 → ['L70', 'Centre', 'R70'].
    Returns plain strings ready to print — no maths for the user to do."""
    n = max(1, int(n))
    width = MULTI_SPREAD.get(spread, 55)
    if spread == "duet":
        # Same widening rule as stage_plan step 4, or the two would disagree.
        width = max(float(width), 15.0 * (n - 1) / 2.0)
    if n == 1:
        return ["Centre" if width == 0 else "its usual position"]
    if width == 0:
        return ["Dead centre — all of them"] * n
    out = []
    # Positions evenly spaced from -width to +width; the middle one lands centre.
    for i in range(n):
        pos = -width + (2.0 * width) * i / (n - 1)
        p = int(round(abs(pos) / 5.0) * 5)
        if p <= 5:
            out.append("Centre")
        else:
            out.append(("L" if pos < 0 else "R") + str(p))
    return out


# verdict → how the program talks about having more than one.
#   widen  = more copies is a WIDTH tool; spread and differentiate them
#   layer  = more copies is a TONE tool; they must split the frequency range,
#            not the stereo field (bass, kick, lead vocal)
#   kit    = several mics/pieces of one physical instrument; pan by position
#   section= it is already an ensemble; a second one is an octave/divisi decision
MULTI_VERDICT_LABEL = {
    "widen":   ("WIDTH", "More of these makes the mix WIDER — if you differentiate them."),
    "layer":   ("LAYER", "More of these makes the mix THICKER, not wider. Split the frequency range instead of the stereo field."),
    "kit":     ("SPREAD", "Several pieces of one instrument — pan them where they physically sit."),
    "section": ("SECTION", "This is already an ensemble. A second one is an octave/divisi decision, not a doubling."),
    "duet":    ("DUET", "Two lead voices at once: two singers stand either side of the middle; one singer's double sits behind the main take. Never both on one spot."),
}

# Per-instrument rules. Anything not listed falls back to MULTI_GROUP_RULE.
#   verdict · spread · sweet (how many actually help) · what · tone · trap
MULTI_ADVICE = {
    # ---- Guitars: the classic case where doubling is the whole technique ----
    "guitar_rhythm": {
        "verdict": "widen", "spread": "wide", "sweet": 4,
        "what": "Doubled rhythm guitars are the sound of rock — but ONLY as separate takes. Play the part twice, hard-pan the two takes L/R, and the small timing/pick differences become the width.",
        "tone": "Give one side more 1–3 kHz bite and the other more 150–300 Hz body; then cut on each side what you boosted on the other. Different amp/cab (or a different Telos preset) per side does more than any EQ move.",
        "trap": "Copy-pasting one take to the other side gives you +6 dB in the centre and no width at all — and it collapses to a single mono guitar the moment anyone hears it on a phone speaker."},
    "guitar_chords": {
        "verdict": "widen", "spread": "wide", "sweet": 3,
        "what": "Two chord guitars want DIFFERENT VOICINGS, not the same chord twice: one low around the open position, one high with a capo. That is what makes them sound like two instruments.",
        "tone": "The low voicing keeps 150–300 Hz warmth; the high one gets high-passed at 200 Hz+ and keeps the 2–5 kHz shimmer. Neither should have both.",
        "trap": "Same chord, same voicing, two tracks = one louder, muddier guitar sitting in the exact centre of the vocal."},
    "guitar_acoustic": {
        "verdict": "widen", "spread": "wide", "sweet": 2,
        "what": "Two acoustics is a lot of 200–500 Hz body. Record the second one with a capo or a different voicing and pan them wide apart.",
        "tone": "Let ONE keep the body (100–250 Hz); high-pass the other at 200 Hz and let it be the sparkle. Two full-range acoustics is the single most common way to cloud a mix.",
        "trap": "Both acoustics keeping their low end means the bass and the kick now share the low mids with two more instruments."},
    "guitar_single_low": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Two low single-note lines will fight, because a low line is defined by its 700 Hz–4 kHz core and they both want it.",
        "tone": "Split by octave or by register — one plays the line, the other doubles it an octave up. If they must play the same octave, give one the pick attack (2–4 kHz) and the other the note weight (90–140 Hz).",
        "trap": "Two low lines at the same octave, both centred: the notes stop being separable and just sound out of tune."},
    # ---- Bass & kick: layering, never widening ----
    "bass_root": {
        "verdict": "layer", "spread": "mono", "sweet": 2,
        "what": "Two root basses is a LAYER (sub + character), never two basses. Both must stay dead centre and mono.",
        "tone": "ONE owns below 100 Hz — high-pass the other at 100–120 Hz and let it be the grind/definition layer at 700 Hz–3 kHz. The Bass Loop card is the tidier way to say the same thing.",
        "trap": "Two full-range basses is the classic 'my low end disappears on small speakers': they are phase-fighting below 100 Hz, and no EQ fixes a phase problem."},
    "bass_loop": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "More than one bass riff wants a clear division of labour — usually by section of the song, not by playing both at once.",
        "tone": "High-pass every extra one higher than the last (80 → 120 → 160 Hz) and push each into a different midrange window.",
        "trap": "Several bass loops running at once turns the low mids into porridge and steals the kick's headroom."},
    "kick": {
        "verdict": "layer", "spread": "mono", "sweet": 3,
        "what": "Several kicks = a layered kick (sub + body + click), not several drummers. All of them stay centred and mono, and they must be phase-aligned or the low end cancels.",
        "tone": "One layer owns 40–80 Hz (the sub), one owns 80–150 Hz (the body), one owns 2–5 kHz (the beater click). High-pass every layer out of the two bands it does not own.",
        "trap": "Two unaligned kick samples cancel each other around 60 Hz — the kick gets QUIETER the more you add. Nudge one sample a few samples until the low end grows."},
    "snare": {
        "verdict": "layer", "spread": "narrow", "sweet": 3,
        "what": "Top + bottom + sample is a layered snare. Keep them centred; the width comes from the overheads, not from panning the snare.",
        "tone": "Top mic owns 100–250 Hz body and the stick, bottom mic owns 5–8 kHz wires (high-pass it at 300 Hz), the sample fills whatever is missing.",
        "trap": "The bottom mic is usually phase-inverted against the top — flip its polarity, or the body of the snare vanishes."},
    # ---- Kit pieces: spread by physical position ----
    "toms": {
        "verdict": "kit", "spread": "wide", "sweet": 4,
        "what": "Toms are one instrument in several channels. Pan them where they sit on the kit: floor tom left-ish, rack toms toward the right (or mirrored, for the drummer's perspective).",
        "tone": "Each tom has its OWN fundamental (floor ≈80 Hz, rack ≈200 Hz) — find and boost each one separately, and cut 200–400 Hz on all of them.",
        "trap": "Gates matter more than EQ here: three open tom channels means three copies of the whole kit bleeding into the mix. Once you have 2+ toms they belong on a Drums: Toms bus with ONE set of plug-ins."},
    "hand_drums": {
        "verdict": "kit", "spread": "wide", "sweet": 3,
        "what": "Congas and bongos come in sets, and a set is ONE player: pan them where the hands are, low drum to one side of the high one, not scattered across the stage.",
        "tone": "Each drum has its own fundamental \u2014 conga \u2248 200 Hz, quinto higher, djembe \u2248 120 Hz. Tune the boost per channel and cut 250\u2013500 Hz on all of them.",
        "trap": "Two full hand-drum sets is two players in the same square metre. Either they play different patterns and sit apart, or you only needed one."},
    "percussion": {
        "verdict": "kit", "spread": "wide", "sweet": 4,
        "what": "Several percussion parts are texture — they only work when each sits in a different place and a different band.",
        "tone": "Shaker up at 8–12 kHz, tambourine at 5–10 kHz, cowbell/woodblock at 1–3 kHz. High-pass all of them hard and give each a different one of those windows.",
        "trap": "Three shakers panned around the same spot is just hiss. And every extra percussion layer eats the cymbals' air."},
    "cymbals": {
        "verdict": "kit", "spread": "wide", "sweet": 3,
        "what": "Overheads/crashes as a stereo picture — the width IS the point.",
        "tone": "Keep the pair wide, high-pass each channel, and let only ONE of them carry the 10 kHz+ shelf, or the top of the mix turns to hiss.",
        "trap": "More cymbal channels = more kick/snare bleed arriving at slightly different times, which smears the whole kit. High-pass at 300–600 Hz first."},
    # ---- Vocals ----
    "vocals_lead": {
        "verdict": "duet", "spread": "duet", "sweet": 2,
        "what": "Two lead voices at once are one of two different things. TWO SINGERS (a duet) are equal partners: close either side of the middle at ONE shared Distance, so neither is the 'second' voice. ONE singer double-tracked is a LAYER: main take centred, the double slightly quieter and a step further back (Distance +8).",
        "tone": "Two singers: the same high-pass on both, each keeps their own low end. One singer doubled: high-pass the double higher than the main take (150 Hz) and dip its 3–5 kHz so it never competes.",
        "trap": "Two different singers both dead centre at the same Distance is two people standing in one spot — they mask each other and neither one is the lead. And a double panned WIDE makes one singer sound like two people and collapses badly in mono."},
    "vocals_backing": {
        "verdict": "widen", "spread": "wide", "sweet": 6,
        "what": "This is the one place where MORE is genuinely better: stacked backing vocals get smoother and wider with every honest new take.",
        "tone": "Hard-pan them in PAIRS (L/R, then L60/R60, then L30/R30) so the stack stays balanced. Bus them all and do the EQ once, on the bus.",
        "trap": "Every extra layer adds 200–500 Hz mud and 6–9 kHz sibilance. High-pass the stack at 150 Hz, cut the mud on the BUS, and de-ess the bus rather than each take."},
    "vocals_extra": {
        "verdict": "widen", "spread": "wide", "sweet": 3,
        "what": "More layers of ooh/aah is how a wash is built - each one a different vowel or octave, panned apart.",
        "tone": "Only the TOP layer keeps the 8-12 kHz air; high-pass the others higher and let each one own a different band.",
        "trap": "Several held vowels on the same note stack 250-500 Hz mud and breath noise fast. High-pass the stack and EQ it once, on the bus."},
    "vocals_choir_pad": {
        "verdict": "section", "spread": "wide", "sweet": 2,
        "what": "A sampled choir is already dozens of voices. A second one is a register decision (high pad + low pad), not a doubling.",
        "tone": "Split them by octave and let only the upper one keep the 8–12 kHz air.",
        "trap": "Two full-range choir pads mask everything in 400–800 Hz at once — it is the fastest way to lose a lead vocal."},
    # ---- Keys ----
    "organ": {
        "verdict": "widen", "spread": "medium", "sweet": 2,
        "what": "Two organs usually means two registrations (drawbar settings) rather than two players — treat them as different instruments.",
        "tone": "One takes the low drawbars (100–200 Hz warmth), the other the upper harmonics (1–3 kHz Leslie presence). High-pass the upper one at 200 Hz.",
        "trap": "Two full organ registrations pile up in 200–800 Hz and swallow the guitars."},
    "accordion_lead": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Two accordion melodies is a harmony or it is a mistake — musette tuning already beats two reeds against each other inside ONE instrument.",
        "tone": "Split by octave and let only the upper one keep 2–4 kHz; the lower one keeps body and blends.",
        "trap": "A lead accordion over a padding accordion is not a double — it is this card over the Accordion card, and if both play the bass side you have doubled the bass part twice over."},
    "flute_bg": {
        "verdict": "widen", "spread": "medium", "sweet": 2,
        "what": "Two held flutes is how you get a real pad out of a real instrument — this is one of the few places a second take genuinely helps.",
        "tone": "Pan them apart and split by octave; high-pass the upper one at 400 Hz so only one of them carries body.",
        "trap": "Two flutes both keeping their 4–8 kHz breath is two lots of hiss, and it lands exactly on the singer's consonants."},
    "violin_bg": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "Layered held violins is literally how a string section is built — but at three or more, stop and use the String Section card instead.",
        "tone": "Pan in pairs, split by octave, and do the EQ ONCE on a bus rather than per take.",
        "trap": "Every layer adds 200–500 Hz, and a bed has no transient to hide it behind. High-pass each layer separately."},
    "brass_lead": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Two horn lines is a harmony, and a harmony is written, not doubled: decide which is the tune and which is the third under it.",
        "tone": "Keep the 1.5–3 kHz core on the TOP line only; the lower one lives on body and blends. Same reverb on both or they stop being one section.",
        "trap": "Doubling a lead line with the stab card underneath is not a double — it is two cards fighting over 2–5 kHz, and the tune loses."},
    "strings_lead": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "A second string melody is an octave or a harmony, never the same line twice — unison sampled strings just smear the attack.",
        "tone": "Split them by octave and give only the upper one the 3–6 kHz bow bite; the lower one keeps body.",
        "trap": "Layering Strings (lead) on top of the String Section bed and EQ-ing both the same way is the classic way to end up with a loud, wide, inaudible tune."},
    "organ_lead": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Two lead organs is two melodies — an arrangement decision, not a mix one. Normally they should take turns.",
        "tone": "If both must play, split them by octave and let only ONE own the 1–3 kHz note core at a time; the other drops to a harmony underneath.",
        "trap": "A lead organ plus a background organ is NOT a double — it is this entry plus the Organ (background) entry, played by one pair of hands. Give them the same EQ and both disappear."},
    "organ_melody": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "A second line on the organ is a harmony or a counter-melody - written, not doubled. Decide which line is on top.",
        "tone": "Let the top line keep the 1-3 kHz note core and give the lower one more body (150-300 Hz) with a firmer mud cut; pan them a few percent apart.",
        "trap": "Two organ lines with identical EQ and identical reverb are heard as one thick line - give each its own slot, or they stop being two voices."},
    "accordion": {
        "verdict": "widen", "spread": "medium", "sweet": 2,
        "what": "Two accordions in the same musette tuning beat against each other in a way that is either beautiful or seasick — there is no middle.",
        "tone": "Give one the left-hand/bass side and the other the treble reeds, and high-pass the treble one at 200 Hz.",
        "trap": "Two accordions both playing left-hand bass reeds doubles the bass part twice over."},
    "piano_bg": {
        "verdict": "widen", "spread": "medium", "sweet": 2,
        "what": "Two comping pianos rarely helps — a second one is usually a register split (low comp + high sparkle).",
        "tone": "Low one keeps 100–250 Hz, high one is high-passed at 300 Hz and keeps only the 2 kHz+ detail.",
        "trap": "Two stereo pianos is four channels of 300–500 Hz mud sitting right where the vocal needs room."},
    "piano_riff": {
        "verdict": "layer", "spread": "medium", "sweet": 2,
        "what": "Two hooks at once is an arrangement problem, not a mix problem — normally they should alternate.",
        "tone": "If both must play, split them by octave and let only one have the 1–3 kHz hook window at a time.",
        "trap": "Two riffs fighting for the same hook slot means the listener hears neither."},
    "synth_pad": {
        "verdict": "widen", "spread": "wide", "sweet": 3,
        "what": "Layered pads is normal synth practice — a low warm one, a mid body one, a high air one.",
        "tone": "Assign each layer ONE band and high-pass the rest away: low pad below 400 Hz, mid pad 400 Hz–3 kHz, air pad above 4 kHz. Every layer must still be dipped at 3–5 kHz under a vocal.",
        "trap": "Three full-range pads is a wall — you will not be able to hear anything else, and the mix will still feel empty because nothing has definition."},
    "synth_pluck": {
        "verdict": "widen", "spread": "wide", "sweet": 4,
        "what": "Multiple plucks/stabs are a rhythm texture. Pan them apart and give them different delay times so they answer each other.",
        "tone": "Different pitch registers per copy, and only one of them gets the 8–12 kHz zing shelf.",
        "trap": "Several bright plucks on the same beat is a click, not a groove — offset them rhythmically."},
    "synth_mallet": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "Mallet layers work when they are in different octaves.",
        "tone": "Only the top layer keeps the 8–14 kHz shimmer, or you are stacking bell tops against the cymbals.",
        "trap": "The 8 kHz+ shimmer adds up fastest of anything in the mix — three mallets is three shelves."},
    # ---- Horns ----
    "trumpet": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "Two or three trumpets is a SECTION — and a section is written in harmony, not in unison. Unison trumpets just get louder and more strident.",
        "tone": "Pan them apart, keep the lead trumpet a little brighter (3–5 kHz) and roll the harmony parts back so the top voice reads as the melody.",
        "trap": "Every trumpet adds 3–6 kHz blare. Three of them is a genuinely painful mix — cut that band on the section BUS, once."},
    "saxophone": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "Two saxes should be different HORNS (alto + tenor, or tenor + bari), not two of the same. Same horn twice just doubles the reed honk.",
        "tone": "Split by register: the low horn keeps 150–350 Hz, the high one gets high-passed at 200 Hz and keeps the 1–5 kHz reed core.",
        "trap": "Two saxes in the same register behind a singer is two extra voices in the vocal's slot — the words go first."},
    "trombone": {
        "verdict": "layer", "spread": "medium", "sweet": 3,
        "what": "Multiple bones stack in the low mids exactly where the bass lives.",
        "tone": "One carries the bottom line (100–250 Hz); high-pass the rest at 150–200 Hz so they add harmony without adding weight.",
        "trap": "Three trombones at full weight will bury a bass guitar without ever sounding loud."},
    "tenor_trombone": {
        "verdict": "layer", "spread": "medium", "sweet": 3,
        "what": "Multiple bones stack in the low mids exactly where the bass lives.",
        "tone": "One carries the bottom line (100–250 Hz); high-pass the rest at 150–200 Hz so they add harmony without adding weight.",
        "trap": "Three trombones at full weight will bury a bass guitar without ever sounding loud."},
    "tenor_bass_trombone": {
        "verdict": "layer", "spread": "medium", "sweet": 3,
        "what": "Multiple bones stack in the low mids exactly where the bass lives.",
        "tone": "One carries the bottom line (100–250 Hz); high-pass the rest at 150–200 Hz so they add harmony without adding weight.",
        "trap": "Three trombones at full weight will bury a bass guitar without ever sounding loud."},
    "horn_section": {
        "verdict": "section", "spread": "medium", "sweet": 2,
        "what": "It is already a section. A second one means a second ARRANGEMENT (stabs plus sustained pads) — treat them as two different parts.",
        "tone": "Stabs stay punchy and dry-ish; the pad section gets high-passed higher, dipped at 2–4 kHz and pushed further back with reverb.",
        "trap": "Two full sections doubling the same line is just a loud section — write them apart or use one."},
    "harmonica": {
        "verdict": "layer", "spread": "medium", "sweet": 2,
        "what": "Two harps is almost always one too many — it is a solo instrument that answers the singer.",
        "tone": "If you do stack them, one is the melody and the other a quiet octave/chord bed high-passed at 300 Hz.",
        "trap": "Two harmonicas in the same octave is a wall of 2–4 kHz right on the vocal."},
    "flute": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "Flutes stack beautifully in harmony — they are quiet and blend easily.",
        "tone": "Only the top line keeps the 4–8 kHz breath boost; the harmony parts stay softer and darker.",
        "trap": "Stacked breath noise is the giveaway of a sampled flute section — pull the 4–8 kHz band down on all but the lead."},
    "clarinet": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "A clarinet choir is a classic sound - several clarinets in harmony blend into one warm body.",
        "tone": "Keep the lead clarinet a little brighter (1-3 kHz) and roll the harmony parts back so the top voice reads as the melody.",
        "trap": "Clarinets in unison are just a louder clarinet - write them in harmony, and pull the hollow 500-900 Hz on the stack."},
    "oboe": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "One oboe is a voice; two in unison is a thicker, more nasal oboe. An oboe pair works in harmony.",
        "tone": "Pan them a little apart, keep one the lead (2-4 kHz presence) and let the other sit darker.",
        "trap": "Every oboe adds 1-1.5 kHz nasal honk - cut that band on the pair once, not on each."},
    "bassoon": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "A pair of bassoons gives a rich tenor/bass bed, but they stack energy at 80-250 Hz very fast.",
        "tone": "One carries the bottom line, the other is high-passed at about 120 Hz and plays the harmony.",
        "trap": "Two bassoons plus cellos is a wall of 100-300 Hz that muddies any mix."},
    "contrabassoon": {
        "verdict": "layer", "spread": "mono", "sweet": 1,
        "what": "One is plenty - it is the lowest woodwind, and a second is only ever a different register.",
        "tone": "Whichever is playing owns below 80 Hz; the other is high-passed and muted when it is not needed.",
        "trap": "A contrabassoon plus a double bass plus a bass guitar is three instruments in the same 40-80 Hz window."},
    "flugelhorn": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "Flugelhorns are written in harmony like trumpets and give a darker, warmer section sound.",
        "tone": "Pan them apart, keep the lead brighter at 1.5-3 kHz and roll the harmony parts back.",
        "trap": "Stacked warmth at 200-400 Hz gets muddy fast - high-pass the harmony parts higher."},
    "french_horn": {
        "verdict": "section", "spread": "wide", "sweet": 4,
        "what": "Horns are written as a section of four; more horns is how the sound gets big and soft at the same time.",
        "tone": "Ladder them across the stage at one Distance, keep the lead horn a bit brighter and roll the others off above 6 kHz.",
        "trap": "Four horns stack 300-500 Hz fog - cut that band on the section BUS, once."},
    "tuba": {
        "verdict": "layer", "spread": "mono", "sweet": 1,
        "what": "One tuba is the right number. A second one is only ever a different register (tuba vs euphonium) or an octave double.",
        "tone": "Whichever is playing owns below 100 Hz; the other is high-passed and plays the harmony.",
        "trap": "A tuba plus a bass guitar plus a kick is three instruments in the same 40-100 Hz window."},
    "english_horn": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "One English horn is a voice. A second doubles an oboe line or plays the harmony.",
        "tone": "Keep one the lead and the other darker, 1-2 dB lower.",
        "trap": "Two double reeds stack the 700 Hz-1.2 kHz nasal honk - cut it on the pair once."},
    "euphonium": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "A pair of euphoniums gives a rich tenor-brass bed, but it stacks energy at 100-300 Hz very fast.",
        "tone": "One carries the bottom line, the other is high-passed at about 120 Hz and plays the harmony.",
        "trap": "Two euphoniums plus trombone and cello is a wall of 100-300 Hz."},
    "bass_clarinet": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Two bass clarinets in unison are just a bigger bass clarinet; in harmony they are a dark woody bed.",
        "tone": "One carries the line, the other is high-passed at about 100 Hz.",
        "trap": "Stacked hollow 300-600 Hz makes the pair sound like a tube."},
    "contrabass_clarinet": {
        "verdict": "layer", "spread": "mono", "sweet": 1,
        "what": "One is plenty - it is the lowest clarinet, and a second is only ever a different register.",
        "tone": "Whichever is playing owns below 80 Hz; the other is high-passed.",
        "trap": "A contrabass clarinet plus a double bass plus a bass guitar is three instruments in the same 40-80 Hz window."},
    "double_bass_section": {
        "verdict": "section", "spread": "narrow", "sweet": 1,
        "what": "Already an ensemble. A second section is a register or articulation decision (arco bed plus pizzicato line), not more weight.",
        "tone": "The section owns below 100 Hz; the second one is high-passed and plays the articulated line.",
        "trap": "Two bass sections plus a bass guitar is a wall of 50-250 Hz that no kick survives."},
    "piccolo": {
        "verdict": "layer", "spread": "narrow", "sweet": 1,
        "what": "One piccolo is plenty; a second is an octave double or a different part, not more of the same.",
        "tone": "Keep one the lead and the other much quieter and further back.",
        "trap": "Two piccolos is a wall of 2-4 kHz shrill that no hi-hat survives."},
    "alto_flute": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "A flute choir is a classic sound; alto flutes stack beautifully in harmony.",
        "tone": "Only the top line keeps the presence boost; the harmony parts stay darker and softer.",
        "trap": "Stacked breath noise gives away a sampled flute section - pull 5-8 kHz down on all but the lead."},
    "bass_flute": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "A second bass flute adds hollow low-mid weight rather than width.",
        "tone": "One carries the line, the other is high-passed at 200 Hz.",
        "trap": "Two bass flutes plus a bass clarinet is a pile of hollow 150-400 Hz."},
    "soprano_sax": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Two sopranos in unison are just a louder, more nasal soprano. Write them in harmony.",
        "tone": "Keep one the lead and the other darker, 1-2 dB lower.",
        "trap": "Every soprano adds 3.5-6 kHz squeal - cut it on the pair once."},
    "alto_sax": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "A sax section is written in harmony, not unison; altos stack into a rich section.",
        "tone": "Pan them apart, keep the lead brighter at 1-3 kHz and roll the harmony parts back.",
        "trap": "Every sax adds 400-800 Hz box - cut it on the section bus, once."},
    "tenor_sax": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "A sax section is written in harmony; tenors give it body.",
        "tone": "Pan them apart, keep the lead brighter and the harmony parts darker.",
        "trap": "Several tenors stack 120-300 Hz body - high-pass the harmony parts higher."},
    "baritone_sax": {
        "verdict": "layer", "spread": "narrow", "sweet": 1,
        "what": "One baritone is the right number. A second is an octave double or a different part.",
        "tone": "Whichever is playing owns below 100 Hz; the other is high-passed.",
        "trap": "A baritone plus a bass guitar plus a kick is three instruments in the same 80-200 Hz window."},
    "piccolo_trumpet": {
        "verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Piccolo trumpets are rarely doubled; a second is an octave double or a harmony.",
        "tone": "Keep one the lead and the other quieter and further back.",
        "trap": "Every piccolo trumpet adds 3-6 kHz blare - cut that band once on the pair."},
    "alto_trombone": {
        "verdict": "widen", "spread": "medium", "sweet": 3,
        "what": "A trombone section is written in harmony; the alto takes the top voice.",
        "tone": "Pan them apart, keep the top voice brighter.",
        "trap": "Trombones stack 300-600 Hz mud - cut it on the section BUS, once."},
    "bass_trombone": {
        "verdict": "layer", "spread": "mono", "sweet": 1,
        "what": "One bass trombone is the foundation of the section; a second is only ever a different register.",
        "tone": "Whichever plays the bottom note owns below 100 Hz; the other is high-passed.",
        "trap": "A bass trombone plus a tuba plus a bass guitar is three instruments in the same 60-150 Hz window."},
    "double_bass_trombone": {
        "verdict": "layer", "spread": "mono", "sweet": 1,
        "what": "One double-bass trombone is the foundation of the section; a second is only ever a different register.",
        "tone": "Whichever plays the bottom note owns below 100 Hz; the other is high-passed.",
        "trap": "A double-bass trombone plus a tuba plus a bass guitar is three instruments in the same 60-150 Hz window."},
    # ---- Strings ----
    "violin": {
        "verdict": "widen", "spread": "medium", "sweet": 4,
        "what": "More violins is how a string section is built — and unlike guitars, they SHOULD be slightly out of tune with each other. That is the ensemble sound.",
        "tone": "Spread them across the field, detune/offset each take a hair, and let only the section as a whole carry the 8–12 kHz silk.",
        "trap": "Perfectly identical violin takes sound like a chorus effect, not like players. And every take adds 3–6 kHz bow scratch."},
    "viola":  {"verdict": "widen", "spread": "medium", "sweet": 4,
        "what": "Inner voices — more of them thickens the middle of the section.",
        "tone": "Keep them darker than the violins and cut 600–900 Hz on the stack.",
        "trap": "Violas pile up in exactly the 200–500 Hz range that clouds a mix."},
    "viola_front": {"verdict": "widen", "spread": "medium", "sweet": 4,
        "what": "More violas with the tune is a section playing the melody.",
        "tone": "Keep them darker than the violins and give each copy a slightly different bow noise cut.",
        "trap": "A viola line in the middle of the mix lands in the same 200-500 Hz as the guitars and the organ."},
    "cello":  {"verdict": "layer", "spread": "narrow", "sweet": 3,
        "what": "Several cellos add real low-mid weight — which puts them straight in the bass's way.",
        "tone": "Let one carry the bottom line; high-pass the others at 150 Hz.",
        "trap": "A cello stack under a bass guitar is the classic 'why is my low end muddy' with no obvious culprit."},
    "double_bass": {
        "verdict": "layer", "spread": "mono", "sweet": 1,
        "what": "One is the right number. A second double bass is only ever a different sound (arco vs pizz), not a doubling.",
        "tone": "Whichever is playing owns below 100 Hz; the other is high-passed and muted when it is not needed.",
        "trap": "Two of these plus an electric bass is three instruments in the same 60–100 Hz window."},
    "string_section": {
        "verdict": "section", "spread": "wide", "sweet": 2,
        "what": "Already an ensemble. A second one is a register/articulation decision (a legato bed plus a staccato line).",
        "tone": "Bed stays wide and far back; the articulated line comes forward, high-passed higher.",
        "trap": "Two lush full-range sections is a wall of 400–800 Hz that no vocal survives."},
    # ---- Timekeepers ----
    "hihat": {"verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "Two hats normally means a live hat plus a programmed one.",
        "tone": "Pan them a little apart and let only one carry the 8–12 kHz air shelf.",
        "trap": "Two hats stacking their air shelves is where a mix starts sounding brittle."},
    "ride":  {"verdict": "layer", "spread": "narrow", "sweet": 2,
        "what": "More than one ride is unusual — usually a ride plus a second cymbal doing a different job.",
        "tone": "Keep only one 3–5 kHz ping forward; tame the other's 5–8 kHz wash.",
        "trap": "Two long cymbal washes smear the top of everything."},
}

# Fallback when an instrument has no specific entry: one rule per family.
MULTI_GROUP_RULE = {
    "Vocals": ("widen", "wide",
        "Stacked voices widen — pan them in pairs, bus them, and do the EQ and "
        "de-essing once on the bus."),
    "Drums & Percussion": ("kit", "wide",
        "Pan by where the piece physically sits, gate the bleed, and put them on "
        "a shared bus with one set of plug-ins."),
    "Bass": ("layer", "mono",
        "Bass parts never widen — they divide the frequency range. One owns the "
        "bottom; high-pass the rest."),
    "Guitar": ("widen", "wide",
        "Separate takes, hard-panned, with different tone per side. A copied "
        "take is a volume knob, not a double."),
    "Keys & Winds": ("widen", "medium",
        "Split them by register and give each copy one band to own; high-pass "
        "every copy that is not carrying the bottom."),
    "Brass": ("widen", "medium",
        "Split them by register and give each copy one band to own; high-pass "
        "every copy that is not carrying the bottom."),
    "Strings": ("widen", "medium",
        "More players = a section. Spread them, keep the takes slightly "
        "different, and let only the section as a whole carry the air."),
}


for _g in ("Winds", "Keys", "Other"):
    MULTI_GROUP_RULE[_g] = MULTI_GROUP_RULE["Keys & Winds"]


def multi_rule(iid, group=""):
    """The MULTI_ADVICE entry for an instrument, or a group-level fallback."""
    r = MULTI_ADVICE.get(iid)
    if r:
        return r
    verdict, spread, what = MULTI_GROUP_RULE.get(
        group, ("widen", "medium",
                "Spread the copies apart and give each one its own band to own."))
    return {"verdict": verdict, "spread": spread, "sweet": 3,
            "what": what, "tone": "", "trap": ""}


def multiples_plan(iid, n, group="", lowcut=None, depth_tier=None):
    """The full 'you have N of these' plan.

    Returns None for n <= 1 (nothing to say). Otherwise a dict:
      verdict, label, headline, gain_db, gain_line, pan[], hp[], level, reverb,
      bus, what, tone, trap, too_many
    Every number is derived, so it stays right for any count the user types."""
    n = max(1, int(n))
    if n < 2:
        return None
    r = multi_rule(iid, group)
    verdict = r["verdict"]
    label, headline = MULTI_VERDICT_LABEL.get(verdict, MULTI_VERDICT_LABEL["widen"])
    spread = r.get("spread", "medium")

    inc = stack_gain_db(n)          # separate performances
    coh = stack_gain_db(n, True)    # duplicated audio

    gain_line = (
        f"{n} separate takes are about +{inc:.1f} dB louder in the band they share; "
        f"{n} copies of the SAME audio are +{coh:.1f} dB and give you no width at all. "
        f"Pull each copy down roughly {inc:.1f} dB from where a single one sat, or "
        f"the section quietly becomes a {inc:.1f} dB EQ boost across its whole range.")

    pan = multi_pan_ladder(n, spread)
    # Ready-to-print version: a mono/centred part says it ONCE, not N times.
    if len(set(pan)) == 1:
        pan_line = pan[0]
    else:
        pan_line = "  ·  ".join(f"#{i+1} {p}" for i, p in enumerate(pan))

    # High-pass ladder: every copy after the first is cut higher, so only ONE of
    # them carries the low end of that instrument.
    hp = []
    if lowcut and spread != "mono":
        base = lowcut[0]
        for i in range(n):
            hz = int(round(base * (1.0 + 0.30 * i) / 5.0) * 5)
            hp.append(f"#{i+1}: {hz} Hz" + ("  (keeps the low end)" if i == 0 else ""))
    elif spread == "mono":
        hp = ["Only ONE of them keeps the low end — high-pass every other copy "
              "at least an octave above it."]
    elif spread == "duet":
        hp = ["Two different singers: the SAME high-pass on each, because each "
              "has a low end of their own. Only if #2 is a double of the same "
              "singer: high-pass #2 at about 150 Hz."]

    level = (f"#1 at the level you would give a single one, then each further copy "
             f"1–2 dB below the one before it. One of them has to be 'the' part.")

    reverb = ("Keep #1 at its normal reverb depth and push each further copy one "
              "step further back. Same depth on all of them is what makes copies "
              "sound stuck together instead of spread out.")
    if depth_tier == "dry":
        reverb = ("These stay DRY — depth here comes from level and tone, not "
                  "from reverb.")

    bus = (f"{n} channels of one instrument earn a BUS: one glue compressor, one "
           f"smart:EQ slot, one duck and one reverb send for the whole group. Do "
           f"the shared cuts there, not {n} times over.")

    sweet = r.get("sweet", 3)
    too_many = ""
    if n > sweet:
        too_many = (f"{n} is more than this part usually rewards (about {sweet}). "
                    f"Past that point each extra copy adds masking and level but "
                    f"almost no width — consider muting one and hearing whether "
                    f"anything is actually missing.")

    return {"n": n, "verdict": verdict, "label": label, "headline": headline,
            "gain_db": inc, "gain_line": gain_line, "pan": pan,
            "pan_line": pan_line, "hp": hp,
            "level": level, "reverb": reverb, "bus": bus,
            "what": r.get("what", ""), "tone": r.get("tone", ""),
            "trap": r.get("trap", ""), "too_many": too_many}


# *************** DEL 02m - VIRTUAL STAGE (EVA Instruments) ******************
# "Where does this channel STAND?" — EVA Instruments' Virtual Stage (v1.2) puts
# a source at a point inside a virtual room and moves EQ, delay, stereo width,
# balance, panning and reverb together to get it there. Three controls carry
# the whole plug-in:
#
#   POSITION  — left/right on the stage (Centre is centre).
#   DISTANCE  — 0 = in your face … 100 = against the back wall. Your own first
#               preset ("Test1-virtual stage") is Distance 45, Position centre,
#               so 45 is what this program treats as the middle of the stage.
#   ROOM      — Small / Medium / Large: the acoustic the reflections come from.
#   LOCK POSITION — moves a source front/back WITHOUT changing its left/right.
#               That is the mode for anything that must stay dead centre.
#
# THERE ARE NO FIXED PER-INSTRUMENT PRESETS HERE, ON PURPOSE - and since v3.20 a
# generated preset is a SNAPSHOT of the current stage, named by its numbers (DEL 02t).
# Every number here depends on what ELSE is in the song, so a preset saved as
# "Cello" would be a lie the moment you add or remove a channel. A lone rhythm
# guitar does not want the position a doubled pair wants; a ride with a hi-hat next
# to it does not want the position a ride on its own wants. So this section tells
# you what to dial in, and re-tells you the moment the line-up changes; Generate >
# Virtual Stage presets writes that answer to disk as '3---Cello---D46---L10', where
# the name says what is in the file, so a changed line-up makes a new name instead
# of quietly changing an old preset.
#
# TWO RULES CARRY EVERYTHING BELOW.
#
#   1) ONE SONG = ONE ROOM. The Room control is not a per-channel flavour, it
#      is the building the band is standing in. Small on the snare and Large on
#      the overheads is not "depth", it is two recordings edited together. The
#      room is picked ONCE (vstage_room) and used on every instance. Closeness
#      comes from DISTANCE, never from a smaller room.
#
#   2) A STAGE IS A SHARED SPACE. Two players cannot stand in the same spot, so
#      no instrument has a fixed position: it has a preferred spot, and then it
#      is moved by who else turned up. That is what stage_plan() does — it lays
#      out the WHOLE line-up at once, family by family, and every number it
#      prints comes with the reason it is that number.
#
# For the drum kit this matters most, so it has its own planner
# (drum_stage_plan): a kit with no toms must not be spread as wide as a kit
# with toms (the flanks would be empty and the hats would sit in a hole); a kit
# with no overheads must not be pushed as far back (nothing is carrying the
# air, so all the room comes out of the close mics and turns to wash); and a
# kick-and-snare beat must not be spread across a stage at all.

VSTAGE_COLOUR  = "#ffc98b"   # warm amber — distinct from the cyan depth line
VSTAGE_NAME    = "Virtual Stage"
VSTAGE_VERSION = "1.2"       # the version with discrete Distance/Position/Lock
VSTAGE_ROOMS   = ("Small", "Medium", "Large")

# The middle of the stage, in Distance units (0–100). 45 = your saved preset.
VSTAGE_MID = 45

# Reverb-depth tier → Distance. Same front/back ordering as DEPTH_SPEC, but
# these are Virtual Stage's own numbers: it is building the whole room, not
# feeding a send.
VSTAGE_TIER_DIST = {"front": 18, "near": 32, "mid": 50, "far": 72}

# The drum kit proper, in the order it is spoken about. Percussion is NOT part
# of it — a shaker is another player standing beside the riser.
KIT_IDS       = ("kick", "snare", "hihat", "ride", "toms", "cymbals")
KIT_OFF_RISER = ("percussion",)

# Channels Virtual Stage should not be on at all, and why. A "no" with a reason
# is worth more than a number you should not have used.
VSTAGE_SKIP = {
    "kick": ("Leave Virtual Stage OFF the kick. It is the front edge of the "
             "kit and it has to stay tight, mono and phase-true against the "
             "bass — and this plug-in adds delay, width and room to whatever "
             "it touches, which is all three of the things a kick must not "
             "have. The kick is the Distance everything else is measured from. "
             "This one does NOT change with ✖N: a layered kick is still one "
             "transient, and the beater-click layer is the single thing in the "
             "mix that must never be delayed."),
    "bass_root": ("Leave it OFF. Room on a bass is mud: the reflections arrive "
                  "a few milliseconds late and comb-filter the exact octave "
                  "your whole low end depends on. The bass is not standing "
                  "somewhere on the stage — it IS the stage."),
    "bass_loop": ("Leave it OFF, same reason as the root bass. If a bass part "
                  "needs to sound further away, do that with the low cut and "
                  "the top end, never with a room."),
}

# ---- THE ONE EXCEPTION: ✖2 ON A BASS ---------------------------------------
# "Never put a bass on the stage" is the right answer for ONE bass. It stops
# being the whole answer the moment there are two, because the second one is
# not really a bass any more. MULTI_ADVICE already splits a doubled bass into
#   • a FOUNDATION layer that owns everything below 100 Hz, and
#   • a CHARACTER layer, high-passed at 100–120 Hz, living at 700 Hz–3 kHz.
#
# The reason the plug-in is banned from a bass is entirely a low-end reason:
# its reflections arrive a few milliseconds late and comb-filter the octave the
# whole mix is built on. The character layer has no octave down there to
# comb-filter — it was high-passed out. So on THAT layer, and only that layer,
# Virtual Stage is a legitimate way to make two basses read as two bodies
# instead of one thick one.
#
# It is offered as an OPTION and never as the plan, because the answer depends
# on something this program cannot see: whether the two are ONE instrument in
# two layers (keep both OFF — a room on half of a layered sound is just a phase
# difference between two copies of the same note) or two separate PARTS (then
# it is a real placement decision, and this is the tool for it). The condition
# is printed with the option, so the choice is made on purpose.
VSTAGE_BASS_MAX_DIST = 35   # past this any bass goes woolly — the double_bass limit
VSTAGE_BASS_OPT_DIST = 30   # a touch of room, not a position at the back
VSTAGE_BASS_OPT_POS  = 12   # widest a high-passed bass layer may sit off centre

# ---- MANUAL INFLUENCE: the three things this engine cannot work out --------
# Everything above is derived from the line-up, and that is right for nearly
# all of it. Three decisions are NOT derivable, because they are about the
# ARRANGEMENT and not about the instrument:
#
#   1. ROLE - is this part carrying the song, or sitting under it? A piano
#      riff can be the hook the whole verse hangs on, or it can be the bed
#      the hook stands on. The channel is identical either way; only the
#      writing decides. So it is a hand switch: "bed" pushes it back and
#      makes it the one that YIELDS, "feature" walks it forward and makes it
#      the one that STAYS PUT.
#   2. SIDE - sometimes there is a reason nothing in a mix can see: the
#      video, the live line-up, or simply "not there, over here".
#   3. COUNTERPOLE - which part answers which. Two parts that ANSWER each
#      other must not end up on the same side, and which two those are is a
#      fact about the song, not about the instruments.
#
# Three rules this layer keeps, so a hand placement never quietly becomes a
# lie:
#
#   * Every override writes its own line, and every one of those lines
#     starts with a hand and the word YOU. The sheet must always say which
#     numbers are its own and which are yours. Those lines are SETTINGS,
#     not reasons, so they are never hidden with the why-lines.
#   * The kit is not up for negotiation. drum_stage_plan lays the kit out as
#     ONE object, and a snare dragged out of it is not a placement, it is a
#     broken kit. Same for VSTAGE_SKIP: "leave it OFF" has a reason next to
#     it, and a position would contradict that reason.
#   * Collisions are still checked afterwards. A hand-placed channel WINS
#     the collision - the engine moves the other one - but when two
#     hand-placed channels collide NEITHER is moved and both are told so.
#     Inventing a compromise there would silently undo the very decision
#     that was made on purpose.

STAGE_HAND = "\u270b"          # the marker every hand-set line starts with

# What the sheet says about a role it applied. %s = hand, %d -> %d = Distance.
STAGE_ROLE_BECAUSE = {
    "lead": "%s YOU marked this the LEAD: Distance %d -> %d, as far forward "
            "as the engine goes, and from here it never gives way in a "
            "collision - not even to a Feature. Only one part at a time is "
            "what the song is about.",
    "colead": "%s YOU marked this a CO-LEAD: Distance %d -> %d. An equal "
              "partner, so it keeps its place in a collision like a Feature "
              "does.",
    "feature": "%s YOU marked this a FEATURE: Distance %d -> %d, a step "
               "forward, and from here it KEEPS its place when something "
               "else wants the same spot. Only one part at a time can be "
               "the thing the listener follows.",
    "support": "%s YOU marked this SUPPORT: Distance %d -> %d, a little "
               "behind the features. It plays with the song without being "
               "the song, and it yields to the parts above it.",
    "double": "%s YOU marked this a DOUBLE: Distance %d -> %d, just behind "
              "the main take. It thickens that part; it is not a second "
              "voice.",
    "harmony": "%s YOU marked this a HARMONY: Distance %d -> %d, behind the "
               "double. Colour around the lead, not content - it yields to "
               "every part above it.",
    "bed": "%s YOU marked this a BED: not the hook, but what the hook "
           "stands on. Distance %d -> %d, and from here it is the channel "
           "that MOVES when two of them want the same spot. A foundation "
           "gets out of the way; a feature does not. Nothing else about "
           "the channel changes - a bed is a position in the room, not a "
           "different sound.",
    "texture": "%s YOU marked this TEXTURE: Distance %d -> %d, the "
               "furthest back and the first to yield. Air and movement, "
               "never the thing you follow.",
}

STAGE_ROLES = (
    ("auto", "Auto",
     "The engine decides, from the depth tier and the rest of the line-up."),
    ("lead", "Lead",
     "The one thing the song is about right now: as far forward as it goes, "
     "and it never gives way - not even to a Feature."),
    ("colead", "Co-lead",
     "An equal partner: a duet, two main vocals, two instruments sharing the "
     "tune. Two or more Co-leads take opposite sides, close to the middle - "
     "neither one is the 'second' voice."),
    ("feature", "Feature",
     "On top: a step closer, and the one that STAYS PUT when two channels "
     "want the same spot. A part the listener is meant to follow."),
    ("support", "Support",
     "Plays with the song without being the song: a chord part, a fill, an "
     "answer. A little behind the features, and yields to them."),
    ("double", "Double",
     "The same part again behind the main take. Drawn halfway in towards the "
     "middle and a little further back, so it thickens the main part instead "
     "of competing with it."),
    ("harmony", "Harmony",
     "A different note under or over the lead - colour, not content. Behind "
     "the double, and it yields to every part above it."),
    ("bed", "Bed",
     "Underneath: further back, and the one that MOVES when two channels "
     "want the same spot. A riff that is a foundation, not a hook."),
    ("texture", "Texture",
     "Air and movement - a shaker, a glittering pluck, a high strum. The "
     "furthest back, and the first to yield."),
)

STAGE_SIDES = (
    ("auto",   "Auto"),
    ("left",   "Left"),
    ("right",  "Right"),
    ("centre", "Centre"),
)

# How far a hand-set role moves a channel, in Distance units.
STAGE_ROLE_DIST = {"lead": -20, "colead": -14, "feature": -14,
                   "support": 6, "double": 8, "harmony": 14,
                   "bed": 16, "texture": 28}
# A role never pushes anything past these: past the back one a source stops
# being in this room and starts being in the next one, and past the front one
# it is inside your head rather than on a stage.
STAGE_ROLE_MAX_DIST = 85
STAGE_ROLE_MIN_DIST = 8
# Who yields in a collision. Lower = stays put. The kit is 0 and never moves.
STAGE_ROLE_PRIO = {"lead": 0.5, "colead": 1, "feature": 1, "support": 2,
                   "double": 2, "harmony": 3, "bed": 3, "texture": 4}
# Co-leads stand this far either side of the middle (percent), and a Double is
# drawn this fraction of the way back in towards the middle.
STAGE_COLEAD_SPAN   = 14.0
STAGE_DOUBLE_PULL   = 0.5
# A channel standing dead centre and told to take a side needs a magnitude to
# take it with. A fraction of its own family's half-width, so a horn does not
# suddenly stand where only a guitar is allowed to stand.
STAGE_SIDE_FRACTION = 0.55
STAGE_SIDE_DEFAULT  = 40.0   # when the family half-width is not known

# LEVEL BALANCE (stage_plan step 4c). The program has no fader values, but it
# has the ROLE, which is the same fact in other words: a Lead or Feature is the
# louder part, a Support/Bed the quieter one. Auto counts as an ordinary part.
# Two parts of one family on opposite sides are only balanced if
# position x weight is equal on both, so the louder one stands nearer the
# middle (a part at 80 % against one at 45 % on mirrored edges leans the
# whole stage towards the louder side).
STAGE_ROLE_WEIGHT = {"lead": 1.00, "colead": 1.00, "feature": 0.85,
                     "auto": 0.70, "support": 0.60, "double": 0.55,
                     "bed": 0.55, "harmony": 0.50, "texture": 0.40}
STAGE_LEVEL_TOLERANCE = 0.90   # a weight ratio above this = equal, no change
STAGE_LEVEL_MIN_RATIO = 0.50   # the louder part never goes closer than half
STAGE_BALANCE = "\u2696"       # marker for the lines the balance pass writes

# stage_manual keys that are not a plain instrument id:
#   "<id>#<k>"  a hand placement for copy k (2..N) of a part you have several of
#               (copy 1 is the plain "<id>", exactly as before);
#   "__room__"  the forced room size, a string, not a placement.
STAGE_ROOM_KEY = "__room__"


def stage_copy_key(iid, k):
    """The stage_manual key of copy k of a part (copy 1 = the plain id)."""
    return iid if int(k) <= 1 else "%s#%d" % (iid, int(k))


def stage_has_copies(iid, n):
    """Does stage_plan lay N of this part out as N copies on one row?
    Not for the kit, the channels Virtual Stage stays off, or a part the x N
    engine calls MONO (a second one of those is a layer, not a place)."""
    if int(n or 1) < 2 or iid in VSTAGE_SKIP or iid in KIT_IDS \
            or iid in KIT_OFF_RISER:
        return False
    return not (multi_rule(iid).get("spread") == "mono"
                and iid not in VSTAGE_LADDERED)


def stage_dist_text(r):
    """Distance for a sentence: '24', or '#1 18 · #2 30 · #3 18' when the
    copies of one part stand at different depths."""
    ds = (r or {}).get("dists")
    if ds:
        return "  \u00b7  ".join("#%d %d" % (k + 1, d) for k, d in enumerate(ds))
    d = (r or {}).get("dist")
    return "%d" % d if d is not None else "-"


def vstage_numbered_label(pcts):
    """'#1 R65 · #2 Centre · #3 L65' - positions in COPY order."""
    return "  \u00b7  ".join("#%d %s" % (k + 1, vstage_pos_label(p))
                           for k, p in enumerate(pcts))


def _stage_weight(iid, overrides=None):
    """How much of the song this part carries (see STAGE_ROLE_WEIGHT)."""
    role = ((overrides or {}).get(iid) or {}).get("role", "auto")
    return STAGE_ROLE_WEIGHT.get(role, STAGE_ROLE_WEIGHT["auto"])


def _stage_known(iid):
    """Is this a real instrument id? A table can be older than the program."""
    return any(x["id"] == iid for x in EQ_DATA)


def stage_manual_ok(iid):
    """Can this channel be hand-placed at all?

    No for the kit - drum_stage_plan lays it out as one object, and one drum
    dragged out of it is a broken kit rather than a placement - and no for
    the channels this plug-in is meant to stay OFF, where a position would
    contradict the reason printed right next to it."""
    return (_stage_known(iid) and iid not in KIT_IDS
            and iid not in KIT_OFF_RISER and iid not in VSTAGE_SKIP)


def stage_overrides_clean(raw):
    """A saved override table, sanitised.

    Anything unknown is dropped in silence: the table comes out of a file,
    and a file can be older than the program that reads it. An entry with
    nothing actually set is not an override and is dropped too, so an empty
    dict really does mean "the engine decides everything here"."""
    roles = {k for k, _l, _d in STAGE_ROLES}
    sides = {k for k, _l in STAGE_SIDES}
    out = {}
    for key, o in (raw or {}).items():
        if key == STAGE_ROOM_KEY:
            if o in VSTAGE_ROOMS:
                out[key] = o
            continue
        if not isinstance(o, dict) or not isinstance(key, str):
            continue
        iid, hashed, k = key.partition("#")
        if not stage_manual_ok(iid):
            continue
        if hashed and not (k.isdigit() and 2 <= int(k) <= MAX_INSTRUMENT_COUNT):
            continue
        role = o.get("role") if o.get("role") in roles else "auto"
        side = o.get("side") if o.get("side") in sides else "auto"
        opp = o.get("opposite") or ""
        if hashed or opp == iid or not stage_manual_ok(opp):
            opp = ""                       # a copy never pairs; see stage_copy_key
        sib = o.get("sibling") or ""
        if hashed or sib == iid or not stage_manual_ok(sib):
            sib = ""                       # siblings are whole channels, too
        if sib:
            opp = ""                       # a sibling pair IS the opposite sides
        if role == "auto" and side == "auto" and not opp and not sib:
            continue
        out[key] = {"role": role, "side": side, "opposite": opp,
                    "sibling": sib}
    return out


def stage_sibling_pairs(ov):
    """The SIBLING pairs in an override table, each pair exactly once.
    Written from one side, meant for both - like "Opposite of"."""
    seen, pairs = set(), []
    for iid, o in (ov or {}).items():
        if not isinstance(o, dict):
            continue
        other = (o or {}).get("sibling") or ""
        if not other:
            continue
        key = tuple(sorted((iid, other)))
        if key in seen:
            continue
        seen.add(key)
        pairs.append(key)
    return pairs


def stage_override_pairs(ov):
    """The counterpole pairs in an override table, each pair exactly once.

    "Opposite of" is written down from one side but it means both, so A->B
    and B->A are the SAME pair - applying it twice would move the same
    channel back where it came from."""
    seen, pairs = set(), []
    for iid, o in (ov or {}).items():
        if not isinstance(o, dict):
            continue                       # the forced-room entry
        other = (o or {}).get("opposite") or ""
        if not other:
            continue
        key = tuple(sorted((iid, other)))
        if key in seen:
            continue
        seen.add(key)
        pairs.append(key)
    return pairs


def stage_manual_summary(ov):
    """One short line per hand placement, for the map and the dialog."""
    out = []
    role_label = {k: lbl for k, lbl, _d in STAGE_ROLES}
    side_label = {k: lbl for k, lbl in STAGE_SIDES}
    for key in sorted(ov or {}):
        if key == STAGE_ROOM_KEY:
            continue
        o = ov[key]
        base, hashed, k = key.partition("#")
        bits = []
        if o.get("role", "auto") != "auto":
            bits.append("Role %s" % role_label.get(o["role"], o["role"]))
        if o.get("side", "auto") != "auto":
            bits.append("Side %s" % side_label.get(o["side"], o["side"]))
        if o.get("opposite"):
            bits.append("Opposite of the %s" % _stage_name(o["opposite"]))
        if o.get("sibling"):
            bits.append("Sibling of the %s" % _stage_name(o["sibling"]))
        if bits:
            out.append("%s  %s%s: %s" % (STAGE_HAND, _stage_name(base),
                                         (" #" + k) if hashed else "",
                                         "  \u00b7  ".join(bits)))
    if (ov or {}).get(STAGE_ROOM_KEY):
        out.append("%s  Room: %s (forced)" % (STAGE_HAND, ov[STAGE_ROOM_KEY]))
    return out


def lowend_row(iid, n=1, stage_row=None):
    """The ONE permanent line for a channel that has a SubMass entry.

    His request: "slå ihop dem till en permanentrad". Returns
    {"text", "extra"} or None - text is the line, extra is the *N sentence
    when there is more than one of this channel.

    Three things it deliberately does NOT say:
      * "this instrument is MONO" - nothing in this sheet sets that.
        Lowtility's width stays at 100 % (untouched) and SubMass's Center
        only centres the generated SUB LAYER. When Center is 100 % it says
        "sub mono", which is the true version of the same claim.
      * one sentence about Virtual Stage over all four channels - three of
        them are in VSTAGE_SKIP and the DOUBLE BASS is not: it gets a real
        position in the `low` family, so it is read off the stage instead.
      * its own *N advice. Every word of that comes from multi_rule(), so
        this line can never drift from what the *N section says two inches
        further down the same card.
    """
    sm = submass_for(iid)
    if not sm:
        return None
    amp, freq_hz, center_pct, note = sm
    n = max(1, int(n or 1))
    bits = []
    # The same line as coloured RUNS - [(text, colour)] - so each part has its own
    # colour: Low cut gold, SubMass blue, its frequency (@ Hz) lime, Center and
    # '(sub mono)' grey, Virtual Stage amber with Position / Distance accented.
    SEP = ("   \u00b7   ", C_FG_DIM)
    runs = []
    lc = lowcut_for(iid)
    if lc:
        bits.append("\U0001f53b Low cut %g Hz \u00b7 %g dB/oct" % (lc[0], lc[1]))
        runs += [(bits[-1], LOWCUT_COLOUR), SEP]
    bits.append("\U0001f311 SubMass %g/12 @ %g Hz, Center %g %%%s"
                % (amp, freq_hz, center_pct,
                   " (sub mono)" if center_pct >= 100 else ""))
    runs += [("\U0001f311 SubMass %g/12" % amp, SUBMASS_COLOUR),
             (" @ %g Hz" % freq_hz, LOWEND_FREQ_COLOUR),
             (", Center %g %%%s" % (center_pct,
                                    " (sub mono)" if center_pct >= 100 else ""),
              C_FG_DIM), SEP]
    if iid in VSTAGE_SKIP:
        bits.append("\U0001f3aa Virtual Stage OFF")
        runs.append((bits[-1], VSTAGE_COLOUR))
    elif stage_row and not stage_row.get("skip"):
        bits.append("\U0001f3aa Virtual Stage %s \u00b7 Distance %s"
                    % (stage_row.get("pos") or "Centre",
                       stage_row.get("dist")))
        runs += [("\U0001f3aa Virtual Stage ", VSTAGE_COLOUR),
                 (str(stage_row.get("pos") or "Centre"), STAGE_POS_COLOUR),
                 (" \u00b7 Distance ", VSTAGE_COLOUR),
                 (str(stage_row.get("dist")), STAGE_DIST_COLOUR)]
    else:
        bits.append("\U0001f3aa Virtual Stage \u2013 see below")
        runs.append((bits[-1], VSTAGE_COLOUR))

    extra = None
    if n > 1:
        if iid in ("bass_root", "bass_loop"):
            extra = ("\u2716%d \u2014 Virtual Stage becomes an OPTION on the "
                     "character layer, and the side, the Distance and the "
                     "\u2018only if\u2019 are in the \U0001f3aa footnote below. It is "
                     "never the plan, and never on the foundation layer." % n)
        else:
            r = multi_rule(iid) or {}
            parts = ["\u2716%d \u2014 %s" % (n, r.get("what") or "")]
            if r.get("trap"):
                parts.append("TRAP: " + r["trap"])
            extra = "  ".join(p for p in parts if p.strip())
    # `note` travels with the row because the row REPLACES the SubMass
    # footnote that used to carry it. Dropping the head line is fine;
    # dropping the explanation would not be.
    return {"text": "   \u00b7   ".join(bits), "runs": runs, "extra": extra, "note": note}


def vstage_multi_option(iid, n, room):
    """Virtual Stage as an OPTION on a doubled bass — or None.

    Returns {"n", "head", "lines", "condition"}:
      lines     = what to dial in (these are SETTINGS, always shown)
      condition = the "only if", which is a WHY and therefore an extra comment.
    Anything that is not a bass, or is not doubled, gets None — the plug-in
    stays off, with no 'maybe' attached to it."""
    n = max(1, int(n or 1))
    if n < 2 or iid not in ("bass_root", "bass_loop"):
        return None
    room = room or "Medium"
    pos = ("Centre" if n < 3 else
           "ladder them ~%d %% apart around centre" % VSTAGE_BASS_OPT_POS)
    # pos_text / pos_line let stage_plan step 5c rewrite JUST the Position
    # field once it knows what else is on the stage. Without them that step
    # would have to guess at this string from the outside, and a guess that
    # misses would leave two layers quietly stacked on one spot again.
    common = [
        "Set the high-pass FIRST, then the plug-in. Virtual Stage on a "
        "still-full-range bass is exactly the mud this rule exists to stop.",
        "Never past Distance %d on anything called a bass, and never more than "
        "~%d %% off centre. Below ~120 Hz there is nothing left to move, so a "
        "wider position only smears the grind and buys no width."
        % (VSTAGE_BASS_MAX_DIST, VSTAGE_BASS_OPT_POS),
        "Cubase pan stays centred and the reverb send stays at zero on that "
        "layer — Virtual Stage is doing both of those jobs already.",
    ]
    if iid == "bass_root":
        return {
            "n": n,
            "head": "✖%d root basses — Virtual Stage becomes an OPTION on the "
                    "high-passed layer" % n,
            "lines": [
                "Layer 1, the foundation (owns below 100 Hz): Virtual Stage "
                "stays OFF. Nothing about that changes.",
                "Layer %s, the character layer (high-passed 100–120 Hz, lives "
                "at 700 Hz–3 kHz): Virtual Stage is allowed here. "
                "Position %s  ·  Lock Position ON  ·  Distance %d  ·  Room %s."
                % (("2" if n == 2 else "2 and up"), pos,
                   VSTAGE_BASS_OPT_DIST, room),
            ] + common,
            "pos_text": pos,
            "pos_line": 1,
            "condition":
                "Only if the two are two PARTS. If they are one bass split "
                "into sub + character, keep both OFF: a room on one half of a "
                "layered sound is a phase difference between two copies of the "
                "same note, and no EQ fixes a phase problem.",
        }
    return {
        "n": n,
        "head": "✖%d bass loops — Virtual Stage becomes an OPTION on the "
                "higher-passed ones" % n,
        "lines": [
            "Loop 1, the lowest one (high-passed ~80 Hz): Virtual Stage OFF.",
            "Loop 2 and up, each high-passed higher than the last "
            "(120 → 160 Hz): Virtual Stage is allowed. "
            "Position %s  ·  Lock Position ON  ·  Distance %d  ·  Room %s."
            % (pos, VSTAGE_BASS_OPT_DIST, room),
        ] + common,
        "pos_text": pos,
        "pos_line": 1,
        "condition":
            "Only if the loops actually play AT THE SAME TIME. If they take "
            "turns by section, they are one instrument in different clothes — "
            "place them identically, or the song changes address at the "
            "chorus.",
    }


def _vstage_skip_row(iid, room, n=1):
    """A 'keep the plug-in off this channel' row, with the ✖N option attached
    when there is one (see vstage_multi_option)."""
    return {
        "id": iid, "kit": False, "pos_pct": 0.0, "pos": "Centre",
        "pos_pcts": None, "dist": None, "room": room, "lock": True,
        "skip": True, "why": VSTAGE_SKIP[iid], "because": [],
        "option": vstage_multi_option(iid, n, room),
    }

# ---------------------------------------------------------------------------
# FAMILIES: who competes with whom for the same piece of stage.
#
# Each member has an ANCHOR from -1 (far left) to +1 (far right) — its natural
# spot inside its own family — and the family has a HALF-WIDTH in percent.
# The actual position is  anchor × half × fill, where FILL depends on how many
# of that family are present:
#
#     one member  → 0.50   a single guitar hard-panned leaves the mix leaning
#     two         → 0.82   a pair is what the edges are FOR
#     three       → 0.93
#     four+       → 1.00   a full section uses the whole stage it has
#
# That one factor is why "Guitar Chords" is a different setting depending on
# whether the rhythm guitar is in the song.
# ---------------------------------------------------------------------------
STAGE_FILL = {1: 0.50, 2: 0.82, 3: 0.93}
STAGE_FILL_MAX = 1.00

# How far apart two rungs of a ladder have to be before they are two positions.
# Positions print rounded to 5 and anything inside ±5 prints as "Centre", so two
# rungs straddling the middle need to be 15 apart before they read as two places
# (±7.5 rounds to ±10; ±6 still rounds into "Centre"). Below this a ladder hands
# out the same instruction twice, and 'Centre · Centre' is not two places for
# two singers to stand.
STAGE_RUNG_MIN = 15.0

# TWO of one part (2 x Rhythm Guitar) is a pair on opposite sides. When the
# family has exactly ONE other part (the Guitar Chords), that lone part takes
# the middle and the pair stands at this fraction of the family's half-width
# (guitars: 78 x 0.65 = L/R 50). Not for vocals, where the middle is the lead's.
STAGE_PAIR_WITH_LONE = 0.65
STAGE_PAIR_NO_LONE = {"vocals", "handperc"}

STAGE_FAMILIES = [
    {"key": "vocals", "name": "Vocals", "half": 62, "one": "vocal", "members": [
        ("vocals_lead",       0.00),
        ("vocals_backing",    1.00),
        ("vocals_choir_pad",  0.00),
        ("vocals_extra",     -0.70),
    ]},
    {"key": "guitars", "name": "Guitars", "half": 78, "one": "guitar", "members": [
        ("guitar_rhythm",    -1.00),
        ("guitar_acoustic",  -0.62),
        ("guitar_lead",      -0.16),
        ("guitar_single_low", 0.45),
        ("guitar_chords",     1.00),
    ]},
    {"key": "keys", "name": "Keys & organ", "half": 58, "one": "keyboard", "members": [
        ("accordion",        -1.00),
        ("piano_bg",         -0.72),
        ("accordion_lead",   -0.40),
        ("organ_lead",        0.34),
        ("organ_melody",      0.52),
        ("piano_riff",        0.62),
        ("organ",             0.90),
    ]},
    {"key": "horns", "name": "Horns", "half": 55, "one": "horn", "members": [
        ("trombone",         -1.00),
        ("bass_trombone",    -0.94),
        ("double_bass_trombone",    -0.98),
        ("tenor_trombone",    -0.90),
        ("tenor_bass_trombone",    -0.92),
        ("alto_trombone",    -0.86),
        ("tuba",             -0.80),
        ("euphonium",        -0.66),
        ("brass",            -0.55),
        ("french_horn",      -0.40),
        ("baritone_sax",     -0.34),
        ("tenor_sax",        -0.28),
        ("saxophone",        -0.22),
        ("alto_sax",         -0.16),
        ("soprano_sax",      -0.10),
        ("brass_lead",        0.18),
        ("horn_section",      1.00),
        ("flugelhorn",        0.62),
        ("piccolo_trumpet",   0.80),
        ("trumpet",           0.92),
    ]},
    {"key": "winds", "name": "Winds & harp", "half": 48, "one": "wind instrument", "members": [
        ("contrabassoon",    -0.95),
        ("flute_bg",         -0.85),
        ("contrabass_clarinet", -0.74),
        ("bassoon",          -0.62),
        ("woodwind",         -0.38),
        ("english_horn",     -0.24),
        ("oboe",             -0.10),
        ("clarinet",          0.22),
        ("bass_clarinet",     0.38),
        ("bass_flute",        0.43),
        ("alto_flute",        0.48),
        ("flute",             0.55),
        ("piccolo",           0.70),
        ("harmonica",         0.85),
    ]},
    {"key": "strings", "name": "Strings", "half": 80, "one": "string part", "members": [
        ("violin_bg",        -0.90),
        ("violin",           -0.58),
        ("cello",            -0.26),
        ("strings_lead",      0.10),
        ("viola",             0.42),
        ("viola_front",      -0.08),
        ("string_section",    1.00),
    ]},
    {"key": "synths", "name": "Synths", "half": 70, "one": "synth", "members": [
        ("synth_mallet",     -0.85),
        ("synth_pad",         0.00),
        ("synth_pluck",       0.85),
    ]},
    {"key": "low", "name": "Low end", "half": 22, "one": "low instrument", "members": [
        ("double_bass",      -0.55),
        ("double_bass_section", 0.55),
    ]},
    # A hand-drum player is not part of the kit and does not stand on the
    # riser. One member, so the engine's own "a lone family flips to whichever
    # side is empty" rule decides which side of the drummer they end up on.
    {"key": "handperc", "name": "Hand drums", "half": 68, "one": "hand-drum set", "members": [
        ("hand_drums",        0.85),
    ]},
]

# Members whose position is a WIDTH, not a point: an ensemble in one channel is
# a ROW of players, so it is printed as a ladder across its own span.
VSTAGE_LADDERED = {"vocals_backing", "vocals_extra", "horn_section",
                   "string_section"}

# A part that stands one row BEHIND another when both are in the song:
# {id: (the row in front, how many Distance units behind it)}. Two rows of
# singers on one line are one row (his report, 2026-10-14: backing vocals and
# extra vocals both at Distance 72).
STAGE_BEHIND = {"vocals_extra": ("vocals_backing", 10)}
STAGE_BEHIND_MAX = 90
# NOTE: "strings_lead" is deliberately NOT in that set. It is the same section
# of players, so it still WEIGHS two places (VSTAGE_UNIT_WEIGHT below) — but a
# unison tune arrives as one voice, and drawing it as a row of chairs is the
# same mistake as giving it the bed's 8–14 kHz silk.

# Channels that keep Lock Position ON — anything whose left/right must not move
# when you change its depth.
VSTAGE_LOCK = {"vocals_lead", "vocals_choir_pad", "snare", "kick",
               "double_bass", "double_bass_section", "synth_pad"}

# Per-channel "why this spot", before anything else in the song moves it.
VSTAGE_WHY = {
    "hand_drums":       "Out beside the kit, not on it: a second player standing "
                        "where there is room. Keep them off the snare's side, or "
                        "two skin drums arrive at the same spot.",
    "vocals_lead":      "Dead centre and the closest thing in the mix. If the "
                        "words start to blur, take Distance DOWN — never fix a "
                        "vocal by shrinking the room.",
    "vocals_backing":   "A row of singers, not one singer: ladder them either "
                        "side of the lead. The gap between them and the lead is "
                        "what makes the lead sound close.",
    "vocals_choir_pad": "A bed, not a position — centred, far back, and left at "
                        "the width it already has.",
    "vocals_extra":     "Colour, not words: on the OPPOSITE side from the "
                        "backing vocals and as far back, so a sung vowel does "
                        "not stand where a sung word stands.",
    "double_bass":      "Just off centre and CLOSE. An upright can take a "
                        "little room, but past Distance ~35 the low end goes "
                        "woolly.",
    "guitar_rhythm":    "Rhythm guitar is a stage-edge instrument — its whole "
                        "job is to be somewhere the vocal is not.",
    "guitar_chords":    "The opposite edge from the rhythm guitar, at the SAME "
                        "Distance, or the pair sounds like one player standing "
                        "in a doorway.",
    "guitar_lead":      "Nearly centre and a step closer than the other "
                        "guitars — a solo has to walk forward.",
    "guitar_single_low":"Off centre, clear of the lead guitar's line.",
    "guitar_acoustic":  "Off to one side, opposite the electrics. It is full of "
                        "its own body already; keep the Distance modest or the "
                        "strum turns to mush.",
    "organ":            "An organ is a big instrument in a fixed place, not a "
                        "wide stereo bed. Give it one side and leave it there.",
    "accordion_lead":   "In from the padding accordion's spot toward the "
                        "centre. Same player, same side — a melody simply "
                        "stands further forward than a chord wash.",
    "flute_bg":         "Well out to one side and a long way back. A held "
                        "flute is scenery; the solo Flute stands nearer the "
                        "middle, and the gap between the two is the point.",
    "violin_bg":        "The far side and the back of the stage — it is a "
                        "bed, and depth is the thing a bed is allowed and a "
                        "melody is not.",
    "brass_lead":       "In from the horn row toward the centre: the section "
                        "is still standing together, but the line that carries "
                        "the tune steps forward out of it.",
    "strings_lead":     "Nearly centre, and much closer than the String "
                        "Section bed. Depth is what a bed is FOR, and it is "
                        "the one thing a melody cannot have. It is also the "
                        "one section NOT drawn as a row: a unison tune "
                        "arrives as one voice, not as eight chairs.",
    "organ_lead":       "The same player as the Organ (background), one step in "
                        "toward the centre: a melody walks forward, the pad "
                        "stays where the building put it. Keep the two on the "
                        "SAME side — it is one instrument, not two.",
    "organ_melody":     "Between the Organ (background) and the Organ (lead): a "
                        "half step in from the pad, a half step out from the "
                        "tune. It is one of several lines, so it should not "
                        "stand where the vocal stands. Same side as the other "
                        "organ - one player. (Equal in importance to the "
                        "vocal? Set its Role to Co-lead or Feature.)",
    "accordion":        "Opposite the organ and the piano, so the reed-and-pipe "
                        "sounds are not standing on each other.",
    "piano_bg":         "A step back — it is bedding, not a hook.",
    "piano_riff":       "Closer than the background piano: a riff is a lead "
                        "line, so it stands nearer.",
    "flute":            "Off centre, in front of the pads.",
    "brass":            "A section standing together, slightly off centre.",
    "trumpet":          "Out on one side, clear of the vocal, and not too far "
                        "back — stabs have to stay punchy.",
    "trombone":         "The far side from the trumpet, at the SAME Distance, "
                        "so the two read as one horn line.",
    "tenor_trombone":         "The far side from the trumpet, at the SAME Distance, "
                        "so the two read as one horn line.",
    "tenor_bass_trombone":         "The far side from the trumpet, at the SAME Distance, "
                        "so the two read as one horn line.",
    "saxophone":        "The middle of the horn row, a shade off centre.",
    "horn_section":     "A section is a ROW: ladder it across the stage at ONE "
                        "shared Distance. That shared distance is what makes "
                        "three horns sound like a section instead of three "
                        "overdubs.",
    "harmonica":        "Off centre, close enough to answer the vocal.",
    "woodwind":         "Slightly off centre, behind the leads.",
    "clarinet":         "Centre-right of the wind row, behind the oboe's side - "
                        "inside the flute, in front of the bassoons.",
    "oboe":             "Centre-left of the wind row: the oboe is the one wind "
                        "that stands clear of the others, so give it a clear spot.",
    "bassoon":          "Right of centre at the back, as in an orchestra - "
                        "behind the clarinets, with the low end still centred.",
    "contrabassoon":    "Far back and low in the row, next to the bassoon. "
                        "Keep the low end centred.",
    "flugelhorn":       "Beside the trumpet at the SAME Distance, so the two "
                        "read as one horn line - nearer centre, a shade back.",
    "french_horn":      "Back of the row and slightly off centre: its bell "
                        "points backwards, so it always sounds a little distant.",
    "tuba":             "The far end of the horn row, close to centre and "
                        "CLOSE in Distance - a tuba is a bass line.",
    "english_horn":     "Next to the oboe, a step to the left and a step back - "
                        "a quieter voice must not stand behind a louder one.",
    "euphonium":        "The low end of the horn row beside the tuba, close to "
                        "centre - a tenor brass line, not a point on the side.",
    "bass_clarinet":    "Right of the clarinets, a step back, with the low end "
                        "still centred.",
    "contrabass_clarinet": "Far back and low in the row, beside the contrabassoon. "
                        "Keep the low end centred.",
    "double_bass_section": "Just off centre on the opposite side from the solo "
                        "bass, and CLOSE. A section can take a little room, but "
                        "past Distance ~35 the low end goes woolly.",
    "piccolo":          "Off centre at the right of the wind row, further back "
                        "than it wants to be: a piccolo is the loudest thing in "
                        "the top octave and wins every collision.",
    "alto_flute":       "Beside the flute, a step to the centre and a step "
                        "back - it is a quieter voice.",
    "bass_flute":       "Next to the bass clarinet, close enough to be heard: "
                        "it is the quietest flute and gets buried first.",
    "soprano_sax":      "The inner end of the sax row, a shade off centre.",
    "alto_sax":         "The middle of the sax row, a shade off centre.",
    "tenor_sax":        "The outer end of the sax row, with the low end centred.",
    "baritone_sax":     "The far end of the sax row, close to centre: a "
                        "baritone is a bass-register voice.",
    "piccolo_trumpet":  "Beside the trumpet at the SAME Distance, so the two "
                        "read as one horn line.",
    "alto_trombone":    "Beside the trombone at the SAME Distance - the "
                        "bright end of the bone row.",
    "bass_trombone":    "The far end of the horn row, close to centre and "
                        "CLOSE in Distance: a bass trombone is a bass line.",
    "double_bass_trombone":    "The far end of the horn row, close to centre and "
                        "CLOSE in Distance: a double-bass trombone is a bass line.",
    "synth_pad":        "Centred and far back — a pad is the back wall of the "
                        "mix. Do not narrow it.",
    "synth_pluck":      "Out to one side. If it ping-pongs, place it and let "
                        "the delay do the travelling.",
    "synth_mallet":     "The opposite side from the plucks.",
    "violin":           "Left of the string layout, as an orchestra looks from "
                        "the audience.",
    "viola":            "Inside the violins, at the SAME distance as the violin: the two are partners, not front and back.",
    "viola_front":      "Nearly centre and close, like a solo violin: the tune must stand in "
                        "FRONT of the string desk, not inside it.",
    "cello":            "Nearer centre and nearer the front than the violas.",
    "string_section":   "A whole section: ladder it right across the stage at "
                        "ONE Distance, wide and back.",
}

# Which instrument yields when two of them want the same spot. FRONT channels
# (the ones that win masking) keep their place; BACK channels move. Drums never
# move — the kit is laid out as one object and stays that way.
_STAGE_PRIO = {"front": 1, "mid": 2, "back": 3}

# How close two sources may stand before it stops being two sources.
STAGE_MIN_GAP = 14

# Sections that must end up sharing ONE Distance. A row of players standing at
# different depths stops sounding like a section and starts sounding like a
# stack of separate overdubs — and a doubled guitar pair at two depths is the
# classic "one guitar in a doorway" mix.
STAGE_SAME_DIST = [
    ("guitar pair",  ("guitar_rhythm", "guitar_chords")),
    ("horn line",    ("trombone", "saxophone", "trumpet", "brass", "flugelhorn",
                      "french_horn", "tuba", "euphonium", "soprano_sax", "alto_sax",
                      "tenor_sax", "baritone_sax", "piccolo_trumpet", "alto_trombone",
                      "bass_trombone", "tenor_trombone", "tenor_bass_trombone", "double_bass_trombone")),
    ("string desks", ("violin", "viola", "cello")),
]


def vstage_pos_label(pct):
    """-100…+100 → 'L45' / 'Centre' / 'R30'.

    Rounded to 5, because Virtual Stage is a drag control and 2 % is not a
    position anybody can hear."""
    try:
        p = float(pct)
    except (TypeError, ValueError):
        return "Centre"
    p = max(-100.0, min(100.0, p))
    p = int(round(p / 5.0) * 5)
    if abs(p) <= 5:
        return "Centre"
    return ("L" if p < 0 else "R") + str(abs(p))


def vstage_ladder(lo, hi, n):
    """N evenly spaced positions from lo to hi (percent). n == 1 lands in the
    middle of the span."""
    n = max(1, int(n))
    if n == 1:
        return [(lo + hi) / 2.0]
    return [lo + (hi - lo) * i / (n - 1) for i in range(n)]


def vstage_snap_ladder(pcts):
    """A ladder of positions snapped to the 5-step Virtual Stage grid so that
    NO TWO RUNGS LAND ON THE SAME PRINTED SPOT (order of the list is kept).

    Why: 8 toms squeezed inside the hi-hat gave 'L15 . Centre . Centre . R10' -
    two toms on one spot is not a ladder. Rules (Lars, 2026-11-16: 'L5 R5 is
    better: 55, 45, 35, 25, 15, 5, R5, R15'):
      * every rung is rounded to 5; a rung that would land on or below its
        neighbour is pushed one step (5) further out;
      * in a ladder 5 is a real position (L5 / R5), not 'Centre': only a rung
        that rounds to 0 is Centre;
      * when 0 and +-5 are both taken, the 0 rung steps to the free side of
        the middle (L5 / R5), so the middle of the row reads ... L5 R5 ...
    Returns the new list of numbers (multiples of 5)."""
    vals = [max(-100.0, min(100.0, float(p))) for p in pcts]
    if len(vals) < 2:
        return [int(round(v / 5.0) * 5) for v in vals]
    order = sorted(range(len(vals)), key=lambda k: vals[k])
    snapped = {}
    prev = None
    for k in order:
        r = int(round(vals[k] / 5.0) * 5)
        if prev is not None and r < prev + 5:
            r = prev + 5
        snapped[k] = r
        prev = r
    taken = set(snapped.values())
    if 0 in taken and (5 in taken or -5 in taken) and not (5 in taken and -5 in taken):
        zero = [k for k in snapped if snapped[k] == 0][0]
        snapped[zero] = -5 if 5 in taken else 5
    return [snapped[k] for k in range(len(vals))]


def vstage_snap_label(p):
    """One snapped ladder rung printed: 0 -> 'Centre', -15 -> 'L15', 5 -> 'R5'."""
    p = int(p)
    return "Centre" if p == 0 else ("L" if p < 0 else "R") + str(abs(p))


def vstage_ladder_label(pcts):
    """A list of positions, printed: 'L60 · Centre · R60'. Rungs never share a
    printed spot and +-5 is shown as L5 / R5 (see vstage_snap_ladder)."""
    return "  ·  ".join(vstage_snap_label(p) for p in vstage_snap_ladder(pcts))


# ---- HOW BIG IS THIS SONG? -------------------------------------------------
# In PLACES ON THE STAGE, not in channels, and the difference is the drum kit.
# His question, and it is the right one: "should a drum kit not have the same
# place in the room whether it has 1 tom or 4, 0 cymbals or 7, 1 kick or 2?"
# It should. One drummer, one riser, however many microphones are pointed at
# it. Counting channels made a well-miked kit look like five performers spread
# across the stage, and pushed every song with a real kit toward a bigger room
# than it needed.
#
# So the count is his own model — the drums' world, the instruments' world and
# the vocals' world:
#
#   the whole kit                      1 place   (kick, snare, hats, ride,
#                                                  toms, cymbals AND the
#                                                  shaker/tambourine extras,
#                                                  which are played from behind
#                                                  the same kit)
#   hand drums                         its own    (congas, bongos, taiko: a
#                                                  second player who has to
#                                                  stand somewhere)
#   every other instrument             1 place each, and x2 really is 2 —
#                                                  two chord guitars are two
#                                                  guitarists standing apart
#   a section or a bed                 2 places   (string section, horn
#                                                  section, choir pad, long
#                                                  synth pad: one channel, but
#                                                  it is not one person and it
#                                                  does not stand in one spot)
#
# The section weight is also what replaced the old special case — "a pad plus
# cymbals plus eleven channels is Large" — with something that says the same
# thing without naming a number: a bed fills the room because a bed IS wide.
DRUM_UNIT_IDS = frozenset(KIT_IDS) | {"percussion"}
# v3.29: the channels that carry the kit's AIR. A hihat or a ride is a cymbal too, so the
# 'no overheads' step-down only fires when none of them is there.
KIT_AIR_IDS = frozenset({"cymbals", "hihat", "ride"})

# One channel, more than one place. Nothing else is weighted.
VSTAGE_UNIT_WEIGHT = {
    "string_section":   2,
    "strings_lead":     2,      # still the whole section, just playing the tune
    "horn_section":     2,
    "vocals_choir_pad": 2,
    "synth_pad":        2,
}

# Where the room changes size, in places. His scale, and it reads as the four
# rooms he actually records in: 1-5 a singer with a guitar, 6-10 a rock band,
# 11+ a big or over-produced arrangement.
VSTAGE_UNITS_SMALL = 5      # up to and including this = Small
VSTAGE_UNITS_MEDIUM = 10    # up to and including this = Medium, above = Large


# A vocal stack is ONE group standing together, not a person per take: however
# many tracks of these there are, they weigh one place in the room count.
# (His call, 2026-10-13. The x N LADDER on the stage is unchanged.)
VSTAGE_COUNT_ONCE = frozenset({"vocals_backing", "vocals_extra"})


def stage_units(selected_ids, counts=None):
    """How many PLACES this line-up needs on the stage. See the note above."""
    sel = set(selected_ids or ())
    counts = counts or {}
    cnt = lambda i: max(1, int(counts.get(i, 1) or 1))
    units = 0
    if sel & DRUM_UNIT_IDS:
        units += 1                       # the kit, whatever is in it
    for iid in sel - DRUM_UNIT_IDS:
        units += VSTAGE_UNIT_WEIGHT.get(iid, 1) * (
            1 if iid in VSTAGE_COUNT_ONCE else cnt(iid))
    return units


def vstage_room(selected_ids, counts=None, force=None):
    """ONE room for the whole song, and the sentence that justifies it.

    Room size is a property of the BUILDING, not of the channel: every Virtual
    Stage instance in the song gets this same value. Big arrangements need a
    room big enough to hold them; a four-place demo in a Large room just sounds
    far away. And with no overheads in the kit there is nothing carrying
    natural air, so the room comes down a size — otherwise every close mic
    invents its own wash and they do not agree with each other."""
    sel = set(selected_ids or ())
    n = stage_units(sel, counts)

    if n <= VSTAGE_UNITS_SMALL:
        room, why = "Small", ("%d places on the stage — a small line-up in a "
                              "big room just sounds far away, and this keeps it "
                              "close and defined." % n)
    elif n > VSTAGE_UNITS_MEDIUM:
        room, why = "Large", ("%d places on the stage, and an arrangement that "
                              "big needs a room big enough to hold it — "
                              "anything smaller piles everything against the "
                              "same wall." % n)
    else:
        room, why = "Medium", ("%d places on the stage — the room that fits a "
                               "band: enough space to hear depth, not so much "
                               "that the close things stop sounding close." % n)
    if sel & DRUM_UNIT_IDS:
        why += " (The whole kit counts as one place, however many pieces it has.)"

    if (sel & set(KIT_IDS)) and not (sel & KIT_AIR_IDS) and room != "Small":
        was = room
        room = VSTAGE_ROOMS[VSTAGE_ROOMS.index(room) - 1]
        why += (" Stepped DOWN from %s because the kit has no cymbal channel at all (no "
                "cymbals, hihat or ride) carrying its air: every close mic has to "
                "make its own room, and those rooms disagree with each other "
                "the moment you make them big." % was)
    if force in VSTAGE_ROOMS:
        # His call (2026-10-13): a 10-place band can feel closer than Large
        # says. A forced room is FINAL - no step-down for missing overheads.
        if force == room:
            why = ("%s YOU set the room to %s by hand - the same as the count "
                   "says. %s" % (STAGE_HAND, force, why))
        else:
            why = ("%s YOU set the room to %s by hand. Counting %d places on "
                   "the stage the sheet alone would have said %s; a forced "
                   "room is final, so that is not stepped up, down or "
                   "second-guessed." % (STAGE_HAND, force, n, room))
        room = force
    return room, why


# ---------------------------------------------------------------------------
# THE DRUM KIT
# ---------------------------------------------------------------------------
HIHAT_COPY_STEP = 4     # v3.38: Distance points between the copies of a hi-hat (closed -> open)


def drum_stage_plan(selected_ids, counts=None, perspective="audience",
                    mid=VSTAGE_MID, room=None):
    """Virtual Stage placement for the drum kit, adapted to WHICH pieces are
    present in this song.

    selected_ids : the ticked instrument ids ("what is in this song")
    counts       : optional {iid: number of channels} — a three-tom kit is laid
                   out differently from a one-tom kit
    perspective  : "audience" = you are looking AT the drummer, so the hi-hat is
                   on the RIGHT and the ride/floor tom on the LEFT.
                   "drummer"  = mirrored, as the drummer sits.

    Returns (rows, info). rows are ordered left → right; info["notes"] is the
    list of decisions that were made BECAUSE of what is (and is not) in the
    kit — the part that is actually worth reading."""
    sel = set(selected_ids or ())
    counts = counts or {}
    has = lambda i: i in sel
    cnt = lambda i: max(1, int(counts.get(i, 1) or 1))

    kit  = [i for i in KIT_IDS if has(i)]
    perc = [i for i in KIT_OFF_RISER if has(i)]
    if not kit and not perc:
        return [], {"room": room, "edge": 0, "window": 0, "lo": None, "hi": None,
                    "kit": [], "perc": [], "notes": [], "perspective": perspective}

    if room is None:
        room = vstage_room(sel, counts)[0]

    n_kit = len(kit)
    metal = [i for i in ("hihat", "ride") if has(i)]
    notes = []

    # ---- 1. How wide is this kit allowed to be? -----------------------------
    # The outer edge is set by the WIDEST thing actually present. Take the
    # overheads away and the kit does not keep its old footprint with a gap in
    # it — the whole thing gets narrower.
    if has("cymbals"):
        edge = 65
    elif has("toms"):
        edge = 50
    elif metal:
        edge = 38
    else:
        edge = 0

    # ---- 2. How far out does the timekeeper sit? ----------------------------
    # With toms on the flanks the hats/ride stay in at ~0.42 of the edge. With
    # NO toms those flanks are empty, so they move out and cover the ground the
    # toms would have covered — otherwise the kit is cymbals at the rim with a
    # hole in the middle.
    metal_f = 0.42 if has("toms") else 0.58
    if metal:
        # A lone timekeeper is the only mid-width element there is. Parked out
        # wide it just makes the kit sound like it is leaning over.
        # v3.23: this also holds when hi-hat AND ride are both ticked. They take
        # turns (hi-hat through the song, ride in the loud ending), so at any
        # moment ONE of them is the only timekeeper. The old code treated two
        # ticked metals as two players at once and pushed both out wide (the
        # hi-hat went R20 -> R25 with a ride, R25 -> R40 with no toms).
        metal_f *= 0.72

    # ---- 3. The Distance window --------------------------------------------
    if has("toms") and has("cymbals"):
        win = 8
    elif n_kit >= 3:
        win = 6
    else:
        win = 3
    kd = mid
    if n_kit and not has("cymbals"):
        kd = mid - 6

    side = 1.0 if perspective != "drummer" else -1.0   # +1 → hi-hat on the RIGHT
    rows = []

    def add(iid, pos_pct, pos_txt, dist, why, lock=False, skip=False, pcts=None, dists=None):
        # A laddered channel is a RANGE, so it is remembered as one: the map
        # draws it from end to end, and a later nudge moves the whole ladder
        # instead of silently keeping the old rungs.
        # v3.38: `dists` = one Distance per copy (the hi-hat copies: same spot, a little deeper each).
        if pcts:
            pos_pct = sum(pcts) / float(len(pcts))
        row = {
            "id": iid, "kit": True,
            "pos_pct": float(pos_pct),
            "pos_pcts": (list(pcts) if pcts else None),
            "pos": pos_txt if pos_txt is not None else vstage_pos_label(pos_pct),
            "dist": int(max(0, min(100, round(dist)))),
            "room": room, "lock": bool(lock), "skip": bool(skip),
            "why": why, "because": [],
        }
        if dists:
            row["dists"] = [int(max(0, min(100, round(d)))) for d in dists]
        rows.append(row)

    # ---- KICK ---------------------------------------------------------------
    if has("kick"):
        add("kick", 0, "Centre", max(0, kd - win), VSTAGE_SKIP["kick"],
            lock=True, skip=True)

    # ---- SNARE --------------------------------------------------------------
    if has("snare"):
        add("snare", 0, "Centre", kd - 0.6 * win,
            "Dead centre, and the closest thing on the stage after the kick — "
            "the snare is where the listener decides the drummer is sitting. "
            "Lock Position ON: nudge it back or forward, never sideways.",
            lock=True)

    # ---- HI-HAT / RIDE ------------------------------------------------------
    if side > 0:
        hh_why = ("The hi-hat is at the drummer's left hand, which is your "
                  "RIGHT from out front.")
        rd_why = ("The ride is at the drummer's right hand — the opposite side "
                  "from the hi-hat, which is where it really stands in the kit. "
                  "It is not there to keep them apart: the two seldom play "
                  "together.")
    else:
        hh_why = "Drummer's perspective: the hi-hat is at their left hand."
        rd_why = "Drummer's perspective: the ride is at their right hand."
    hh_because, rd_because = [], []
    if not has("toms"):
        e = ("No toms in the song, so it moved OUT to ~%d %% to cover the flank "
             "the toms would have owned." % round(metal_f * edge))
        hh_because.append(e)
        rd_because.append(e)
    else:
        e = ("Toms are in the song and they own the flanks, so it sits IN at "
             "~%d %% to clear them." % round(metal_f * edge))
        hh_because.append(e)
        rd_because.append(e)
    if len(metal) == 1:
        e = ("It is the only metal timekeeper here, so it is pulled back toward "
             "centre — a lone hat parked out wide makes the whole kit lean.")
        hh_because.append(e)
        rd_because.append(e)
    else:
        e = ("Hi-hat and ride usually TAKE TURNS (hi-hat through the song, ride "
             "in the loud ending), so each is placed as if it were the only "
             "timekeeper: pulled in toward centre, on its own side of the kit. "
             "Having both ticked does not push either of them out wider.")
        hh_because.append(e)
        rd_because.append(e)
    if has("hihat"):
        nh = cnt("hihat")
        hh_pos = side * metal_f * edge
        hh_d = kd + 0.25 * win
        if nh >= 2:
            # v3.38: SEVERAL hi-hat channels (typically a closed and an open hat). It is still ONE hi-hat, so
            # every copy keeps the SAME position - but the copies are a little apart in depth: #1 (the closed
            # hat, tight) at the base Distance, each next copy HIHAT_COPY_STEP points deeper (the open hat
            # throws a wash into the room). Without this the open and the closed hat were one point.
            ds = [hh_d + HIHAT_COPY_STEP * k for k in range(nh)]
            add("hihat", hh_pos, None, ds[0], hh_why, pcts=[hh_pos] * nh, dists=ds)
            hh_because.append(
                "✖%d hi-hat channels (closed + open?): same position, because it is ONE hi-hat, but "
                "each copy %d Distance points deeper than the one before - #1 is the closed hat at %d, "
                "#2 the open hat at %d." % (nh, HIHAT_COPY_STEP, rows[-1]["dists"][0], rows[-1]["dists"][1]))
        else:
            add("hihat", hh_pos, None, hh_d, hh_why)
        rows[-1]["because"] = hh_because
    if has("ride"):
        add("ride", -side * metal_f * edge, None, kd + 0.25 * win, rd_why)
        rows[-1]["because"] = rd_because

    # ---- TOMS ---------------------------------------------------------------
    if has("toms"):
        nt = cnt("toms")
        # Floor tom is at the drummer's right = your left; the rack toms sweep
        # across toward the hi-hat side. Keep the top of the sweep INSIDE the
        # hi-hat: a rack tom panned past the hats is a tom in the audience.
        right_cap = (metal_f * edge - 0.10 * edge) if has("hihat") else 0.78 * edge
        left_end  = -0.86 * edge
        right_end = min(0.78 * edge, right_cap)
        pcts = [left_end * 0.55] if nt == 1 else vstage_ladder(left_end, right_end, nt)
        pcts = [side * p for p in pcts]
        if nt == 1:
            why = ("One tom channel, so it is the floor tom: out on the "
                   "floor-tom side, not centred. A single centred tom sounds "
                   "like a sample, not like part of a kit.")
        else:
            why = ("Toms are one instrument in several channels: floor tom on "
                   "the outside, rack toms sweeping in toward the hi-hat. They "
                   "own the flanks — everything else on the kit was pulled in "
                   "to clear them.")
        add("toms", 0, vstage_ladder_label(pcts), kd, why,
            pcts=(pcts if nt > 1 else None))
        if has("hihat"):
            rows[-1]["because"].append(
                "The top of the sweep stops at ~%s because the hi-hat is there; "
                "a rack tom panned past the hats is a tom in the audience."
                % vstage_pos_label(side * right_end))
        if nt > 3:
            rows[-1]["because"].append(
                "✖%d toms, so the ladder is tight — that is right: real rack "
                "toms are 20 cm apart, not 2 metres." % nt)

    # ---- CYMBALS / OVERHEADS ------------------------------------------------
    if has("cymbals"):
        nc = cnt("cymbals")
        cym_pcts = None
        if nc <= 1:
            pos_txt, pct = "Centre — leave it", 0.0
            why = ("Overheads are a stereo PAIR, not a point. Placing a stereo "
                   "pair at a spot collapses the width you recorded it for: "
                   "leave Position centred and use Distance only. They are the "
                   "furthest-back thing on the kit and the only channel "
                   "carrying its air — which is exactly why everything else on "
                   "the kit gets to stay close.")
        else:
            cym_pcts = [side * p for p in vstage_ladder(-edge, edge, nc)]
            pos_txt, pct = vstage_ladder_label(cym_pcts), cym_pcts[0]
            why = ("✖%d separate cymbal channels, so they get to be points: "
                   "ladder them across the outer edge at ONE shared Distance. "
                   "Same distance = same kit. Different distances = cymbals "
                   "from three different rooms." % nc)
        add("cymbals", pct, pos_txt, kd + win, why, pcts=cym_pcts)

    # ---- PERCUSSION (off the riser) -----------------------------------------
    if perc:
        base = edge if edge else 45
        p = (-side if has("hihat") else side) * 0.9 * base
        np_ = cnt("percussion")
        perc_pcts = None
        if np_ > 1:
            perc_pcts = vstage_ladder(p, -p * 0.35, np_)
            pos_txt, p = vstage_ladder_label(perc_pcts), perc_pcts[0]
        else:
            pos_txt = None
        add("percussion", p, pos_txt, kd + win + 6,
            "Percussion is not on the drum riser — it is another player "
            "standing beside it. Put it OUTSIDE the kit's edge, opposite the "
            "hi-hat, and a few Distance points further back. That is what makes "
            "a shaker read as a second musician instead of a seventh drum.",
            pcts=perc_pcts)
        if has("hihat"):
            rows[-1]["because"].append(
                "Placed opposite the hi-hat, because both live in the same "
                "5–12 kHz air and side by side they would mask each other.")

    rows.sort(key=lambda r: r["pos_pct"])
    # The WINDOW is the kit's own depth. Percussion is not on the riser, so it
    # is deliberately outside the window and must not stretch it.
    dists = [d for r in rows if r["id"] in KIT_IDS
             for d in (r.get("dists") or [r["dist"]])] or [int(kd)]
    info = {
        "room": room, "edge": edge, "window": win,
        "lo": min(dists), "hi": max(dists),
        "kit": kit, "perc": perc, "notes": notes,
        "perspective": "audience" if side > 0 else "drummer",
    }

    # ---- The adaptation notes: what changed, and because of WHAT ------------
    if n_kit >= 2 or perc:
        notes.append(
            "Same Room on every piece: %s. Different room sizes across one kit "
            "is the mistake this plug-in makes easy — the kit stops being one "
            "instrument in one place and turns into a pile of samples." % room)
        notes.append(
            "The whole kit lives between Distance %d and %d. That %d-point "
            "window IS the rule: a kit is one object about a metre deep, so "
            "spreading it over 30 Distance points does not make it deeper, it "
            "makes the snare and the hats sound like different recordings."
            % (min(dists), max(dists), max(dists) - min(dists)))

    if n_kit and not has("toms") and metal:
        extra = ("" if has("cymbals") else
                 " With no overheads either, the kit's outer edge drops to "
                 "%d %% — it does not keep a seven-piece footprint with holes "
                 "in it." % edge)
        notes.append(
            "NO TOMS. The flanks the toms would have owned are empty, so the "
            "hi-hat/ride moved OUT to ~%d %% to cover them.%s Do not also widen "
            "the overheads to fill the gap — a four-piece kit spread like a "
            "seven-piece one sounds like two kits in two rooms."
            % (round(metal_f * edge), extra))
    elif has("toms"):
        notes.append(
            "TOMS PRESENT (✖%d). They own the flanks, so the hi-hat/ride sit IN "
            "at ~%d %% instead of out at the edge. Untick the toms and this "
            "whole map re-spreads." % (cnt("toms"), round(metal_f * edge)))

    if n_kit and not has("cymbals"):
        notes.append(
            "NO OVERHEADS/CYMBALS. Nothing is carrying the kit's air or its "
            "natural room, so the whole kit moved FORWARD (Distance ~%d instead "
            "of ~%d) and the room came down a size. With no overheads every "
            "close mic has to invent its own room, and those rooms disagree "
            "with each other the moment you make them big." % (kd, mid))
    elif has("cymbals"):
        notes.append(
            "OVERHEADS PRESENT. They are the back and the outer edge of the kit "
            "(Distance %d, the furthest back of anything on the riser) and they "
            "carry the air — which is why everything else gets to stay close "
            "and dry." % (kd + win))

    if n_kit and not metal:
        notes.append(
            "NO HI-HAT AND NO RIDE. There is no metal timekeeper holding the "
            "mid-width, so the toms — or, failing those, the snare — do that "
            "job. Do not push the overheads wider to compensate: a kit with a "
            "hole where the hats should be just sounds like a channel that "
            "never got exported.")

    if n_kit and edge == 0:
        notes.append(
            "KICK AND SNARE ONLY. That is a beat, not a kit: everything stays "
            "Centre, the room stays Small, and Virtual Stage does almost "
            "nothing — which is correct. Spreading a two-piece kit across a "
            "stage is the fastest way to make a programmed beat sound fake.")

    if perc and not kit:
        notes.append(
            "Percussion with no kit behind it: nothing to squeeze past, so it "
            "may use the whole stage. Spread the parts wide and give each one "
            "its own Distance.")

    if has("kick"):
        notes.append(
            "The kick is in the map, but Virtual Stage stays OFF it — it is the "
            "front edge everything else is measured from, and it has to stay "
            "tight, mono and phase-true against the bass.")

    return rows, info


# ---------------------------------------------------------------------------
# THE WHOLE STAGE
# ---------------------------------------------------------------------------
def _stage_prio(iid, overrides=None):
    """Who yields when two channels want the same spot. Lower = stays put.

    A hand-set role beats the smart:EQ group, because that is the whole
    point of setting one: "this riff is the bed, not the hook" is exactly a
    statement about which of the two moves."""
    if iid in KIT_IDS or iid in KIT_OFF_RISER:
        return 0                      # the kit is laid out as one object
    role = ((overrides or {}).get(iid) or {}).get("role")
    if role in STAGE_ROLE_PRIO:
        return STAGE_ROLE_PRIO[role]
    g = SMARTEQ_GROUP.get(iid)
    return _STAGE_PRIO.get(g[0] if g else "mid", 2)


def stage_plan(selected_ids, counts=None, perspective="audience",
               overrides=None):
    """Lay out the ENTIRE line-up on one stage.

    This is the function that makes the advice interactive: no instrument has a
    fixed position, it has a preferred spot which is then changed by

      • how many of its OWN family are in the song  (one guitar is placed
        differently from two, see STAGE_FILL),
      • how many of ITSELF are in the song          (✖N becomes a ladder),
      • which side of the stage is already crowded  (a lone family flips to the
        empty side),
      • who ends up standing too close              (the channel that yields
        under masking is the one that moves),
      • and, for the kit, which kit pieces exist    (drum_stage_plan).

    `overrides` is the hand-placement table (see stage_overrides_clean):
    the three things about the ARRANGEMENT that no amount of looking at the
    line-up can tell you. It is honoured before the balance pass, so the
    rest of the stage is laid out AROUND it rather than over it.

    Returns (rows_by_id, info).
      rows_by_id : {iid: {"pos", "pos_pct", "dist", "room", "lock", "skip",
                          "manual", "why", "because": [str, …]}}
      info       : {"room", "room_why", "notes", "kit_notes", "order",
                    "manual"}"""
    sel = set(selected_ids or ())
    counts = counts or {}
    cnt = lambda i: max(1, int(counts.get(i, 1) or 1))
    _clean = stage_overrides_clean(overrides)
    room_force = _clean.get(STAGE_ROOM_KEY)
    room, room_why = vstage_room(sel, counts, room_force)
    rows, notes = {}, []
    # Only the channels that are actually in this song, and only pairings
    # whose partner turned up as well: an override for a channel that is not
    # ticked is not wrong, it is simply not about this song.
    ov = {i: dict(o) for i, o in _clean.items()
          if i != STAGE_ROOM_KEY and i.partition("#")[0] in sel}
    for _o in ov.values():
        if _o.get("opposite") not in sel:
            _o["opposite"] = ""
        if _o.get("sibling") not in sel:
            _o["sibling"] = ""
    manual_side = set()

    # ---- 1. The drum kit, as one object ------------------------------------
    kit_rows, kit_info = drum_stage_plan(sel, counts, perspective, room=room)
    for r in kit_rows:
        rows[r["id"]] = r

    # ---- 2. The families ----------------------------------------------------
    for fam in STAGE_FAMILIES:
        present = [(iid, anc) for iid, anc in fam["members"] if iid in sel]
        if not present:
            continue
        k = len(present)
        fill = STAGE_FILL.get(k, STAGE_FILL_MAX)
        for iid, anchor in present:
            if iid in VSTAGE_SKIP:
                rows[iid] = _vstage_skip_row(iid, room, cnt(iid))
                continue
            pct = anchor * fam["half"] * fill
            d = DEPTH.get(iid)
            tier = d[0] if d else "mid"
            dist = VSTAGE_TIER_DIST.get(tier, VSTAGE_MID)
            because = []
            if anchor != 0:
                if k == 1:
                    because.append(
                        "It is the only %s in this song, so it is pulled IN to "
                        "%s. Hard-panning a lone instrument leaves the mix "
                        "leaning to one side with nothing answering it."
                        % (fam.get("one", "one of these"),
                           vstage_pos_label(pct)))
                elif k == 2:
                    other = [x for x, _a in present if x != iid]
                    because.append(
                        "Two of the %s family (with the %s), so they take "
                        "opposite edges — that gap IS the width."
                        % (fam["name"].lower(),
                           ", ".join(_stage_name(x) for x in other)))
                else:
                    because.append(
                        "%d of the %s family are in the song, so they use the "
                        "full width and each one gets its own lane."
                        % (k, fam["name"].lower()))
            rows[iid] = {
                "id": iid, "kit": False, "pos_pct": pct, "pos_pcts": None,
                "pos": vstage_pos_label(pct), "dist": dist, "room": room,
                "lock": iid in VSTAGE_LOCK, "skip": False, "manual": False,
                "why": VSTAGE_WHY.get(iid, ""), "because": because,
                "_fam": fam["key"], "_half": fam["half"],
            }

    if not rows:
        return {}, {"room": room, "room_why": room_why, "notes": [],
                    "kit_notes": [], "order": []}

    # ---- 2b. Channels this plug-in should stay off entirely ----------------
    for iid in VSTAGE_SKIP:
        if iid in sel and iid not in rows:
            rows[iid] = _vstage_skip_row(iid, room, cnt(iid))

    # ---- 2c. BY HAND: role and side ----------------------------------------
    # Applied BEFORE the balance pass, so everything that follows lays the
    # stage out around what was decided by hand instead of on top of it.
    # Every line written here starts with a hand and the word YOU: the sheet
    # never takes credit for a number it did not choose, and it never lets a
    # choice of yours look like one of its own.
    for _iid, _o in ov.items():
        r = rows.get(_iid)
        if not r or r["skip"] or r["kit"]:
            continue
        if stage_has_copies(_iid, cnt(_iid)):
            continue                  # one row per COPY: step 4d does these
        auto_pos, auto_dist = r["pos_pct"], r.get("dist")
        role, side = _o.get("role", "auto"), _o.get("side", "auto")
        if side != "auto":
            half = float(r.get("_half") or STAGE_SIDE_DEFAULT)
            mag = abs(r["pos_pct"]) or half * STAGE_SIDE_FRACTION
            if side == "centre":
                r["pos_pct"] = 0.0
                r["lock"] = True
                r["because"].append(
                    "%s YOU put this dead centre by hand (the engine had it "
                    "at %s). Lock Position goes ON with it, so changing its "
                    "Distance later cannot slide it back off the middle."
                    % (STAGE_HAND, vstage_pos_label(auto_pos)))
            else:
                r["pos_pct"] = -mag if side == "left" else mag
                if vstage_pos_label(r["pos_pct"]) == vstage_pos_label(auto_pos):
                    # Saying "the engine had it at R30" about a channel now
                    # sitting at R30 reads like a bug. It is not one - the
                    # placement still DID something - so say what.
                    r["because"].append(
                        "%s YOU set this to the %s by hand. It was already "
                        "at %s, so nothing moved - but it is pinned there "
                        "now: the balance pass can no longer flip it to the "
                        "emptier side, and it WINS a collision instead of "
                        "being the one that yields."
                        % (STAGE_HAND, side, vstage_pos_label(r["pos_pct"])))
                else:
                    r["because"].append(
                        "%s YOU put this on the %s by hand, at %s (the "
                        "engine had it at %s). Everything else on this stage "
                        "is laid out around that, not over it."
                        % (STAGE_HAND, side, vstage_pos_label(r["pos_pct"]),
                           vstage_pos_label(auto_pos)))
            r["pos"] = vstage_pos_label(r["pos_pct"])
            r["manual"] = True
            manual_side.add(_iid)
        if role in STAGE_ROLE_DIST and auto_dist is not None:
            r["dist"] = int(max(STAGE_ROLE_MIN_DIST,
                                min(STAGE_ROLE_MAX_DIST,
                                    auto_dist + STAGE_ROLE_DIST[role])))
            r["manual"] = True
            r["because"].append(STAGE_ROLE_BECAUSE[role]
                                % (STAGE_HAND, auto_dist, r["dist"]))
            if (role == "double" and abs(r["pos_pct"]) > 6
                    and _iid not in manual_side):
                old = r["pos_pct"]
                r["pos_pct"] = old * STAGE_DOUBLE_PULL
                r["pos"] = vstage_pos_label(r["pos_pct"])
                manual_side.add(_iid)
                r["because"].append(
                    "%s ...and it is drawn halfway in towards the middle, "
                    "%s -> %s: a double that stands far from the part it "
                    "doubles stops being a double and becomes a second "
                    "part." % (STAGE_HAND, vstage_pos_label(old), r["pos"]))

    # Co-leads: two or more equal partners take opposite sides, close in.
    _co = [x["id"] for x in EQ_DATA
           if (ov.get(x["id"]) or {}).get("role") == "colead"
           and rows.get(x["id"]) and not rows[x["id"]]["skip"]
           and not rows[x["id"]]["kit"] and x["id"] not in manual_side
           and not stage_has_copies(x["id"], cnt(x["id"]))]
    if len(_co) >= 2:
        _pcts = vstage_ladder(-STAGE_COLEAD_SPAN, STAGE_COLEAD_SPAN, len(_co))
        # Equal partners stand on ONE line: they all take the nearest of the
        # Distances they would have had, or one of them is not an equal.
        _dists = [rows[i]["dist"] for i in _co if rows[i].get("dist") is not None]
        _dnear = min(_dists) if _dists else None
        for _iid, _p in zip(_co, _pcts):
            r = rows[_iid]
            old = r["pos_pct"]
            r["pos_pct"] = _p
            r["pos"] = vstage_pos_label(_p)
            r["manual"] = True
            manual_side.add(_iid)
            if _dnear is not None and r.get("dist") != _dnear:
                r["because"].append(
                    "%s Equal partners stand on one line, so the Distance is "
                    "%d -> %d: the nearest of the co-leads." % (
                        STAGE_HAND, r["dist"], _dnear))
                r["dist"] = _dnear
            r["because"].append(
                "%s YOU made %s co-leads, so they stand on opposite sides of "
                "the middle: %s (the engine had it at %s). Neither is the "
                "'second' voice, and a gap this small keeps them one duet "
                "rather than two people at the edges."
                % (STAGE_HAND, ("these %d" % len(_co)) if len(_co) > 2
                   else "these two", r["pos"], vstage_pos_label(old)))
    elif len(_co) == 1:
        rows[_co[0]]["because"].append(
            "%s YOU marked this a CO-LEAD, but there is no other co-lead in "
            "this song to stand opposite - so it only takes the Distance "
            "step and behaves like a Feature." % STAGE_HAND)

    # ---- 3. Balance: a lone family flips to the emptier side ----------------
    movable = [r for r in rows.values()
               if not r["kit"] and not r["skip"] and abs(r["pos_pct"]) > 6
               and r["id"] not in manual_side]
    left  = sum(-r["pos_pct"] for r in movable if r["pos_pct"] < 0)
    right = sum(r["pos_pct"] for r in movable if r["pos_pct"] > 0)
    if movable and abs(left - right) > 60:
        crowded = -1 if left > right else 1
        for fam in STAGE_FAMILIES:
            members = [iid for iid, _a in fam["members"] if iid in rows]
            if len(members) != 1:
                continue
            r = rows[members[0]]
            if r["kit"] or r["skip"] or abs(r["pos_pct"]) < 10:
                continue
            if r["id"] in manual_side:
                continue          # you put it there; it does not get flipped
            if (r["pos_pct"] < 0) == (crowded < 0):
                r["pos_pct"] = -r["pos_pct"]
                r["pos"] = vstage_pos_label(r["pos_pct"])
                r["because"].append(
                    "Flipped to the other side: the %s of the stage was already "
                    "carrying most of the arrangement, and this is the only %s "
                    "in the song, so it is the one that can move."
                    % ("left" if crowded < 0 else "right", fam["name"].lower()))
                break

    # ---- 4. ✖N: several of the same channel become a ladder ----------------
    for iid, r in rows.items():
        if r["kit"] or r["skip"]:
            continue
        n = cnt(iid)
        half = r.get("_half", 60)
        if iid in VSTAGE_LADDERED and n > 1:
            span = abs(r["pos_pct"]) or half * 0.8
            # A row of six inside ±27 % puts two of them on the same printed
            # spot. Widen the row until the rungs are genuinely apart, as far
            # as the family is allowed to reach and no further.
            limit = min(95.0, max(float(half), span))
            span = min(max(span, STAGE_RUNG_MIN * (n - 1) / 2.0), limit)
            pcts = vstage_ladder(-span, span, n)
            r["pos_pct"] = sum(pcts) / float(len(pcts))
            r["pos_pcts"] = pcts
            r["pos"] = vstage_ladder_label(pcts)
            r["because"].append(
                "✖%d of them, so they are a ROW of players — %d positions "
                "laddered at ONE shared Distance, which is what makes them read "
                "as a section instead of a stack of overdubs." % (n, n))
        elif iid in VSTAGE_LADDERED:
            # ONE channel is ONE position. Virtual Stage has a single Position
            # control per instance, so printing a ladder here was advice that
            # could not be carried out — and the middle rung of that ladder was
            # dead centre, which for a backing vocal is exactly where the lead
            # vocal already is. The row lives inside the recording; Width
            # spreads it, Position places it.
            r["because"].append(
                "Only ONE of these, so it gets ONE position: a row needs at "
                "least two channels to be a row, and Virtual Stage places one "
                "channel at one spot. Whatever width the part already has comes "
                "from the recording and from Width — not from Position.")
        elif n > 1 and iid == "vocals_lead" and iid not in manual_side:
            # Several LEAD voices at once. His question, 2026-10-12: "ska de
            # verkligen bagge vara Center (och distance 18)?" Two singers on
            # one spot at one depth are one source nobody can un-blend, and
            # neither is the lead any more. So: equal partners, the Co-lead
            # logic - close either side of the middle, ONE shared Distance.
            reach = max(STAGE_COLEAD_SPAN, STAGE_RUNG_MIN * (n - 1) / 2.0)
            pcts = vstage_ladder(-reach, reach, n)
            r["pos_pct"] = sum(pcts) / float(len(pcts))
            r["pos_pcts"] = pcts
            r["pos"] = vstage_ladder_label(pcts)
            r["because"].append(
                "\u2716%d lead voices at once, so they do NOT all stand on "
                "Centre: %s, at ONE shared Distance (%s). Singers who sing the "
                "lead together are equal partners - the same job the Co-lead "
                "role does - and a gap this small keeps them one duet rather "
                "than people at the edges. If it is really ONE singer "
                "double-tracked it is a layer instead: keep the main take at "
                "Centre and put the double at Distance %d, one step behind. "
                "The sheet cannot hear which of the two it is."
                % (n, r["pos"], r["dist"],
                   min(STAGE_ROLE_MAX_DIST,
                       (r["dist"] or VSTAGE_MID) + STAGE_ROLE_DIST["double"])))
        elif n > 1 and multi_rule(iid).get("spread") == "mono":
            # The ✖N engine (DEL 02j) calls this part MONO, and its verdict is
            # 'layer': a second lead vocal or a second double bass is a TONE
            # decision, not a width one. Laddering it here would have the
            # program contradict its own advice on the same screen — which is
            # the one thing a cheat sheet must never do.
            r["because"].append(
                "✖%d, but this one does NOT ladder — it stays at %s. More than one "
                "of these is a LAYER: split the frequency range between them, "
                "not the stereo field. That is the same instruction the ✖%d "
                "block gives you, and they have to agree." % (n, r["pos"], n))
        elif n > 1:
            # A channel that is already out at the family's edge grows INWARD:
            # sliding the ladder past the edge would put copy #2 further out
            # than any single instrument is ever placed.
            limit = min(95.0, float(half))
            reach = max(12.0, min(26.0, half * 0.35))
            # …but never so tight that two copies print as the same position.
            reach = min(max(reach, STAGE_RUNG_MIN * (n - 1) / 2.0), limit)
            centre = r["pos_pct"]
            lo, hi = centre - reach, centre + reach
            if hi > limit:
                lo, hi = lo - (hi - limit), limit
            if lo < -limit:
                lo, hi = -limit, hi + (-limit - lo)
            pcts = vstage_ladder(lo, hi, n)
            if n == 2 and r.get("_fam"):
                # TWO of one part is a PAIR: one on each side, equally far
                # out - never both on the same side (a ladder around an
                # edge anchor put both rhythm guitars on the left). If the
                # family has exactly ONE other part, that lone part takes
                # the middle and the pair stands out at the sides.
                _oth = [x for x in rows.values()
                        if x["id"] != iid and x.get("_fam") == r["_fam"]
                        and not x["kit"] and not x["skip"]]
                _lone = None
                if (len(_oth) == 1 and r["_fam"] not in STAGE_PAIR_NO_LONE
                        and cnt(_oth[0]["id"]) == 1
                        and _oth[0]["id"] not in VSTAGE_LADDERED
                        and _oth[0]["id"] not in manual_side
                        and not (ov.get(_oth[0]["id"]) or {}).get("opposite")):
                    _lone = _oth[0]
                if _lone is not None:
                    edge = half * STAGE_PAIR_WITH_LONE
                elif abs(centre) >= 20:
                    edge = half * STAGE_FILL[2]
                else:
                    edge = reach
                edge = min(limit, edge)
                pcts = [-edge, edge] if centre <= 0 else [edge, -edge]
                if _lone is not None:
                    _old = _lone["pos_pct"]
                    _lone["because"] = [
                        b for b in _lone["because"]
                        if not b.startswith(("Two of the ", "It is the only "))]
                    _lone["pos_pct"] = 0.0
                    _lone["pos"] = "Centre"
                    _lone["because"].append(
                        "There are TWO of the %s in this song, so this one "
                        "takes the middle (%s -> Centre) and the pair stands "
                        "out at the sides. One in the middle, two at the "
                        "edges, no side heavier than the other."
                        % (_stage_name(iid), vstage_pos_label(_old)))
            r["pos_pct"] = sum(pcts) / float(len(pcts))
            r["pos_pcts"] = pcts
            r["pos"] = vstage_ladder_label(pcts)
            if n == 2 and r.get("_fam"):
                r["because"].append(
                    "✖2 of these, so they are a PAIR: one on each side, "
                    "equally far out (%s)%s. Two players on the same side "
                    "would be one louder player and leave the other side "
                    "empty." % (
                        vstage_ladder_label(pcts),
                        ", and the %s stands in the middle between them"
                        % _stage_name(_lone["id"]) if _lone is not None
                        else ""))
            else:
                r["because"].append(
                    "✖%d of these, so they are a ladder around %s, not %d "
                    "copies standing in one spot. Two players in the same "
                    "square metre is one louder player."
                    % (n, vstage_pos_label(centre), n))

    # ---- 5. Nobody stands in the same place --------------------------------
    def _shift(rw, delta):
        """Slide a channel sideways — the whole ladder if it has one."""
        rw["pos_pct"] += delta
        if rw.get("pos_pcts"):
            rw["pos_pcts"] = [p + delta for p in rw["pos_pcts"]]
            rw["pos"] = (vstage_numbered_label(rw["pos_pcts"])
                         if rw.get("_numbered")
                         else vstage_ladder_label(rw["pos_pcts"]))
        else:
            rw["pos"] = vstage_pos_label(rw["pos_pct"])

    # ---- 4d. EVERY COPY OF A PART ON ITS OWN ROW ---------------------------
    # His words, 2026-10-13: three solo guitars, and no way to say that one or
    # two of them are supportive - "en rad (med den stems namn) for varje
    # sak". Copy 1 is the plain id in the table, copy k is "id#k".
    #   * Role  -> a Distance step per copy (STAGE_ROLE_DIST), Double also
    #              drawn halfway in;
    #   * Side  -> that copy is pinned (left / right / centre);
    #   * level -> the louder copies sit on the slots nearest the middle
    #              (three or more), or the louder of two is drawn in
    #              (the same balance as step 4c).
    for iid, r in rows.items():
        pcts = r.get("pos_pcts")
        if r["kit"] or r["skip"] or not pcts or len(pcts) < 2:
            continue
        n = len(pcts)
        c_ov = [ov.get(stage_copy_key(iid, k)) or {} for k in range(1, n + 1)]
        roles = [c.get("role", "auto") for c in c_ov]
        sides = [c.get("side", "auto") for c in c_ov]
        if all(x == "auto" for x in roles) and all(x == "auto" for x in sides):
            continue
        half = float(r.get("_half") or STAGE_SIDE_DEFAULT)
        new = list(pcts)
        pinned = set()
        why = [[] for _ in range(n)]
        for k in range(n):
            if sides[k] == "auto":
                continue
            mag = abs(pcts[k]) or half * STAGE_SIDE_FRACTION
            new[k] = (0.0 if sides[k] == "centre"
                      else (-mag if sides[k] == "left" else mag))
            pinned.add(k)
            why[k].append("%s YOU put copy #%d on the %s by hand, at %s." % (
                STAGE_HAND, k + 1, sides[k], vstage_pos_label(new[k])))
        wts = [STAGE_ROLE_WEIGHT.get(x, STAGE_ROLE_WEIGHT["auto"])
               for x in roles]
        free = [k for k in range(n) if k not in pinned]
        if n >= 3 and len({wts[k] for k in free}) > 1:
            slots = [pcts[k] for k in free]
            before = list(new)
            for k in sorted(free, key=lambda j: (-wts[j], j)):
                s = min(slots, key=lambda p: (abs(p), abs(p - pcts[k])))
                slots.remove(s)
                new[k] = s
            if new != before:
                r["because"].append(
                    "%s LEVEL BALANCE: the copies are seated by Role - the "
                    "louder ones nearest the middle, the quieter ones out at "
                    "the edges: %s." % (STAGE_BALANCE,
                                        vstage_numbered_label(new)))
        elif n == 2 and len(free) == 2 and wts[0] != wts[1]:
            hv, lt = (0, 1) if wts[0] > wts[1] else (1, 0)
            ratio = max(STAGE_LEVEL_MIN_RATIO, wts[lt] / wts[hv])
            if (ratio < STAGE_LEVEL_TOLERANCE and abs(new[hv]) > 5
                    and abs(new[lt]) > 5 and (new[hv] < 0) != (new[lt] < 0)):
                mag = min(abs(new[hv]), max(float(STAGE_MIN_GAP) + 1.0,
                                            abs(new[lt]) * ratio))
                old = new[hv]
                new[hv] = mag if old > 0 else -mag
                why[hv].append(
                    "%s LEVEL BALANCE: copy #%d carries more than copy #%d, "
                    "so it is drawn IN, %s -> %s." % (
                        STAGE_BALANCE, hv + 1, lt + 1, vstage_pos_label(old),
                        vstage_pos_label(new[hv])))
        # Copies marked CO-LEAD are equal partners: they take the middle of
        # the stage between them, on opposite sides, the same job the
        # Co-lead role does between two different channels.
        _cl = [k for k in range(n) if roles[k] == "colead" and k not in pinned]
        if len(_cl) >= 2:
            _reach = max(STAGE_COLEAD_SPAN, STAGE_RUNG_MIN * (len(_cl) - 1) / 2.0)
            for k, p in zip(_cl, vstage_ladder(-_reach, _reach, len(_cl))):
                new[k] = p
                why[k].append(
                    "%s YOU made copies %s co-leads, so they stand on opposite "
                    "sides of the middle: %s. Neither is the 'second' voice."
                    % (STAGE_HAND, ", ".join("#%d" % (j + 1) for j in _cl),
                       vstage_pos_label(p)))
        offs = [0] * n
        base_dist = r.get("dist")
        for k in range(n):
            if roles[k] in STAGE_ROLE_DIST and base_dist is not None:
                d = int(max(STAGE_ROLE_MIN_DIST, min(
                    STAGE_ROLE_MAX_DIST, base_dist + STAGE_ROLE_DIST[roles[k]])))
                offs[k] = d - base_dist
                why[k].append(STAGE_ROLE_BECAUSE[roles[k]]
                              % (STAGE_HAND, base_dist, d))
                if (roles[k] == "double" and k not in pinned
                        and abs(new[k]) > 6):
                    old = new[k]
                    new[k] = old * STAGE_DOUBLE_PULL
                    why[k].append(
                        "%s ...and it is drawn halfway in towards the middle, "
                        "%s -> %s." % (STAGE_HAND, vstage_pos_label(old),
                                       vstage_pos_label(new[k])))
        r["pos_pcts"] = new
        r["pos_pct"] = sum(new) / float(n)
        r["_numbered"] = True
        r["pos"] = vstage_numbered_label(new)
        r["manual"] = True
        if pinned:
            manual_side.add(iid)
        if any(offs):
            r["_dist_off"] = offs
        for k in range(n):
            for line in why[k]:
                r["because"].append("#%d: %s" % (k + 1, line))

    # ---- 4b. COUNTERPOLES: two parts that answer each other ---------------
    # "Kanske inte optimalt att bagge ar R." Two parts that ANSWER each other
    # belong on opposite sides, and WHICH two those are is a fact about the
    # song rather than about the instruments - so it is said by hand, and
    # honoured here: after the ladders (so a row moves as a row) and before
    # the collision pass (so the result is still checked like everything
    # else).
    for _a_id, _b_id in stage_override_pairs(ov):
        ra, rb = rows.get(_a_id), rows.get(_b_id)
        if not ra or not rb or ra["skip"] or rb["skip"]:
            continue
        if ra["kit"] or rb["kit"]:
            continue
        ra["manual"] = rb["manual"] = True
        apart = ((ra["pos_pct"] < 0) != (rb["pos_pct"] < 0)
                 and abs(ra["pos_pct"]) > 5 and abs(rb["pos_pct"]) > 5)
        if apart:
            for one, two in ((ra, rb), (rb, ra)):
                one["because"].append(
                    "%s YOU paired this with the %s as counterpoles, and "
                    "they already stand on opposite sides (%s and %s) - "
                    "nothing had to move."
                    % (STAGE_HAND, _stage_name(two["id"]),
                       vstage_pos_label(one["pos_pct"]),
                       vstage_pos_label(two["pos_pct"])))
            continue
        if _a_id in manual_side and _b_id in manual_side:
            for one, two in ((ra, rb), (rb, ra)):
                one["because"].append(
                    "%s YOU paired this with the %s as counterpoles AND put "
                    "both of them on the same side by hand. Nothing is "
                    "moved: undoing one of your own placements to satisfy "
                    "the other would be this program overruling you. Change "
                    "one of the two sides."
                    % (STAGE_HAND, _stage_name(two["id"])))
            continue
        if _a_id in manual_side:
            keep, move = ra, rb
        elif _b_id in manual_side:
            keep, move = rb, ra
        elif _stage_prio(_a_id, ov) <= _stage_prio(_b_id, ov):
            keep, move = ra, rb
        else:
            keep, move = rb, ra
        half = float(move.get("_half") or STAGE_SIDE_DEFAULT)
        mag = max(abs(keep["pos_pct"]), half * STAGE_SIDE_FRACTION,
                  float(STAGE_MIN_GAP))
        target = -mag if keep["pos_pct"] >= 0 else mag
        _shift(move, target - move["pos_pct"])
        move["because"].append(
            "%s YOU paired this with the %s as counterpoles, so it is moved "
            "to %s - the opposite side from the %s at %s. Two parts that "
            "answer each other standing on the same side is one thicker "
            "part, not a conversation."
            % (STAGE_HAND, _stage_name(keep["id"]),
               vstage_pos_label(move["pos_pct"]), _stage_name(keep["id"]),
               vstage_pos_label(keep["pos_pct"])))
        keep["because"].append(
            "%s YOU paired this with the %s as counterpoles; the %s moved to "
            "%s and this one kept its place."
            % (STAGE_HAND, _stage_name(move["id"]), _stage_name(move["id"]),
               vstage_pos_label(move["pos_pct"])))
        manual_side.add(move["id"])

    # ---- 4b2. SIBLINGS: a matched stereo pair ------------------------------
    # His words, 2026-10-18: an individual stereo pair where it does not
    # matter whether either one is the Lead - they relate to EACH OTHER, and
    # unless one of them is already tied to something else they stand one on
    # each side of the middle, as a mirror image (same distance from Centre,
    # same Distance), as long as that is practical.
    #   * nothing about Role is read: siblings are equal by definition, so the
    #     level balance (4c) leaves them alone;
    #   * "tied to something else" = placed by hand (Side). That one stays and
    #     its sibling takes the mirror spot; both placed by hand = nothing
    #     moves and both say so;
    #   * a part with several copies pairs ITSELF (step 4), so it is skipped.
    sib_ids = set()
    sib_done = []
    for _a_id, _b_id in stage_sibling_pairs(ov):
        ra, rb = rows.get(_a_id), rows.get(_b_id)
        if not ra or not rb or ra["skip"] or rb["skip"]:
            continue
        if ra["kit"] or rb["kit"]:
            continue
        if ra.get("pos_pcts") or rb.get("pos_pcts"):
            continue
        sib_ids.update((_a_id, _b_id))
        ra["manual"] = rb["manual"] = True
        a_hand, b_hand = _a_id in manual_side, _b_id in manual_side
        if a_hand and b_hand:
            _mirrored = abs(ra["pos_pct"] + rb["pos_pct"]) < 5 \
                and abs(ra["pos_pct"]) > 5
            for one, two in ((ra, rb), (rb, ra)):
                one["because"].append(
                    "%s YOU made this a SIBLING of the %s, and placed both by "
                    "hand: %s. Nothing is moved - undoing a placement you "
                    "made on purpose is not this program's call."
                    % (STAGE_HAND, _stage_name(two["id"]),
                       "they already stand as a mirror pair" if _mirrored
                       else "they do NOT mirror each other (%s and %s)"
                       % (vstage_pos_label(one["pos_pct"]),
                          vstage_pos_label(two["pos_pct"]))))
            sib_done.append((_a_id, _b_id))
            continue
        half = float(ra.get("_half") or STAGE_SIDE_DEFAULT)
        if a_hand or b_hand:
            keep, move = (ra, rb) if a_hand else (rb, ra)
            if abs(keep["pos_pct"]) <= 5:
                for one, two in ((keep, move), (move, keep)):
                    one["because"].append(
                        "%s YOU made this a SIBLING of the %s, but one of "
                        "them is at Centre by hand, so there is nothing to "
                        "mirror. Nothing is moved." % (
                            STAGE_HAND, _stage_name(two["id"])))
                sib_done.append((_a_id, _b_id))
                continue
            _old = move["pos_pct"]
            _shift(move, -keep["pos_pct"] - move["pos_pct"])
            move["because"].append(
                "%s YOU made this a SIBLING of the %s, which you placed at %s "
                "- so this one takes the mirror spot, %s -> %s."
                % (STAGE_HAND, _stage_name(keep["id"]),
                   vstage_pos_label(keep["pos_pct"]),
                   vstage_pos_label(_old), vstage_pos_label(move["pos_pct"])))
            keep["because"].append(
                "%s YOU made this a SIBLING of the %s, so that one stands at "
                "the mirror spot %s." % (STAGE_HAND, _stage_name(move["id"]),
                                         vstage_pos_label(move["pos_pct"])))
        else:
            mag = (abs(ra["pos_pct"]) + abs(rb["pos_pct"])) / 2.0
            if mag < STAGE_MIN_GAP:
                mag = max(half * STAGE_SIDE_FRACTION, float(STAGE_MIN_GAP))
            mag = min(95.0, mag)
            left, right = sorted(
                (ra, rb), key=lambda x: (x["pos_pct"], x["id"]))
            _ol, _or = left["pos_pct"], right["pos_pct"]
            _shift(left, -mag - left["pos_pct"])
            _shift(right, mag - right["pos_pct"])
            for one, two, old in ((left, right, _ol), (right, left, _or)):
                one["because"].append(
                    "%s YOU made this a SIBLING of the %s: a matched stereo "
                    "pair, one on each side of the middle, as a mirror image "
                    "(%s, the engine had it at %s). Role does not matter "
                    "here - siblings are equal by definition."
                    % (STAGE_HAND, _stage_name(two["id"]),
                       vstage_pos_label(one["pos_pct"]),
                       vstage_pos_label(old)))
        manual_side.update((_a_id, _b_id))
        sib_done.append((_a_id, _b_id))

    # ---- 4c. LEVEL BALANCE: the louder part stands nearer the middle -------
    # His question, 2026-10-12: two guitars on mirrored edges, one at 80 %
    # and one at 45 % - "blir det ju mycket mindre gitarr pa den sidan.
    # Borde det inte kompenseras for? Equal, Lead/Behind, Support."
    # Only a family with exactly ONE part on each side (a pair), no ladders,
    # and only when the Roles say the two do not carry the same amount.
    _fam_rows = {}
    for r in rows.values():
        if (r.get("_fam") and not r["kit"] and not r["skip"]
                and not r.get("pos_pcts") and r["id"] not in sib_ids):
            _fam_rows.setdefault(r["_fam"], []).append(r)
    _role_label = {k: lbl for k, lbl, _d in STAGE_ROLES}
    for _fam_key, _members in _fam_rows.items():
        _left = [r for r in _members if r["pos_pct"] < -5]
        _right = [r for r in _members if r["pos_pct"] > 5]
        if len(_left) != 1 or len(_right) != 1:
            continue
        _wa = _stage_weight(_left[0]["id"], ov)
        _wb = _stage_weight(_right[0]["id"], ov)
        if min(_wa, _wb) / max(_wa, _wb) >= STAGE_LEVEL_TOLERANCE:
            continue                      # Equal: nothing to compensate
        heavy, light = ((_left[0], _right[0]) if _wa > _wb
                        else (_right[0], _left[0]))
        ratio = max(STAGE_LEVEL_MIN_RATIO,
                    min(_wa, _wb) / max(_wa, _wb))
        _hrole = (ov.get(heavy["id"]) or {}).get("role", "auto")
        _lrole = (ov.get(light["id"]) or {}).get("role", "auto")
        who = ("%s (%s) carries more of the song than the %s (%s)"
               % (_stage_name(heavy["id"]), _role_label.get(_hrole, "Auto"),
                  _stage_name(light["id"]), _role_label.get(_lrole, "Auto")))
        old_h, old_l = heavy["pos_pct"], light["pos_pct"]
        if heavy["id"] not in manual_side:
            mag = min(abs(old_h), max(float(STAGE_MIN_GAP) + 1.0,
                                      abs(old_l) * ratio))
            _shift(heavy, (mag if old_h > 0 else -mag) - old_h)
            if vstage_pos_label(old_h) != vstage_pos_label(heavy["pos_pct"]):
                heavy["because"].append(
                    "%s LEVEL BALANCE: the %s, and they stand on opposite "
                    "sides. Mirrored positions would lean the stage towards "
                    "the louder side, so the louder one is drawn IN, %s -> %s "
                    "(the %s stays at %s). Give both the same Role to undo "
                    "this."
                    % (STAGE_BALANCE, who, vstage_pos_label(old_h),
                       heavy["pos"], _stage_name(light["id"]),
                       vstage_pos_label(old_l)))
                light["because"].append(
                    "%s LEVEL BALANCE: this part is the quieter of the pair, "
                    "so it keeps the edge (%s) and the %s moved in to %s to "
                    "even out the stage."
                    % (STAGE_BALANCE, vstage_pos_label(old_l),
                       _stage_name(heavy["id"]), heavy["pos"]))
        elif light["id"] not in manual_side:
            mag = max(abs(old_l), min(95.0, abs(old_h) / ratio))
            _shift(light, (mag if old_l > 0 else -mag) - old_l)
            if vstage_pos_label(old_l) != vstage_pos_label(light["pos_pct"]):
                light["because"].append(
                    "%s LEVEL BALANCE: the %s, and you placed the louder one "
                    "by hand, so this quieter one goes further OUT instead, "
                    "%s -> %s, to even out the stage."
                    % (STAGE_BALANCE, who, vstage_pos_label(old_l),
                       light["pos"]))

    # Rows that stand BEHIND each other (STAGE_BEHIND, applied in step 6b2) are
    # not in each other's way, so the collision pass leaves them alone.
    _behind = {(i, f) for i, (f, _g) in STAGE_BEHIND.items()
               if i in rows and f in rows}
    order = sorted(rows.values(), key=lambda r: r["pos_pct"])
    told_pairs = set()
    for _pass in range(3):
        moved_any = False
        order.sort(key=lambda r: r["pos_pct"])
        for a, b in zip(order, order[1:]):
            if a["skip"] or b["skip"]:
                continue
            if a["kit"] and b["kit"]:
                continue          # the kit is laid out as one object already
            gap = b["pos_pct"] - a["pos_pct"]
            da, db = a.get("dist"), b.get("dist")
            if da is None or db is None or abs(da - db) > 12:
                continue          # different depth = they are not in each other's way
            if (a["id"], b["id"]) in _behind or (b["id"], a["id"]) in _behind:
                continue          # one row stands behind the other
            if gap >= STAGE_MIN_GAP:
                continue
            need = STAGE_MIN_GAP - gap
            pa, pb = _stage_prio(a["id"], ov), _stage_prio(b["id"], ov)
            am, bm = a["id"] in manual_side, b["id"] in manual_side
            if am and bm:
                # Two placements you made on purpose. Moving either one is
                # the program overruling you, and moving both is it
                # overruling you twice - so it says so instead, once.
                _key = tuple(sorted((a["id"], b["id"])))
                if _key not in told_pairs:
                    told_pairs.add(_key)
                    for m, other in ((a, b), (b, a)):
                        m["because"].append(
                            "%s YOU placed both this and the %s by hand, and "
                            "they end up %d apart where %d is the minimum. "
                            "Neither is moved. Separate them by TONE and by "
                            "LEVEL, or move one of them yourself."
                            % (STAGE_HAND, _stage_name(other["id"]),
                               int(round(gap)), STAGE_MIN_GAP))
                continue
            if am:
                pa -= 10          # you put it there: the other one moves
            if bm:
                pb -= 10
            if pa == pb:
                _shift(a, -need / 2.0)
                _shift(b, need / 2.0)
                movers = [(a, b), (b, a)]
            elif pa > pb:
                _shift(a, -need)
                movers = [(a, b)]
            else:
                _shift(b, need)
                movers = [(b, a)]
            for m, other in movers:
                m["because"].append(
                    "Moved to %s to clear the %s, which is at the same depth: "
                    "two sources standing in the same spot at the same distance "
                    "are one source you cannot un-blend."
                    % (vstage_pos_label(m["pos_pct"]), _stage_name(other["id"])))
            moved_any = True
        if not moved_any:
            break
    # ---- 5c. Two doubled basses must not both be told "Centre" ------------
    # The option is computed one instrument at a time, so *2 root basses AND
    # *2 bass loops both came back with "Position Centre" - two character
    # layers standing on the same spot at the same Distance, which is the one
    # thing the option exists to prevent. Opposite sides instead, inside the
    # +/-12 the low end allows, and the side is chosen from what is already
    # standing at THAT depth (a character layer sits at VSTAGE_BASS_OPT_DIST,
    # so anything within 12 of it is in the way and anything further back is
    # not). Only fires with two or more eligible: one on its own is centred
    # for the same reason a lone guitar is pulled in.
    elig = [r for r in rows.values()
            if isinstance(r.get("option"), dict)
            and int(r["option"].get("n") or 1) >= 2
            and r["option"].get("pos_line") is not None]
    if len(elig) >= 2:
        elig.sort(key=lambda r: (_stage_prio(r["id"]), r["id"]))
        # Who is standing at a character layer's depth and actually on a
        # SIDE. Centre is excluded on purpose: the kick, the snare and the
        # lead vocal are centred in every song, and the kick is the Distance
        # everything else is measured from - counting them as blockers made
        # this fire in every song and name "Centre" as a side.
        busy = [(r["pos_pct"], r["id"]) for r in rows.values()
                if r.get("dist") is not None
                and abs(r["dist"] - VSTAGE_BASS_OPT_DIST) <= 12
                and abs(r["pos_pct"]) > 5
                and not isinstance(r.get("option"), dict)]

        def _clear(p):
            return min((abs(p - o) for o, _n in busy), default=999.0)

        P = float(VSTAGE_BASS_OPT_POS)
        if len(elig) == 2:
            spots = [-P, P] if _clear(-P) >= _clear(P) else [P, -P]
        else:
            spots = vstage_ladder(-P, P, len(elig))
        names = ", ".join(_stage_name(r["id"]) for r in elig)
        for r, p in zip(elig, spots):
            opt = r["option"]
            i = int(opt["pos_line"])
            old_field = "Position " + str(opt["pos_text"])
            new_field = "Position " + vstage_pos_label(p)
            if old_field in opt["lines"][i]:
                opt["lines"][i] = opt["lines"][i].replace(
                    old_field, new_field, 1)
                opt["pos_text"] = vstage_pos_label(p)
                opt["side_pct"] = p
                # Describe THIS layer's own clearance, not the other one's.
                # With two layers there are only two sides inside +/-12, so the
                # second one takes what is left whether or not it is free - and
                # saying "most room" about a side that is not free is exactly
                # the kind of number this sheet must never hand out.
                mine = [(o, nm) for o, nm in busy
                        if abs(p - o) < STAGE_MIN_GAP]
                other = [(o, nm) for o, nm in busy
                         if abs(-p - o) < STAGE_MIN_GAP]
                head = ("Not Centre, because %s are BOTH eligible this song: "
                        "two character layers at Centre is two sources on one "
                        "spot, which is what this option exists to avoid."
                        % names)
                if mine:
                    o, nm = min(mine, key=lambda t: abs(p - t[0]))
                    tail = (" %s is what is LEFT, not what is free: the %s "
                            "stands at %s at the same depth, %d apart where %d "
                            "is the minimum. Inside the +/-%d a bass may use "
                            "there is no clean third spot, so pick one on "
                            "purpose: accept the overlap, move the %s, or leave "
                            "this layer at Centre and let the other one have "
                            "the side."
                            % (vstage_pos_label(p), _stage_name(nm),
                               vstage_pos_label(o),
                               abs(round(p / 5.0) * 5 - round(o / 5.0) * 5),
                               STAGE_MIN_GAP,
                               VSTAGE_BASS_OPT_POS, _stage_name(nm)))
                elif other:
                    o, nm = min(other, key=lambda t: abs(-p - t[0]))
                    tail = (" %s is clear at Distance %d; %s is not - the %s "
                            "stands at %s at the same depth."
                            % (vstage_pos_label(p), VSTAGE_BASS_OPT_DIST,
                               vstage_pos_label(-p), _stage_name(nm),
                               vstage_pos_label(o)))
                else:
                    tail = (" %s is clear at Distance %d, and so is the other "
                            "side - either way round works here."
                            % (vstage_pos_label(p), VSTAGE_BASS_OPT_DIST))
                opt["lines"].insert(i + 1, head + tail)

    for r in rows.values():
        r.pop("_fam", None)
        r.pop("_half", None)

    # ---- 5b. Two copies told to stand in the same spot ---------------------
    # A stage is only so wide, and positions print rounded to 5 with everything
    # inside ±5 reading as "Centre", so a wide enough ladder can still run out
    # of distinct places. Saying so is better than printing one position twice
    # and leaving him to find it — which is exactly how this was reported.
    for r in rows.values():
        pcts = r.get("pos_pcts")
        if not pcts or len(pcts) < 2:
            continue
        parts = [vstage_pos_label(p) for p in pcts]
        if len(set(parts)) == len(parts):
            continue
        r["because"].append(
            "✖%d is more than this row has distinct places for at the width it "
            "is allowed, so some of them share a position — which is what a "
            "real section does anyway. Separate the ones that share a spot by "
            "TONE and by LEVEL, not by dragging them further apart." % len(pcts))

    # ---- 6. Nobody stands on the same LINE either --------------------------
    # A mix where nine channels all sit at Distance 50 is a wall, not a stage.
    by_dist = {}
    for r in rows.values():
        if r["kit"] or r["skip"] or r["dist"] is None:
            continue
        by_dist.setdefault(r["dist"], []).append(r)
    for dist, group in by_dist.items():
        if len(group) < 4:
            continue
        group.sort(key=lambda r: (_stage_prio(r["id"]), abs(r["pos_pct"])))
        for i, r in enumerate(group):
            step = (i - (len(group) - 1) / 2.0) * 3.0
            r["dist"] = int(max(0, min(100, round(dist + step))))
            if abs(step) >= 1:
                r["because"].append(
                    "Nudged to Distance %d: %d channels wanted the exact same "
                    "depth, and a row of sources on one line is a wall, not a "
                    "stage. The ones that win masking stay nearer the front."
                    % (r["dist"], len(group)))

    # ---- 6b. A section stands on ONE line -----------------------------------
    for label, members in STAGE_SAME_DIST:
        # A part whose Role you set by hand keeps the Distance that Role
        # gave it: averaging it back would undo the very step you chose.
        group = [rows[i] for i in members
                 if i in rows and not rows[i]["skip"] and rows[i]["dist"] is not None
                 and (ov.get(i) or {}).get("role") not in STAGE_ROLE_DIST]
        if len(group) < 2:
            continue
        d = int(round(sum(r["dist"] for r in group) / float(len(group))))
        for r in group:
            if r["dist"] != d:
                r["because"].append(
                    "Distance pulled to %d so the whole %s stands on ONE line "
                    "with %s. Players at different depths stop sounding like a "
                    "section and start sounding like separate overdubs."
                    % (d, label,
                       ", ".join(_stage_name(x["id"]) for x in group if x is not r)))
            r["dist"] = d

    # ---- 6b1. Siblings stand on ONE line ------------------------------------
    for _a_id, _b_id in sib_done:
        ra, rb = rows.get(_a_id), rows.get(_b_id)
        if (not ra or not rb or ra.get("dist") is None
                or rb.get("dist") is None or ra["dist"] == rb["dist"]):
            continue
        a_role = (ov.get(_a_id) or {}).get("role") in STAGE_ROLE_DIST
        b_role = (ov.get(_b_id) or {}).get("role") in STAGE_ROLE_DIST
        if a_role and b_role:
            continue                  # both Roles chosen by hand: both stay
        if a_role:
            d = ra["dist"]
        elif b_role:
            d = rb["dist"]
        else:
            d = int(round((ra["dist"] + rb["dist"]) / 2.0))
        for one, two in ((ra, rb), (rb, ra)):
            if one["dist"] != d:
                one["because"].append(
                    "Distance %d -> %d so the siblings stand on ONE line with "
                    "the %s: a matched pair at two depths is not a pair."
                    % (one["dist"], d, _stage_name(two["id"])))
                one["dist"] = d

    # ---- 6b2. A row stands BEHIND the row in front of it --------------------
    for _iid, (_front, _gap) in STAGE_BEHIND.items():
        rb, rf = rows.get(_iid), rows.get(_front)
        if (not rb or not rf or rb["skip"] or rf["skip"]
                or rb.get("dist") is None or rf.get("dist") is None):
            continue
        want = min(STAGE_BEHIND_MAX, rf["dist"] + _gap)
        if rb["dist"] < want:
            old = rb["dist"]
            rb["dist"] = int(want)
            rb["because"].append(
                "Distance %d -> %d: one row BEHIND the %s (Distance %d). Two "
                "rows of singers on one line are one row - and the bed of "
                "oohs and trailing words is meant to sit behind the "
                "singers who have the words." % (
                    old, rb["dist"], _stage_name(_front), rf["dist"]))

    # ---- 6c. Per-copy Distances (step 4d) on top of the final row Distance -
    for r in rows.values():
        off = r.pop("_dist_off", None)
        r.pop("_numbered", None)
        if off and r.get("dist") is not None:
            ds = [int(max(0, min(100, r["dist"] + o))) for o in off]
            if len(set(ds)) > 1:
                r["dists"] = ds

    # ---- 7. Song-level notes ------------------------------------------------
    notes.append("ONE ROOM for the whole song: %s. %s" % (room, room_why))
    if ov:
        notes.append(
            "%s HAND-PLACED in this song: %s. The rest of the stage was laid "
            "out AROUND them. Every line that begins with a hand is a "
            "decision of yours, not a number this program worked out - clear "
            "the override and the engine takes that channel back."
            % (STAGE_HAND,
               ", ".join(_stage_name(i) for i in
                         sorted({k.partition("#")[0] for k in ov}))))
    notes.append(
        "Generate > Virtual Stage presets writes these numbers as presets, one "
        "file per channel, named by what is in them (3---Cello---D46---L10). "
        "They are a snapshot of THIS line-up: change what is ticked, read the "
        "numbers again and generate again - the new numbers get new names.")
    if kit_info.get("notes"):
        notes.append(
            "The drum kit is laid out as ONE object (Distance %s–%s) — see the "
            "kit notes below." % (kit_info.get("lo"), kit_info.get("hi")))
    lead = rows.get("vocals_lead")
    if lead and not lead["skip"]:
        nearer = [r for r in rows.values()
                  if not r["skip"] and r["dist"] is not None
                  and r["dist"] < lead["dist"] and not r["kit"]]
        if nearer:
            notes.append(
                "%s %s nearer than the lead vocal. That is allowed exactly "
                "once, for a solo — otherwise pull them back, because the "
                "closest thing in a mix is the thing the listener follows."
                % (", ".join(_stage_name(r["id"]) for r in nearer),
                   "is" if len(nearer) == 1 else "are"))
    # v3.30: the backing-vocal roles (doubles / harmonies / own parts) as alternatives.
    try:
        _balts = vstage_backing_alts(rows)
        if _balts:
            rows["vocals_backing"]["alts"] = _balts
    except Exception:
        pass
    return rows, {"room": room, "room_why": room_why, "notes": notes,
                  "kit_notes": kit_info.get("notes", []),
                  "kit_info": kit_info,
                  "manual": ov,
                  "order": [r["id"] for r in sorted(rows.values(),
                                                    key=lambda x: x["pos_pct"])]}


def _stage_name(iid):
    """Instrument name for a sentence, without needing the app object."""
    for x in EQ_DATA:
        if x["id"] == iid:
            return x["name"]
    return iid


def vstage_head(info):
    """The one-line header for a channel:
    '🎪 Virtual Stage: R25 · Distance 47 · Room Medium'."""
    if not info:
        return ""
    if info.get("swam"):
        return "\U0001f3aa Virtual Stage: OFF \u2014 placed in SWAM (see below)"
    if info.get("skip"):
        opt = info.get("option")
        if opt:
            return ("🎪 Virtual Stage: OFF on the foundation  ·  ✖%d opens ONE "
                    "option (below)" % opt["n"])
        return "🎪 Virtual Stage: OFF on this channel"
    bits = ["🎪 Virtual Stage: " + info["pos"]]
    if info.get("dist") is not None:
        bits.append("Distance " + stage_dist_text(info))
    if info.get("room"):
        bits.append("Room %s" % info["room"])
    if info.get("lock"):
        bits.append("Lock Position ON")
    return "  ·  ".join(bits)


# ---- v3.30: BACKING VOCALS, THREE ROLES (2026-11-08) -------------------------
# The default backing-vocal row (a ladder far behind the lead) is right for a group of
# singers with their own parts. Two other roles want a different spot, so the
# card for Backing Vocals prints them as ALTERNATIVES under the normal numbers
# (idea from musicguymixing.com/panning-backing-vocals, his request: a few more rows).
#   doubles    copies of the lead that only thicken it: hard L/R, tight to the
#              lead; the lead stays in the middle. Level ~20 dB under the lead.
#   harmonies  thirds / fourths / fifths / octaves: only ~10 % off centre, so
#              they blend with the lead instead of standing apart from it.
#   own parts  different timing / melody / rhythm: out at the sides (the default
#              row); hard L/R in a busy mix; double it once and put the copies
#              hard L/R.
# Rule behind all three: the further from the centre, the less a backing
# vocal is attached to the lead. Distance is set relative to the lead's.
# ToDo: Generate > Virtual Stage presets does not write these alternatives yet.
VSTAGE_BACKING_ALTS = (
    {"name": "Doubles", "what": "copies of the lead that only thicken it",
     "pcts": (-100, 100), "gap": 6,
     "how": "hard left and right, the lead stays in the middle; about 20 dB "
            "below the lead, timing as tight to it as you can get"},
    {"name": "Harmonies", "what": "thirds, fourths, fifths, octaves",
     "pcts": (-10, 10), "gap": 12,
     "how": "just off centre so they blend with the lead; one harmony = one "
            "side only"},
    {"name": "Own parts", "what": "different timing, melody or rhythm than the lead",
     "pcts": (-70, 70), "gap": None,
     "how": "out at the sides, or hard L/R in a busy mix; double it once and "
            "put the two copies hard L/R"},
)
VSTAGE_BACKING_ALTS_WHY = (
    "The further a backing vocal stands from the centre, the less attached it "
    "sounds to the lead: doubles hug the lead from the edges, harmonies stay "
    "inside it, own parts stand apart. Cubase pan stays at centre - the "
    "position is set here.")


def vstage_backing_alts(rows):
    """The alternatives for the Backing Vocals row, or None.

    Returns {"head", "lines", "why"}. Distances follow the lead vocal's (the
    default row stands far behind it); the normal numbers stay as they are."""
    row = rows.get("vocals_backing")
    if not row or row.get("skip") or row.get("dist") is None:
        return None
    lead = rows.get("vocals_lead")
    base = lead["dist"] if (lead and not lead.get("skip")
                            and lead.get("dist") is not None) else None
    lines = []
    for a in VSTAGE_BACKING_ALTS:
        lo, hi = a["pcts"]
        if a["gap"] is None or base is None:
            dist = row["dist"]
        else:
            dist = int(min(row["dist"], base + a["gap"]))
        lines.append("%s (%s):  %s  ·  Distance %d  -  %s."
                     % (a["name"], a["what"],
                        vstage_ladder_label([lo, hi]), dist, a["how"]))
    return {"head": "If the backing vocals are something else than the row above "
                    "(same Room, Cubase pan at centre)",
            "lines": lines, "why": VSTAGE_BACKING_ALTS_WHY}


# What Virtual Stage replaces, and what it must not be stacked on top of. This
# is the part that saves a mix: the plug-in is already doing a pan, a width, a
# delay and a reverb, so doing any of them AGAIN on the same channel is how a
# mix ends up with two rooms in it.
VSTAGE_CHAIN = [
    ("Where in the chain",
     "Low cut → Kirchhoff EQ → compressor → VIRTUAL STAGE → (nothing else "
     "spatial). It goes near the end, because it has to hear the finished tone "
     "of the channel in order to place it."),
    ("It replaces the pan",
     "Position IS the pan for that channel. Leave the Cubase pan at centre and "
     "let Virtual Stage do it, or the two disagree and the source smears."),
    ("It replaces the reverb send",
     "A channel on Virtual Stage should NOT also go to the Near/Mid/Far reverb "
     "bus at the same depth — that is two rooms at once. Either place it here "
     "or send it there. Keep the send only for a deliberate extra effect (a "
     "long tail on a lead), never for the same depth twice."),
    ("It is not a width plug-in",
     "It narrows as readily as it widens, because that is what distance does. "
     "If you want a source wider than it is, that is a different tool."),
    ("One room for the song",
     "Every instance gets the same Room. Closeness comes from Distance."),
    ("Presets are snapshots",
     "Every number depends on the rest of the line-up, so a preset is only "
     "right for THIS line-up. Generate > Virtual Stage presets names each file "
     "by its numbers; when the arrangement changes, generate again."),
]

# *************** DEL 02k - HEARING PROFILE (mixing with hearing loss) ********
# This program exists to replace an ear that cannot be fully trusted. That works
# far better when the program KNOWS which parts of the spectrum you can still
# judge. Fill in the profile (Help ▸ 🦻 Hearing profile) and every band in every
# card is marked:
#
#     ✔  judge this by ear          — your ear is the best tool you have here
#     ◐  set the number, then check — trust it only for large moves
#     ⛔  use the number, full stop  — do not adjust this one by ear
#
# and three things change:
#   1. BOOSTS ARE CAPPED in the ranges you cannot hear. This is the single most
#      common way a hearing-impaired mix goes wrong: you raise a band until YOU
#      can hear it, which means everybody else gets it 8-10 dB too loud. The cap
#      is not a limitation, it is the whole point.
#   2. "TRY / depends on the track" bands inside a lost range stop being a
#      question. The program picks the value and says so — an undecidable choice
#      is worse than a slightly wrong one.
#   3. The 🦻 window prints YOUR rules: what to set by number, what to check on a
#      meter, and which of your own plug-ins decide by ANALYSIS instead of by ear.
#
# Nothing here is medical advice and it does not replace an audiogram — it is a
# working preference, in your own words, about what you can hear today.

HEARING_COLOUR = "#ffd479"    # amber, distinct from the other footnote colours

# key, low Hz, high Hz, label, what lives there. Octave-wide bands, because that
# is how an audiogram is measured and how you would describe it out loud.
HEARING_BANDS = [
    ("125",  20,    180,   "125 Hz",  "Weight and rumble — kick body, bass fundamentals, room noise"),
    ("250",  180,   355,   "250 Hz",  "Warmth and mud — the 'boxy' zone every card asks you to cut"),
    ("500",  355,   710,   "500 Hz",  "Low mids — body of guitars, organ, horns, snare"),
    ("1k",   710,   1400,  "1 kHz",   "Mid core — where a note gets its identity"),
    ("2k",   1400,  2800,  "2 kHz",   "Attack and intelligibility — consonants, pick, stick, reed"),
    ("4k",   2800,  5600,  "4 kHz",   "Presence — who sits in front. The most commonly lost range"),
    ("8k",   5600,  11200, "8 kHz",   "Sibilance and sizzle — 's' sounds, cymbal shimmer, harshness"),
    ("16k",  11200, 30000, "16 kHz",  "Air — the top shelf. Almost everyone loses some of this"),
]

# state -> (glyph, colour, short label, what it means for a decision)
HEARING_STATES = {
    "ok":   ("✔", C_BOOST,   "Hear it well",
             "Judge this one by ear — your ear is more accurate than any number here."),
    "weak": ("◐", "#ffcf8f", "Not sure",
             "Set the printed number FIRST. Then adjust by no more than ±2 dB, and only if it is obvious."),
    "lost": ("⛔", C_CUT,    "Cannot judge",
             "Use the printed number and leave it. Anything you 'fix' by ear in this range will be wrong for everyone else."),
}
HEARING_ORDER = ["ok", "weak", "lost"]

# Hard caps applied to the program's own suggestions in each state. Boosts are
# capped tightly (a boost you cannot hear becomes harshness for the listener);
# cuts are capped more loosely (a cut is subtractive and far more forgiving).
HEARING_BOOST_CAP = {"ok": None, "weak": 4, "lost": 2}
HEARING_CUT_CAP   = {"ok": None, "weak": -8, "lost": -6}


def hearing_profile(settings):
    """{band_key: state} from settings, ignoring anything unrecognised."""
    raw = (settings or {}).get("hearing", {}) or {}
    valid = {k for k, _lo, _hi, _l, _d in HEARING_BANDS}
    return {k: v for k, v in raw.items()
            if k in valid and v in HEARING_STATES}


def hearing_active(profile):
    """True once the user has told us anything at all. Until then the program
    behaves exactly as it did before — no marks, no caps, no extra boxes."""
    return bool(profile) and any(v != "ok" for v in profile.values())


def hearing_state_for_hz(hz, profile):
    """The state covering a frequency, or '' when we have no opinion."""
    if not profile or not hz:
        return ""
    for key, lo, hi, _label, _desc in HEARING_BANDS:
        if lo <= hz < hi:
            return profile.get(key, "")
    return ""


def hearing_mark(hz, profile):
    """(glyph, colour, tooltip) for a band row, or None when nothing to say."""
    st = hearing_state_for_hz(hz, profile)
    if not st or st == "ok":
        return None
    glyph, colour, short, meaning = HEARING_STATES[st]
    return glyph, colour, f"{short} at this frequency — {meaning}"


def hearing_cap_db(hz, db, profile):
    """Clamp a suggested gain to what is safe to set without hearing it.
    Returns (capped_db, reason) — reason is '' when nothing was changed."""
    st = hearing_state_for_hz(hz, profile)
    if not st or st == "ok" or db is None:
        return db, ""
    if db > 0:
        cap = HEARING_BOOST_CAP.get(st)
        if cap is not None and db > cap:
            return cap, (f"capped at +{cap} dB — you cannot hear this range well "
                         f"enough to judge a bigger boost, and a boost you cannot "
                         f"hear is harshness for everyone else")
    elif db < 0:
        cap = HEARING_CUT_CAP.get(st)
        if cap is not None and db < cap:
            return cap, (f"capped at {cap} dB — a deeper cut here is a decision "
                         f"you cannot check by ear")
    return db, ""


def hearing_decide(band, profile):
    """A 'TRY / depends on the track' band inside a range you cannot judge is not
    a useful question. Pick the value and say so.
    Returns (decided_db, sentence) or (None, '')."""
    if band.get("type") != "char":
        return None, ""
    hz = _parse_hz_midpoint(band.get("hz", ""))
    st = hearing_state_for_hz(hz, profile)
    if st not in ("weak", "lost"):
        return None, ""
    # The card's own centre value is the program's best guess; the cap then keeps
    # it inside what is safe to set without being able to check it.
    db, _why = hearing_cap_db(hz, band.get("db", 0), profile)
    word = "cannot judge" if st == "lost" else "are unsure about"
    return db, (f"DECIDED: {('+' if db > 0 else '')}{db} dB. This band asks you to "
                f"choose by ear, and it sits in a range you {word} — so the program "
                f"picks, and you leave it alone.")


# Your own plug-ins that reach a decision by ANALYSING the audio instead of by
# asking you to listen. For a hearing-impaired mixer these are not conveniences,
# they are the most reliable tools in the whole rack.
HEARING_TRUSTED_TOOLS = [
    ("smart:EQ 4", "Measures the actual masking between tracks in a group and "
                   "resolves it. It is doing the job your ear cannot do in the "
                   "4–16 kHz range. Run Learn on every group."),
    ("smart:comp", "Sets its own ratio/attack/release from the audio. The level "
                   "problems you cannot hear (a vocal dropping between phrases) "
                   "are exactly what it fixes."),
    ("Bandwidth",  "You pick a preset rather than dialling a curve — a decision "
                   "made from the plug-in's analysis, not from your monitoring."),
    ("Lowtility 2", "A pure number: corner frequency and slope. Nothing to judge "
                    "by ear at all — this program prints the value."),
    ("Kirchhoff-EQ", "Every value comes from this program as an exact number. "
                     "Type it in; do not sweep for it."),
    ("smart:reverb 2", "Distance/Size/Width as numbers per depth tier, so 'how "
                       "far back' stops being a listening test."),
    ("Ozone / Elevate", "Master-bus analysis with a loudness target. Trust the "
                        "LUFS number, not how loud it feels."),
]

# The rules that follow from a profile. Each: (heading, [lines]).
def hearing_rules(profile):
    """Build the personal rule list from the profile. Ranges the user marked
    weak/lost drive most of it, so the text is never generic."""
    lost = [b for b in HEARING_BANDS if profile.get(b[0]) == "lost"]
    weak = [b for b in HEARING_BANDS if profile.get(b[0]) == "weak"]
    ok   = [b for b in HEARING_BANDS if profile.get(b[0]) == "ok"]
    out = []

    if lost or weak:
        lines = []
        if lost:
            names = ", ".join(b[3] for b in lost)
            lines.append(f"You cannot judge: {names}. In those bands the number on "
                         f"the card is the answer. Type it, then move on — do not "
                         f"sweep, do not A/B, do not 'just a bit more'.")
        if weak:
            names = ", ".join(b[3] for b in weak)
            lines.append(f"You are unsure about: {names}. Set the printed number "
                         f"first, then allow yourself ±2 dB — no more.")
        if ok:
            names = ", ".join(b[3] for b in ok)
            lines.append(f"You hear these well: {names}. This is where your ear "
                         f"beats any preset — spend your listening time here and "
                         f"stop worrying about the rest.")
        out.append(("Where your ear counts, and where it does not", lines))

    out.append(("The one trap to know about", [
        "The classic hearing-loss mixing error is turning a band up until YOU can "
        "hear it. If your loss at 8 kHz is 20 dB, then 'now I can hear the "
        "cymbals' means you have added roughly 20 dB of cymbals for everybody "
        "else. It will sound thin, brittle and fatiguing to them while sounding "
        "correct to you.",
        "That is why this program CAPS boosts in the ranges you marked: +2 dB in "
        "a range you cannot judge, +4 dB in one you are unsure about. If the part "
        "still feels missing after the cap, the answer is almost never more EQ — "
        "it is level, compression, or removing something that is masking it.",
        "The mirror-image trap: cutting a band you cannot hear until 'it sounds "
        "clean'. You can gut the air of a whole mix that way. Cuts are capped too.",
    ]))

    out.append(("Decide by number, not by listening", [
        "High-pass corners and slopes — the Lowtility values on every card.",
        "Reverb depth — the Distance/Size/Width numbers per tier, not 'how far "
        "back does that feel'.",
        "Compressor gain reduction — watch the meter hit 3–6 dB. Do not judge "
        "compression by ear in a range you cannot hear.",
        "Loudness — a LUFS number on the master, always. 'Loud enough' is not a "
        "judgement you can make reliably, and neither can anyone with normal "
        "hearing after twenty minutes.",
        "Stereo width and mono compatibility — a correlation meter, not your ears. "
        "Flip to mono and watch what drops; masking is worse in mono and it shows "
        "up on a meter before it shows up in a room.",
    ]))

    out.append(("Let the plug-ins do the listening", [
        f"{name} — {why}" for name, why in HEARING_TRUSTED_TOOLS
    ]))

    out.append(("Monitoring rules that matter more for you than for anyone else", [
        "Pick ONE monitoring level and never change it while mixing. Your balance "
        "decisions shift with level far more than a normal ear's do, so a "
        "consistent level is worth more than an expensive speaker.",
        "Mix quieter than feels natural. At low level the ear flattens out and "
        "you are forced to fix balance instead of tone.",
        "Reference tracks are your best instrument: load a song you know is mixed "
        "well, match ITS spectrum on an analyser, and trust the picture over the "
        "sound. This is the single most effective technique available to you.",
        "If you use any hearing correction to monitor, it must sit on the MONITOR "
        "path only — never on the master, never printed. And every decision it "
        "changes has to be checked against the printed number, because your mix "
        "will otherwise carry the exact inverse of your correction curve.",
        "Take breaks on a timer, not on a feeling. Fatigue in a damaged ear "
        "arrives earlier and is harder to notice.",
        "Check every mix on three systems (phone speaker, car, headphones). If it "
        "translates on all three, the ranges you cannot hear are fine.",
    ]))
    return out


# *************** DEL 02g - PLUGIN LIBRARY ***********************************
# A personal, GROW-OVER-TIME library of the plugins you own / want to try. It
# lets the program: (a) REMIND you what you have (you forget the names), (b) show
# the INSERT-CHAIN ORDER they sit in (the "inserts map" in the Channel Plan), and
# (c) SUGGEST trying one when a need is detected. It never guesses exact numbers —
# only RANGES, with what "good" vs "too much" sounds like, so you can dial by ear.
#
# status (you set it; disliked ones are excluded from suggestions / the map):
#   favorite ♥ · like 👍 · untested · · dislike 👎 · core ⚙ (a tool the program
#   itself already drives — Lowtility / Kirchhoff / smart:EQ / Trackspacer / …).
# scope = how widely it sits in a mix → the inserts-map notation YOU asked for:
#   "all"  → shown plain     e.g.  Lowtility        (on (almost) every channel)
#   "many" → shown as (Name)  e.g. (smart:EQ)        (many but not all channels)
#   "few"  → shown as ((Name)) e.g.((Trackspacer))   (only the odd channel)
# kind = a human category; 'chain' = where it sits in the channel strip (smaller =
#   earlier). The inserts map is sorted by chain. Sends (delay/reverb) sit last;
#   mastering tools sit on the master and are shown separately.

PLUGIN_SCOPE_WRAP = {"all": ("", ""), "many": ("(", ")"), "few": ("((", "))")}
PLUGIN_SCOPE_NEXT = {"all": "many", "many": "few", "few": "all"}
PLUGIN_SCOPE_LABEL = {"all": "all channels", "many": "many channels",
                      "few": "few channels"}

# Status → (glyph, colour, label). 'core' is reserved for the program's own tools.
PLUGIN_STATUS = {
    "favorite": ("♥", "#ff9ec4", "Favourite"),
    "like":     ("👍", C_BOOST,  "Like"),
    "untested": ("·",  C_FG_DIM, "Untested"),
    "dislike":  ("👎", C_CUT,    "Dislike"),
    "core":     ("⚙",  C_ACCENT, "Core tool"),
}
# The statuses a normal (non-core) plugin cycles through when you tag it.
PLUGIN_STATUS_PICK = ["favorite", "like", "untested", "dislike"]

# Human categories (used in the Add/Edit dialog dropdown).
PLUGIN_KINDS = [
    "EQ", "Low cut", "Gate", "Saturation", "Exciter", "Comp", "Dynamics",
    "Duck", "Sub", "Transient", "Chorus", "Mod", "Width", "Pitch", "Vocal",
    "Delay", "Reverb", "Amp", "Bass", "Drums", "Synth", "Multi", "Bundle",
    "Scale", "Tool", "Limiter", "Clipper", "Loudness",
]

# kind → default chain position (top of the channel strip = small number).
PLUGIN_KIND_CHAIN = {
    "Scale": 1, "Tool": 2, "Synth": 3, "Amp": 6, "Pitch": 8,
    "Low cut": 10, "Gate": 14, "Vocal": 18, "EQ": 20, "Bass": 22,
    "Drums": 23, "Saturation": 26, "Exciter": 27, "Multi": 28, "Bundle": 28,
    "Comp": 34, "Dynamics": 34, "Transient": 36, "Duck": 40, "Sub": 42,
    "Chorus": 44, "Mod": 45, "Width": 50, "Delay": 55, "Reverb": 60,
    "Limiter": 90, "Clipper": 90, "Loudness": 90,
}
# Kinds that live on the master / a bus, not a normal channel insert.
PLUGIN_MASTER_KINDS = {"Limiter", "Clipper", "Loudness"}
# Kinds that are normally a SEND (aux), shown at the end of the chain.
PLUGIN_SEND_KINDS = {"Delay", "Reverb"}


def plugin_chain(p):
    """Numeric channel-strip position for ordering the inserts map."""
    if isinstance(p.get("chain"), (int, float)):
        return p["chain"]
    return PLUGIN_KIND_CHAIN.get(p.get("kind", ""), 50)


def plugin_wrapped_name(p):
    """The display name with the scope notation: Name / (Name) / ((Name))."""
    lo, hi = PLUGIN_SCOPE_WRAP.get(p.get("scope", "many"), ("", ""))
    return f"{lo}{p.get('name', '?')}{hi}"


# Per-KIND generic guidance — RANGES only, never exact. 'try' = the move, 'good' =
# what you should NOTICE if it is helping, 'too_much' = the over-cooked warning.
PLUGIN_KIND_TIP = {
    "Delay": {"try": "a short slap or 1/8–1/4-note delay, ~10–25% wet, maybe ping-pong",
              "good": "more depth, width and movement while the dry note stays clear",
              "too_much": "the part smears, the timing blurs, or it washes into mud"},
    "Reverb": {"try": "a small room/plate send, ~10–20% wet, with 20–80 ms pre-delay on leads",
               "good": "the part sits in a space and glues, words/notes still crisp",
               "too_much": "it drifts far back, lyrics blur, the low end gets cloudy"},
    "Chorus": {"try": "a gentle stereo chorus/widener, depth low, ~15–30% mix",
               "good": "a wider, richer, lightly shimmering part",
               "too_much": "seasick warble, a hollow/phasey centre, lost mono punch"},
    "Saturation": {"try": "a touch of drive/warmth, just a few % to start",
                   "good": "more presence and 'glue', the part cuts a bit better",
                   "too_much": "fizz/harshness, lost dynamics, an obviously distorted tone"},
    "Exciter": {"try": "a small high-band excite above ~5 kHz, very low amount",
                "good": "air and sparkle without raising a static EQ shelf",
                "too_much": "harsh, brittle, fatiguing top end"},
    "Width": {"try": "widen the SIDES a little (keep the lows mono)",
              "good": "a bigger stereo image with a solid centre",
              "too_much": "a hollow centre, phase issues, collapse in mono"},
    "Pitch": {"try": "light correction / a subtle detuned double",
              "good": "tighter tuning or a fuller, wider part",
              "too_much": "robotic artefacts, warble, an unnatural tone"},
    "Comp": {"try": "gentle levelling, just a few dB of gain reduction",
             "good": "a steadier, more present part that sits in the mix",
             "too_much": "pumping, squashed life, raised noise/room"},
    "Gate": {"try": "a gate/expander to clean bleed between hits",
             "good": "tighter, cleaner hits with less spill",
             "too_much": "chopped tails, missed soft hits, an unnatural stop-start"},
    "Transient": {"try": "a small attack/sustain nudge",
                  "good": "more punch or a tighter tail, to taste",
                  "too_much": "clicky, unnatural, or a lifeless flat hit"},
}


# ── VERDICTS: "I own this but I don't understand it — should I use it?" ───────
# Program-authored guidance, NOT user data: it lives here and is looked up at
# display time, so it is never written into plugins.json and never goes stale
# behind your own edits. Keyed by the plugin name in _SEED_ROWS.
#   rank: "use"   → a real gap in your chain, start with this one
#         "maybe" → useful, but only for a specific job
#         "skip"  → you already own something that does this; adding it is noise
#         "ask"   → I could not verify what this plug-in actually does
PLUGIN_VERDICT_STYLE = {
    "use":   ("★ START USING", C_BOOST),
    "maybe": ("○ worth a try",  "#ffcf8f"),
    "skip":  ("— skip",         C_FG_DIM),
    "ask":   ("? tell me",      C_ACCENT),
}

PLUGIN_VERDICT = {
    # --- The one real hole in your chain: per-channel dynamics ---
    "Smart Comp": ("use",
        "This is the biggest gap you have. You run NO compressor on individual "
        "channels — only auto-mastering on the master. smart:comp is the exact "
        "counterpart to smart:EQ: it analyses the track and sets itself, so you "
        "get the levelling without having to hear ratio/attack/release. Put it on "
        "the LEAD VOCAL and the BASS first, aim for 3–4 dB of gain reduction, and "
        "your vocal stops disappearing between phrases. That is a level problem, "
        "and no amount of EQ or reverb fixes a level problem."),
    "Learn Comp": ("maybe",
        "Same job as smart:comp. Pick ONE of the two and learn that one — owning "
        "both just means neither gets used."),

    # --- Saturation: you have the loud end, not the gentle end ---
    "Colour": ("use",
        "You own Diablo, which is the aggressive end of saturation. You own "
        "nothing for the gentle end. A light saturator on the BASS bus and the "
        "background beds adds harmonics that make a part audible on small "
        "speakers without raising its level — which is exactly what you need when "
        "the mix is already full. A few percent. If you can clearly hear it, it "
        "is too much."),

    # --- Space: your actual complaint ---
    "Synchron Stage Reverb": ("use",
        "Your 'Cascadia is not spacious enough' problem. Cascadia is a delay-based "
        "space tool, not a room — a delay can never give you a big hall, so no "
        "setting of it will. This is a convolution reverb built from a real "
        "concert hall, which is the most direct way to get actual size. Use it on "
        "the FAR bus (the Hall tier) and keep smart:reverb for Near/Mid."),
    "Crystalline": ("maybe",
        "The other route to size: a big algorithmic reverb with long, clean tails. "
        "Try it on the FAR bus if you prefer 'lush and modern' over 'real hall'. "
        "Pick one of this and Synchron Stage — not both."),
    "Neoverb": ("maybe",
        "It does not feel spacious because its assistant aims for a tasteful, "
        "controlled ambience. For size you have to push SIZE and PRE-DELAY "
        "yourself, on a 100%-wet send bus. If it still falls short, that is the "
        "plug-in's character, not your settings — use a hall/convolution instead."),

    # --- Things you already cover; adding them only adds decisions ---
    "Sub Ninja": ("skip",
        "SubMass already does this, and the program generates SubMass presets for "
        "your kick and basses. Two sub generators on one low end fight each other."),
    "Loudbody": ("skip",
        "Master-bus loudness. You already finish with Ozone. Stacking a second "
        "loudness tool costs you dynamics and gains nothing."),
    "Uberloud": ("skip",
        "Same as Loudbody — you already have a master chain. One loudness stage, "
        "at the end, is the whole rule."),
    "Smart Limit": ("skip",
        "Only if it REPLACES Ozone's maximizer. Two limiters in series is how a "
        "mix gets flat."),
    "Learn Limit": ("skip", "Same as Smart Limit — one limiter, on the master, at the end."),
    "SweetEQ": ("maybe",
        "Use its BUILT-IN presets and nothing else. Its knobs are proprietary "
        "macros with no published behaviour, so no recipe — mine or anyone's — can "
        "be trusted. Audition the factory presets and pick by ear."),
    "Pluto": ("maybe",
        "You keep forgetting it because it has no fixed place in your chain. Give "
        "it one: decide it is for ONE job (say, widening the background beds), "
        "write that here in its note, and it will stop disappearing."),
    "Flexion": ("maybe",
        "A synth, not a mix tool — it belongs at writing time, not mixing time. "
        "That is why it feels like you 'forget' it."),

    "Cascadia": ("maybe",
        "Keep it — but for what it IS: rhythmic echo and movement, not size. When "
        "you want the part further BACK, that is a reverb send and a Distance "
        "value, not a delay. Using Cascadia for depth is why space keeps feeling "
        "out of reach."),

    # --- Honest unknowns. I will not invent behaviour for a plug-in. ---
    "Magic Ride": ("ask",
        "I could not verify what this does, and I will not guess at a plug-in you "
        "would then put on your mix. Open it, tell me the main controls, and I "
        "will write a real entry."),
    "Prism": ("ask",
        "Same — unverified. Tell me what its main controls are and I will give you "
        "a proper verdict instead of a plausible-sounding guess."),
    "Pure Level": ("ask",
        "If this rides the level automatically (like a vocal rider), it is worth a "
        "lot to you — an automatic rider on the lead vocal solves 'the vocal "
        "disappears' more cleanly than compression does. But I could not verify "
        "the product, so confirm what it does first."),
    "Pure Lever": ("ask",
        "sonible's pure: series are one-knob versions of their smart: tools. I "
        "could not verify this one's exact name or job, so I will not guess. Open "
        "it, tell me what the main control is called, and I will write a proper "
        "entry."),
}


# ── ★ FOCUS: the plug-ins you are actually working with right now ────────────
# A big library is a library you never read. The FOCUS set is pinned to the top
# of the 🧩 Plugins tab, starred in the list and starred in the insert map, so
# the eight tools you are learning stay in front of the fifty you own. Click ★
# on any row to add or remove one; the set is saved in settings['focus_plugins']
# and the default below is only used the first time.
FOCUS_DEFAULT = [
    "Lowtility 2",
    "Kirchhoff-EQ",
    "Bandwidth",
    "SubMass",
    "Diablo",
    "Cascadia",
    "smart:EQ 4",
    "Trackspacer",
]

# Names you might type/remember for a plug-in vs the name it has in the library.
# Lets the focus list survive a spelling that is not the vendor's.
FOCUS_ALIASES = {
    "kirchenhof eq": "Kirchhoff-EQ",
    "kirchhoff eq": "Kirchhoff-EQ",
    "kirchhoff": "Kirchhoff-EQ",
    "trackspace": "Trackspacer",
    "smarteq": "smart:EQ 4",
    "smart:eq": "smart:EQ 4",
    "smart eq": "smart:EQ 4",
    "submass": "SubMass",
    "cymatics diablo": "Diablo",
    "bandwidth (in the mix)": "Bandwidth",
    "lowtility": "Lowtility 2",
    "smart:reverb": "smart:reverb 2",
    # The delay is iZotope "Cascadia" — checked against Cubase's own plug-in
    # report, which lists Cascadia 1.1.0 and no "Cascade" at all. This entry
    # used to point the other way (2026-09-13), so a focus list saved before
    # then still says "Cascade" and has to land on the real name.
    "cascade": "Cascadia",
}

# One line on WHY each focus tool is in the chain and where it sits — printed in
# the pinned box so the list is a reminder, not just eight names.
FOCUS_JOB = {
    "Lowtility 2":  "FIRST insert. One number: the high-pass corner + slope from the card. Nothing to judge by ear.",
    "Kirchhoff-EQ": "The main EQ. Every value on every card is written for it — and the program generates the presets.",
    "Bandwidth":    "On most sounds. You choose one of ITS presets; the analysis is the plug-in's job, not yours.",
    "SubMass":      "Only kick and basses. A tracked sub layer, glued mono — weight you can measure rather than hear.",
    "Diablo":       "The aggressive end of saturation. A few percent goes a long way; if it is obvious, it is too much.",
    "Cascadia":     "A SEND, at the end of the chain. Rhythmic echo and movement — not size: a delay cannot be a hall, so depth comes from a reverb send instead.",
    "smart:EQ 4":   "The group/unmasking slot on a BUS. It measures the masking your ears cannot — run Learn on every group.",
    "Trackspacer":  "Only on channels that must yield (bass under kick, everything under the vocal). Start gentle.",
}


def focus_canonical(name):
    """Map a typed/remembered name onto the library's own spelling."""
    n = (name or "").strip()
    return FOCUS_ALIASES.get(n.lower(), n)


def plugin_is_focus(p, focus_names):
    """True when this plugin is in the current ★ focus set (case-insensitive)."""
    have = {focus_canonical(x).strip().lower() for x in (focus_names or [])}
    return p.get("name", "").strip().lower() in have


def plugin_verdict(p):
    """(rank, style_label, colour, text) for a plugin, or None if we have no
    opinion on it. Looked up by name — never stored in plugins.json."""
    v = PLUGIN_VERDICT.get(p.get("name", ""))
    if not v:
        return None
    rank, text = v
    label, colour = PLUGIN_VERDICT_STYLE.get(rank, PLUGIN_VERDICT_STYLE["maybe"])
    return rank, label, colour, text


def _normalize_plugin(p):
    """Fill in any missing keys on a plugin dict (tolerant of old/partial data)."""
    q = dict(p)
    q.setdefault("name", "Unnamed")
    q.setdefault("vendor", "")
    q.setdefault("kind", "Multi")
    q.setdefault("status", "untested")
    q.setdefault("scope", "many")
    q.setdefault("url", "")
    q.setdefault("note", "")
    q.setdefault("builtin", False)
    q.setdefault("bus", "insert")    # "insert" (channel) | "master" (master bus)
    if q["status"] not in PLUGIN_STATUS:
        q["status"] = "untested"
    if q["scope"] not in PLUGIN_SCOPE_WRAP:
        q["scope"] = "many"
    return q


# ── Seed library (the user's own list — owned faves, mastering tools, and the big
#    "want to test" list with links). Tuples: (name, vendor, kind, status, scope,
#    url, note). Merged into plugins.json on load; the user's edits always win. ──
_SEED_ROWS = [
    # --- CORE tools the program already drives (the inserts map backbone) ---
    ("Lowtility 2", "Venomode", "Low cut", "core", "all",
     "https://www.venomode.com/products/lowtility", "The high-pass the program generates — FIRST in the chain."),
    ("Kirchhoff-EQ", "Three-Body Tech / Plugin Alliance", "EQ", "core", "all",
     "", "The main parametric EQ the program generates presets for."),
    ("smart:EQ 4", "sonible", "EQ", "core", "many",
     "https://www.sonible.com/smarteq", "Group unmasking — add it manually and run Learn; the program gives the Front/Mid/Back ranking."),
    ("Trackspacer", "Wavesfactory", "Duck", "core", "few",
     "https://www.wavesfactory.com/audio-plugins/trackspacer/", "The reactive-EQ ducker — only on channels that must yield."),
    ("Kickstart 2", "Cableguys", "Duck", "core", "few",
     "https://www.cableguys.com/kickstart", "Tempo-synced volume duck — only for an on-beat kick."),
    ("smart:reverb 2", "sonible", "Reverb", "core", "many",
     "https://www.sonible.com/smartreverb", "Depth/character — the program patches Distance/Size/Width into your seed."),
    ("SubMass", "DSPTone", "Sub", "core", "few",
     "", "Tracked sub-harmonic 'feel' generator + mono-below-X on the low end — the program patches Amp/Freq/Center into your seed (kick, bass, low toms)."),

    # --- Often-used FAVOURITES you forget the name of ---
    ("Flexion", "", "Synth", "favorite", "few",
     "", "An often-used synth you keep forgetting the name of."),
    ("Diablo", "Cymatics", "Saturation", "favorite", "few",
     "https://cymatics.fm/products/diablo", "Distortion/heat you reach for."),
    ("Multiply", "Acon Digital", "Chorus", "favorite", "many",
     "https://acondigital.com/products/multiply/", "Your go-to chorus/widener ('Digital Multiply')."),
    ("Neoverb", "iZotope", "Reverb", "like", "many",
     "https://www.izotope.com/en/products/neoverb.html", "Used now and then — often while hunting for Flexion/Cascadia."),
    ("SweetEQ", "Musik Hack", "EQ", "like", "many",
     "https://musikhack.com/products/sweet-eq", "Use its BUILT-IN presets — the program does NOT generate SweetEQ presets."),
    ("Telos Guitars", "Telos", "Amp", "like", "few",
     "https://telosmusic.com", "Guitar tone you sometimes use."),
    ("Bandwidth", "In The Mix", "Multi", "favorite", "all",
     "https://www.inthemix.audio", "On most sounds. You pick one of ITS presets — you never build a patch in it."),
    ("Cascadia", "iZotope", "Delay", "favorite", "many",
     "https://www.izotope.com", "Delay-based space. Read its verdict: a delay cannot be a hall."),
    ("Ozone", "iZotope", "Loudness", "favorite", "few",
     "https://www.izotope.com/en/products/ozone.html", "Your master chain. Master only, always last."),

    # --- Owned but not understood (your own words) — see PLUGIN_VERDICT ---
    ("Magic Ride", "MBM Audio", "Multi", "untested", "few", "", ""),
    ("Prism", "Aurally Sound", "Multi", "untested", "few", "", ""),
    ("Pure Level", "sonible", "Dynamics", "untested", "many", "", ""),

    # --- MASTERING (master channel only; auto/learning tools) ---
    ("Elevate Bundle", "Newfangled Audio", "Limiter", "like", "few",
     "https://www.newfangledaudio.com/elevate", "Auto-mastering on the MASTER only."),
    ("Learn Limit", "", "Limiter", "like", "few",
     "", "Auto-mastering limiter — master only."),
    ("Smart Limit", "sonible", "Limiter", "like", "few",
     "https://www.sonible.com/smartlimit", "Auto-mastering limiter — master only."),
    ("Loudbody", "", "Loudness", "like", "few",
     "", "Loudness/body on the master."),
    ("Learn Comp", "", "Comp", "like", "few",
     "", "Auto-mastering comp — master only."),
    ("Smart Comp", "sonible", "Comp", "like", "few",
     "https://www.sonible.com/smartcomp", "Auto-mastering comp — master only."),

    # --- UNTESTED / want-to-try (your big list, with links) ---
    ("Smart Gate", "sonible", "Gate", "untested", "many", "https://www.sonible.com/smartgate", ""),
    ("ShaperBox", "Cableguys", "Multi", "untested", "many", "https://www.cableguys.com/shaperbox", ""),
    ("Mixing Complete Bundle", "Drumforge", "Bundle", "untested", "many", "https://drumforge.com/products/drumforge-mixing-pro-bundle", ""),
    ("AI-Rack", "Techivation", "Multi", "untested", "many", "https://techivation.com/ai-rack/", ""),
    ("M-Exciter", "Techivation", "Exciter", "untested", "many", "https://techivation.com/m-exciter/", ""),
    ("Uberloud", "", "Loudness", "untested", "few", "https://www.uberloud.com", ""),
    ("FX Suite", "LANDR", "Multi", "untested", "many", "https://www.landr.com/plugins/", ""),
    ("Neutron 5", "iZotope", "Multi", "untested", "many", "https://www.izotope.com/en/products/neutron.html", "You master with LANDR or Ozone 12 instead."),
    ("Sub Ninja", "", "Bass", "untested", "few", "https://www.subninjas.com", ""),
    ("Pure Lever", "sonible", "Comp", "untested", "many", "https://www.sonible.com/purelever", ""),
    ("Alkane", "Kalifornia Dynamic", "Saturation", "untested", "many", "https://www.kaliforniadynamic.com", ""),
    ("Telos Bass", "Telos", "Bass", "untested", "few", "https://telosmusic.com", ""),
    ("SpectralBalance", "Accentize", "EQ", "untested", "many", "https://www.accentize.com/spectralbalance", ""),
    ("élastique Pitch 2", "zplane", "Pitch", "untested", "few", "https://products.zplane.de/elastique-pitch-2", ""),
    ("Graillon", "Auburn Sounds", "Vocal", "untested", "few", "https://www.auburnsounds.com/products/Graillon.html", ""),
    ("Invigorate", "Newfangled Audio", "Saturation", "untested", "many", "https://www.newfangledaudio.com/invigorate", ""),
    ("Chakra", "Styx", "Multi", "untested", "many", "", "Brand/spelling unconfirmed — tell me more about it."),
    ("Kclipper", "Kazrog", "Clipper", "untested", "few", "https://kazrog.com/products/kclipper", ""),
    ("Pluto", "Cymatics", "Multi", "untested", "many", "https://cymatics.fm/products/pluto", ""),
    ("WaveBalance", "Codwaves", "EQ", "untested", "many", "https://codwaves.com/wavebalance/", ""),
    ("Silencer", "Wide Blue Sound", "Gate", "untested", "few", "https://www.widebluesound.com/silencer", ""),
    ("Kick Ninja", "", "Drums", "untested", "few", "https://www.kickninja.app", ""),
    ("Colour", "HOFA", "Saturation", "untested", "many", "https://hofa-plugins.de/plugins/colour/", "HOFA Colour saturation."),
    ("SnappySnap", "Electric Smudge", "Transient", "untested", "few", "https://electricsmudge.com/", ""),
    # Reverb
    ("Crystalline", "Baby Audio", "Reverb", "untested", "many", "https://babyaud.io/crystalline", ""),
    ("Space", "Cymatics", "Reverb", "untested", "many", "https://cymatics.fm/products/space", ""),
    ("Synchron Stage Reverb", "VSL", "Reverb", "untested", "many", "https://www.vsl.co.at/synchron-plugins/synchron-stage-reverb", ""),
    ("Vela", "Sonic Academy", "Reverb", "untested", "many", "https://www.sonicacademy.com/products/vela", ""),
    # Saturation / Scale / misc
    ("Puffer Fish", "sonible", "Saturation", "untested", "many", "https://www.sonible.com/pufferfish", ""),
    ("Scaler 2", "Plugin Boutique", "Scale", "untested", "few", "https://www.pluginboutique.com/product/3-Studio-Tools/72-Scale-Detection/6409-Scaler-2", "Scale/chord detection helper."),
    ("All Access", "Minimal Audio", "Bundle", "untested", "many", "https://www.minimalaudio.com", ""),
    ("Effects Bundle", "Minimal Audio", "Multi", "untested", "many", "https://www.minimalaudio.com", ""),
    # Drums
    ("Drum Production Suite", "Acon Digital", "Drums", "untested", "many", "https://acondigital.com/products/", ""),
    ("Telos Drums", "Telos", "Drums", "untested", "many", "https://telosmusic.com", ""),
    ("Croquesolid", "Tourage DSP", "Drums", "untested", "few", "https://touragedsp.com", ""),
    ("Drum Replacer", "UVI", "Drums", "untested", "few", "https://www.uvi.net/drum-replacer", ""),
    ("Atlas", "Modern Music Solutions", "Drums", "untested", "few", "https://www.modernmusicsolutions.com/atlas", ""),
    # Guitar
    ("Amplifikation 360", "Kuassa", "Amp", "untested", "few", "https://www.kuassa.com/products/amplifikation-360/", ""),
    ("Phantomix", "Muramasa / United Plugins", "Multi", "untested", "few", "https://unitedplugins.com/Phantomix/", ""),
    ("SansAmp Rack", "Audiopunks", "Amp", "untested", "few", "https://audiopunks.com", ""),
    ("TH-U Premium", "Overloud", "Amp", "untested", "few", "https://www.overloud.com/products/th-u", ""),
    ("Ampbox", "Mercuriall", "Amp", "untested", "few", "https://mercuriall.com/cms/details_ampbox", ""),
    # Vocal
    ("Auto-Tune Unlimited", "Antares", "Vocal", "untested", "few", "https://www.antarestech.com/products/auto-tune/auto-tune-unlimited", ""),
    ("Re-esser", "Wavesfactory", "Vocal", "untested", "many", "https://www.wavesfactory.com/audio-plugins/re-esser/", "De-esser."),
    ("UltraVox", "Leapwing Audio", "Vocal", "untested", "few", "https://www.leapwingaudio.com/products/ultravox", ""),
    ("Vocal FX Collection", "AIR", "Vocal", "untested", "few", "https://www.airmusictech.com/product/vocal-bundle", ""),
    ("VocalSynth 2", "iZotope", "Vocal", "untested", "few", "https://www.izotope.com/en/products/vocal-synth.html", ""),
    ("Voxity", "Cymatics", "Vocal", "untested", "few", "https://cymatics.fm/products/voxity", ""),
    ("Voxcraft", "UJAM", "Vocal", "untested", "few", "https://www.ujam.com/voxcraft", ""),
    ("Xvox", "Nuro Audio", "Vocal", "untested", "few", "https://nuro.audio/xvox", ""),
    ("Telos Vocals", "Telos", "Vocal", "untested", "few", "https://telosmusic.com", ""),
    ("VEA", "iZotope", "Vocal", "untested", "many", "https://www.izotope.com/en/products/vea.html", "Vocal EQ assistant."),
    ("Velvet", "iZotope", "Vocal", "untested", "few", "https://www.izotope.com/en/products/velvet.html", ""),
    ("Vocride", "Nclear", "Vocal", "untested", "many", "https://nclear.com", "Vocal rider (auto level)."),
    ("Mantra", "Neural DSP", "Vocal", "untested", "few", "https://neuraldsp.com/plugins/mantra", ""),
    ("Vovious", "DoublePi", "Vocal", "untested", "few", "", "Search KVR — link unconfirmed."),
    ("Aurora", "iZotope", "Reverb", "untested", "many", "https://www.izotope.com/en/products/aurora.html", ""),
    ("XRider", "Nuro Audio", "Multi", "untested", "many", "https://nuro.audio/xrider", "Auto-rider."),
    ("Aguilar Plugin Suite", "Aguilar", "Amp", "untested", "few", "", "Bass amps — confirm it's the plugin suite."),
]


# These specific seed tools live on the MASTER bus (auto-mastering comps/limiters)
# even though their kind alone wouldn't force it.
_SEED_BUS_MASTER = {"Elevate Bundle", "Learn Limit", "Smart Limit", "Loudbody",
                    "Learn Comp", "Smart Comp"}


def _seed_plugins():
    """Build the seed plugin list (every entry marked builtin=True)."""
    out = []
    for name, vendor, kind, status, scope, url, note in _SEED_ROWS:
        out.append(_normalize_plugin({
            "name": name, "vendor": vendor, "kind": kind, "status": status,
            "scope": scope, "url": url, "note": note, "builtin": True,
            "bus": "master" if name in _SEED_BUS_MASTER else "insert"}))
    return out


def _plugins_path():
    return os.path.join(get_helpfiles_dir("eq_cheatsheet"), "plugins.json")


# ── One-time library corrections ────────────────────────────────────────────
# A plug-in that turned out to be the SAME product under a name that was never
# real. Left in a saved plugins.json it stays forever (user data always wins over
# the seed list), showing one plug-in twice — once properly categorised and once
# as an empty "Multi" with no chain position. {wrong name: right name}.
PLUGIN_RENAMES = {
    # iZotope's delay really is called "Cascadia" — Cubase's plug-in report
    # lists Cascadia 1.1.0 and no "Cascade". Until 2026-09-13 this mapping
    # ran the other way and rewrote the real name into a made-up one, so a
    # plugins.json saved before then needs folding back.
    "cascade": "Cascadia",
}


def _merge_renamed_plugins(saved):
    """Fold any renamed entry into its real one. Returns (plugins, changed).
    If the real entry is already there the duplicate is dropped, but anything the
    user actually typed (a note, a 👎) is carried across rather than lost."""
    out, changed = [], False
    by_name = {p.get("name", "").strip().lower(): p for p in saved}
    for p in saved:
        target = PLUGIN_RENAMES.get(p.get("name", "").strip().lower())
        if not target:
            out.append(p)
            continue
        changed = True
        real = by_name.get(target.strip().lower())
        if real is None:
            # The real entry is missing — rename in place and keep the user's tags.
            p["name"] = target
            out.append(p)
        else:
            # Duplicate: drop it, but do not lose anything the user wrote.
            if p.get("note") and not real.get("note"):
                real["note"] = p["note"]
            if p.get("status") == "dislike":
                real["status"] = "dislike"
    return out, changed


def load_plugins():
    """Load plugins.json, merging in any NEW seed entries (the user's saved status
    and edits always win for entries that already exist, matched by name)."""
    saved = []
    try:
        with open(_plugins_path(), "r", encoding="utf-8") as f:
            saved = json.load(f).get("plugins", [])
    except Exception:
        saved = []
    saved = [_normalize_plugin(p) for p in saved]
    saved, renamed = _merge_renamed_plugins(saved)
    have = {p["name"].strip().lower() for p in saved}
    added = False
    for seed in _seed_plugins():
        if seed["name"].strip().lower() not in have:
            saved.append(seed)
            added = True
    if added or renamed or not os.path.isfile(_plugins_path()):
        save_plugins(saved)
    return saved


def save_plugins(plugins):
    try:
        os.makedirs(os.path.dirname(_plugins_path()), exist_ok=True)
        with open(_plugins_path(), "w", encoding="utf-8") as f:
            json.dump({"plugins": plugins}, f, indent=2, ensure_ascii=False)
    except Exception:
        pass


# *************** EQ CURVE HELPERS ********************************************

import math
import re as _re
import shutil      # the open-with block needs this at module level

_FREQ_MIN = 20.0
_FREQ_MAX = 20000.0


def _freq_to_x(hz, width):
    """Map a frequency (Hz) to an x pixel position using log scale."""
    return (math.log10(hz / _FREQ_MIN) / math.log10(_FREQ_MAX / _FREQ_MIN)) * width


def _parse_hz_midpoint(hz_str):
    """
    Extract a representative Hz value from strings like '60–80 Hz', '< 200 Hz',
    '10+ kHz', '2–5 kHz', '700 Hz–1 kHz', etc.
    Returns float Hz or None on failure.
    """
    s = hz_str.strip()
    # Normalise: replace en-dash and remove + (means 'and above')
    s = s.replace("\u2013", "-").replace("\u2014", "-").replace("+", "")

    def _parse_single(token):
        t = token.strip().lstrip("<>").strip()
        if not t:
            return None
        mult = 1000.0 if "k" in t.lower() else 1.0
        t = (t.replace("kHz", "").replace("khz", "")
              .replace("Hz", "").replace("hz", "")
              .replace("k", "").strip())
        try:
            return float(t) * mult
        except ValueError:
            return None

    s_clean = s.strip().lstrip("<>").strip()
    m = _re.match(
        r'^([0-9.]+\s*(?:kHz|khz|Hz|hz|k)?)\s*-\s*([0-9.]+\s*(?:kHz|khz|Hz|hz|k)?)$',
        s_clean
    )
    if m:
        g1, g2 = m.group(1), m.group(2)
        a = _parse_single(g1)
        b = _parse_single(g2)
        # If the first number has no unit but the second is in kHz, the first
        # shares the kHz scale: '3-5 kHz' means 3 kHz to 5 kHz, NOT 3 Hz to 5 kHz.
        def _has_unit(t):
            tl = t.lower()
            return ("hz" in tl) or ("k" in tl)
        if a is not None and b is not None and not _has_unit(g1) and ("k" in g2.lower()):
            a *= 1000.0
        if a and b:
            return (a + b) / 2
        return a or b
    return _parse_single(s_clean)


def _draw_eq_curve_on(canvas, bands, width, height, bg=None):
    """
    Draw an EQ frequency-response curve on a tk.Canvas.
    Each band contributes a Gaussian bump/dip.  Grid lines + freq labels included.
    """
    if bg is None:
        bg = C_BG2
    canvas.delete("all")
    canvas.configure(bg=bg)

    if width < 2 or height < 2:
        return

    # Grid lines + freq labels
    grid_freqs = [
        (20, "20"), (50, "50"), (100, "100"), (200, "200"), (500, "500"),
        (1000, "1k"), (2000, "2k"), (5000, "5k"), (10000, "10k"), (20000, "20k"),
    ]
    label_h = 14
    plot_h  = height - label_h
    for f, lbl in grid_freqs:
        x = _freq_to_x(f, width)
        canvas.create_line(x, 0, x, plot_h, fill="#1e2a45", width=1)
        canvas.create_text(x, plot_h + 7, text=lbl,
                           fill="#4a5a7a", font=("Consolas", 6), anchor="center")

    cy = plot_h / 2
    canvas.create_line(0, cy, width, cy, fill="#2a3a5a", width=1, dash=(4, 4))

    MAX_DB = 20.0
    sigma  = 1.0 * math.log10(2)   # 1 octave width
    N      = max(2, int(width))

    db_curve = [0.0] * N
    for band in bands:
        hz = _parse_hz_midpoint(band["hz"])
        if not hz or hz <= 0:
            continue
        hz = max(_FREQ_MIN, min(_FREQ_MAX, hz))
        db = band.get("db", 0)
        if db == 0:
            continue
        log_c = math.log10(hz)
        for i in range(N):
            f = _FREQ_MIN * ((_FREQ_MAX / _FREQ_MIN) ** (i / (N - 1)))
            db_curve[i] += db * math.exp(-0.5 * ((math.log10(f) - log_c) / sigma) ** 2)

    pts = []
    for i in range(N):
        db = max(-MAX_DB, min(MAX_DB, db_curve[i]))
        pts.append((i, cy - (db / MAX_DB) * cy * 0.85))

    if len(pts) >= 2:
        fill_pts = list(pts) + [(pts[-1][0], cy), (pts[0][0], cy)]
        canvas.create_polygon(fill_pts, fill="#1e3a2a", outline="", smooth=True)
        flat = [coord for p in pts for coord in p]
        canvas.create_line(flat, fill=C_BOOST, width=1, smooth=True)

    for band in bands:
        hz = _parse_hz_midpoint(band["hz"])
        if not hz or hz <= 0:
            continue
        hz  = max(_FREQ_MIN, min(_FREQ_MAX, hz))
        db  = band.get("db", 0)
        if db == 0:
            continue
        col = TYPE_COLOR.get(band.get("type", "neutral"), C_NEUTRAL)
        x   = _freq_to_x(hz, width)
        y   = cy - (max(-MAX_DB, min(MAX_DB, db)) / MAX_DB) * cy * 0.85
        canvas.create_oval(x - 3, y - 3, x + 3, y + 3, fill=col, outline="")


def _draw_combined_curve(canvas, bands, width, height, bg=None):
    """
    Draw a summed EQ curve from multiple instruments' bands (overview view).
    Thicker line, same grid as _draw_eq_curve_on.
    """
    if bg is None:
        bg = C_BG2
    canvas.delete("all")
    canvas.configure(bg=bg)

    if width < 2 or height < 2:
        return

    grid_freqs = [
        (20, "20"), (50, "50"), (100, "100"), (200, "200"), (500, "500"),
        (1000, "1k"), (2000, "2k"), (5000, "5k"), (10000, "10k"), (20000, "20k"),
    ]
    label_h = 14
    plot_h  = height - label_h
    for f, lbl in grid_freqs:
        x = _freq_to_x(f, width)
        canvas.create_line(x, 0, x, plot_h, fill="#1e2a45", width=1)
        canvas.create_text(x, plot_h + 7, text=lbl,
                           fill="#4a5a7a", font=("Consolas", 6), anchor="center")

    cy = plot_h / 2
    canvas.create_line(0, cy, width, cy, fill="#2a3a5a", width=1, dash=(4, 4))

    MAX_DB = 20.0
    sigma  = 1.0 * math.log10(2)
    N      = max(2, int(width))

    db_curve = [0.0] * N
    for band in bands:
        hz = _parse_hz_midpoint(band["hz"])
        if not hz or hz <= 0:
            continue
        hz = max(_FREQ_MIN, min(_FREQ_MAX, hz))
        db = band.get("db", 0)
        if db == 0:
            continue
        log_c = math.log10(hz)
        for i in range(N):
            f = _FREQ_MIN * ((_FREQ_MAX / _FREQ_MIN) ** (i / (N - 1)))
            db_curve[i] += db * math.exp(-0.5 * ((math.log10(f) - log_c) / sigma) ** 2)

    pts = []
    for i in range(N):
        db = max(-MAX_DB, min(MAX_DB, db_curve[i]))
        pts.append((i, cy - (db / MAX_DB) * cy * 0.85))

    if len(pts) >= 2:
        fill_pts = list(pts) + [(pts[-1][0], cy), (pts[0][0], cy)]
        canvas.create_polygon(fill_pts, fill="#1a3025", outline="", smooth=True)
        flat = [coord for p in pts for coord in p]
        canvas.create_line(flat, fill=C_BOOST, width=2, smooth=True)

    for band in bands:
        hz = _parse_hz_midpoint(band["hz"])
        if not hz or hz <= 0:
            continue
        hz  = max(_FREQ_MIN, min(_FREQ_MAX, hz))
        db  = band.get("db", 0)
        if db == 0:
            continue
        col = TYPE_COLOR.get(band.get("type", "neutral"), C_NEUTRAL)
        x   = _freq_to_x(hz, width)
        y   = cy - (max(-MAX_DB, min(MAX_DB, db)) / MAX_DB) * cy * 0.85
        canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill=col, outline="")


# *************** DEL 02c - KIRCHHOFF EQ (PARAMETRIC Q) MAPPING ***************
# Kirchhoff-EQ V1.7.1 (Three-Body Technology) exposes, per band, FIVE controls:
#       Type/Shape  ·  Frequency  ·  Gain  ·  Q  ·  Slope
# The instrument data above stores a frequency *range* and a generic filter name
# (good for SmartEQ-style "draw a region" workflows).  This section converts each
# band into the EXACT single-value parameters you actually dial into a Kirchhoff
# band, so the default "Parametric Q" engine can print precise numbers instead of
# ranges.
#
# SONG CONTEXT (do not miss this!):  these are BASELINE values for the instrument
# heard on its own.  In a real mix they shift — another instrument may force you
# to move a frequency, narrow a Q, or pull a few dB out.  Those mix-dependent
# changes are shown live in the right-hand "Selected Instruments" panel and in the
# "Song Variants" tab; the numbers below are only the starting point.

KIRCHHOFF_VERSION = "1.7.1"

# Kirchhoff "Type" names (the dropdown of filter shapes) we map our data onto.
KTYPE_HPASS  = "High Pass"
KTYPE_HSHELF = "High Shelf"
KTYPE_BELL   = "Bell"
KTYPE_FLAT   = "Flat-Top"   # a Bell with raised Slope -> flat plateau, not a peak

# Short tags for the narrow right-hand summary panel.
KTYPE_SHORT = {KTYPE_HPASS: "HPF", KTYPE_HSHELF: "Shelf",
               KTYPE_BELL: "Bell", KTYPE_FLAT: "Flat"}

# Words in a band's note/label that mean a cut should be surgical/narrow (high Q).
_KIRCH_SURGICAL = ("mud", "box", "boom", "boxy", "honk", "nasal", "sibilance",
                   "hum", "rumble", "harsh", "woolly", "wooden", "congest",
                   "scratch", "rosin", "hiss", "bleed", "blare", "resonan")

# Shape-decision thresholds (in octaves of band width). Tweak to taste:
_KIRCH_FLATTOP_OCT = 1.5   # a boost/cut at least this WIDE -> Flat-Top plateau
_KIRCH_WIDE_OCT    = 0.8   # a boost wider than this uses a low (wide) Q

# A plain Bell shows this in the Slope column. In Kirchhoff a Bell's slope ranges
# 12→96 dB/oct, so 12 IS the bell minimum / default — leave it there and shape the
# band with Q. (6 dB/oct does NOT exist for bells; it does for shelves. Raise the
# slope, or switch to the Sword type, only to dig a resonance out harder.)
KSLOPE_DEFAULT = "12 dB/oct"

# ---- .keq slope NORMALISED values (0..1) used when writing Kirchhoff presets ----
# Reverse-engineered from hand-made presets: Bell=0.0 (its 12 dB/oct minimum),
# High Shelf≈0.1667, Flat-Top≈0.725, and High Pass mapped from the cheat-sheet
# dB/oct label (anchored to real presets: kick 12 dB/oct≈0.50, etc.). Editable.
KEQ_HPF_SLOPE_NORM = {"12 dB/oct": 0.50, "18 dB/oct": 0.54, "24 dB/oct": 0.58}
KEQ_SHELF_SLOPE_NORM = 0.16666666666666666
KEQ_FLATTOP_SLOPE_NORM = 0.725


def _kirch_round_freq(hz):
    """Round a raw Hz value to a clean, dial-able number."""
    if hz < 100:    return int(round(hz / 5.0) * 5)
    if hz < 1000:   return int(round(hz / 10.0) * 10)
    if hz < 10000:  return int(round(hz / 100.0) * 100)
    return int(round(hz / 500.0) * 500)


def _kirch_fmt_freq(hz):
    """Format a Hz value the way Kirchhoff's frequency readout shows it."""
    hz = _kirch_round_freq(hz)
    if hz >= 1000:
        v = hz / 1000.0
        return f"{v:.0f} kHz" if abs(v - round(v)) < 0.05 else f"{v:.1f} kHz"
    return f"{hz} Hz"


def _parse_hz_lo_hi(hz_str):
    """Return (lo_hz, hi_hz) for a band's range string so we can estimate how
    WIDE the band is (in octaves). Single-bound strings like '< 200 Hz' return a
    narrow span; open-ended '10+ kHz' is treated as reaching toward 20 kHz."""
    s = hz_str.strip().replace("–", "-").replace("—", "-")
    plus = "+" in s
    s = s.replace("+", "")
    s_clean = s.strip().lstrip("<>").strip()

    def _one(tok):
        t = tok.strip().lstrip("<>").strip()
        mult = 1000.0 if "k" in t.lower() else 1.0
        for u in ("kHz", "khz", "Hz", "hz", "k"):
            t = t.replace(u, "")
        t = t.strip()
        try:
            return float(t) * mult
        except ValueError:
            return None

    m = _re.match(
        r'^([0-9.]+\s*(?:kHz|khz|Hz|hz|k)?)\s*-\s*([0-9.]+\s*(?:kHz|khz|Hz|hz|k)?)$',
        s_clean)
    if m:
        a, b = _one(m.group(1)), _one(m.group(2))
        # '3-5 kHz' means 3 kHz..5 kHz, not 3 Hz..5 kHz
        if (a and b and ("k" in m.group(2).lower())
                and ("hz" not in m.group(1).lower()) and ("k" not in m.group(1).lower())):
            a *= 1000.0
        if a and b:
            return (min(a, b), max(a, b))

    mid = _parse_hz_midpoint(hz_str)
    if mid and plus:
        return (mid, _FREQ_MAX)            # open-ended "+": wide toward the top
    return (mid, mid) if mid else (None, None)


def _kirch_octaves(hz_str):
    """Width of a band's range, in octaves (0 if unknown / single point)."""
    lo, hi = _parse_hz_lo_hi(hz_str)
    if not lo or not hi or lo <= 0 or hi <= 0 or hi <= lo:
        return 0.0
    return math.log(hi / lo, 2)


def _band_cur_db(b):
    """The representative dB of a band (mid-point for TRY bands). None if no band."""
    if b is None:
        return None
    if (b.get("type") == "char" and b.get("db_lo") is not None
            and b.get("db_hi") is not None):
        return (b["db_lo"] + b["db_hi"]) / 2.0
    return b.get("db", 0)


def kirchhoff_band(band):
    """Convert one instrument band into exact Kirchhoff-EQ V1.7.1 parameters.

    Returns a dict: {ktype, freq, gain, q, slope, shape_note}.
      ktype      — the Kirchhoff Type/Shape to select (Bell / Flat-Top / High Shelf / High Pass)
      freq       — exact centre/corner frequency to type in
      gain       — gain in dB ("—" for pass filters, which have no gain)
      q          — exact Q value ("—" for pass filters where slope rules instead)
      slope      — dB/oct for High Pass (0–96), shelves (6–96) and Bell (12–96, so the
                   '12 dB/oct' shown is the bell minimum/default); "—" for a Flat-Top
                   (it's its own fixed-shape type — set its width with Q)
      shape_note — one line on HOW to shape it in Kirchhoff (which knob is 'the shape')
    """
    ftype = band.get("filter", "Parametric EQ")
    btype = band.get("type", "neutral")
    note  = (str(band.get("note", "")) + " " + str(band.get("label", ""))).lower()
    db    = band.get("db", 0)

    hz = _parse_hz_midpoint(band.get("hz", "")) or 1000.0
    freq  = _kirch_fmt_freq(hz)
    width = _kirch_octaves(band.get("hz", ""))   # band width in octaves
    # A mix edit can move the centre frequency (e.g. bass body 60→90 Hz).
    if band.get("_eff_freq"):
        freq = _kirch_fmt_freq(band["_eff_freq"])

    # Gain string (Bell / Flat-Top / Shelf carry gain; Pass filters overwrite "—").
    if (btype == "char" and band.get("db_lo") is not None
            and band.get("db_hi") is not None):
        lo, hi = band["db_lo"], band["db_hi"]
        gain = f"{lo:+d}…{hi:+d} dB"
    else:
        gain = f"{db:+d} dB" if db else "0 dB"

    if ftype == "High-pass":
        # SLOPE varies here — it IS the shape. Steeper = removes more, faster.
        ktype = KTYPE_HPASS
        gain  = "—"                            # a pass filter has no gain
        q     = "0.71"                         # Butterworth corner (no resonance)
        depth = db if db < 0 else -12
        if depth <= -18:   slope = "24 dB/oct"
        elif depth <= -12: slope = "18 dB/oct"
        else:              slope = "12 dB/oct"
        shape_note = ("Slope IS the shape here — Kirchhoff goes 0→96 dB/oct. "
                      "12 = gentle, 24 = tight, 48+ ≈ surgical (or use the Brickwall type).")
    elif ftype == "High-shelf":
        # SLOPE varies by purpose: gentle/broad for 'air', steeper for tonal shelves.
        ktype = KTYPE_HSHELF
        q     = "0.71"
        if hz >= 8000:
            slope = "6 dB/oct"
            shape_note = ("Air shelf — gentle slope (≈6 dB/oct) + low Q for a broad, "
                          "silky lift; raise the slope if you want it to grip lower.")
        else:
            slope = "12 dB/oct"
            if db >= 0:
                shape_note = ("Shelf ≈12 dB/oct — raise Q for a small resonant bump at "
                              "the corner, lower it for a flat lift.")
            else:
                shape_note = "Shelf cut ≈12 dB/oct — gently rolls the very top off."
    else:  # "Parametric EQ" -> Bell or Flat-Top, depending on width & job
        surgical = any(k in note for k in _KIRCH_SURGICAL)
        if btype == "boost":
            if width >= _KIRCH_FLATTOP_OCT:
                ktype, qv, slope = KTYPE_FLAT, 0.6, "—"
                shape_note = ("Wide lift → pick the FLAT-TOP type (its own type) for an even "
                              "plateau across the whole region; set the width with Q (low ≈ wide).")
            elif width >= _KIRCH_WIDE_OCT:
                ktype, qv, slope = KTYPE_BELL, 1.0, KSLOPE_DEFAULT
                shape_note = "Bell — boost WIDE (Q≈1) for a musical, natural lift."
            else:
                ktype, qv, slope = KTYPE_BELL, 1.6, KSLOPE_DEFAULT
                shape_note = "Bell — focused boost (Q≈1.6) for presence / character."
        elif btype == "cut":
            if surgical or width < 0.6:
                ktype, qv, slope = KTYPE_BELL, 4.0, KSLOPE_DEFAULT
                shape_note = ("Bell — cut NARROW (high Q) to remove a resonance / mud / "
                              "boxiness; switch to the SWORD type to dig out a stubborn one.")
            elif width >= _KIRCH_FLATTOP_OCT:
                ktype, qv, slope = KTYPE_FLAT, 0.7, "—"
                shape_note = ("Broad scoop → pick the FLAT-TOP type to pull a whole region "
                              "down evenly; set the width with Q.")
            else:
                ktype, qv, slope = KTYPE_BELL, 2.0, KSLOPE_DEFAULT
                shape_note = "Bell — moderate Q (≈2) for general tone shaping."
        else:  # char / TRY
            ktype, qv, slope = KTYPE_BELL, 1.2, KSLOPE_DEFAULT
            shape_note = "Bell — sweep to taste; moderate Q (≈1.2); try boost AND cut."
        q = f"{qv:.1f}"

    # ---- numeric values for .keq preset generation ----
    freq_hz_eff = band.get("_eff_freq") or hz
    gain_db_num = None if ktype == KTYPE_HPASS else _band_cur_db(band)
    try:
        q_num = float(q)
    except Exception:
        q_num = 1.0
    if ktype == KTYPE_BELL:
        slope_norm = 0.0
    elif ktype == KTYPE_HSHELF:
        slope_norm = KEQ_SHELF_SLOPE_NORM
    elif ktype == KTYPE_FLAT:
        slope_norm = KEQ_FLATTOP_SLOPE_NORM
    else:  # High Pass
        slope_norm = KEQ_HPF_SLOPE_NORM.get(slope, 0.5)

    return {"ktype": ktype, "freq": freq, "gain": gain,
            "q": q, "slope": slope, "shape_note": shape_note,
            "freq_hz": freq_hz_eff, "gain_db": gain_db_num,
            "q_val": q_num, "slope_norm": slope_norm}


# *************** DEL 02e - KIRCHHOFF .keq PRESET WRITER **********************
# A Kirchhoff-EQ ".keq" file is plain JSON of NORMALISED (0..1) string values:
#   19 global keys + 32 bands × 32 fields each (incl. dynamic-EQ fields).
# 'band_list_order' lists the ACTIVE band indices (0-based).
# Mappings (reverse-engineered & verified against hand-made presets):
#   Freq : 10 * 3000**norm        (10 Hz .. 30 kHz, log)  ← verified (not 20–20k!)
#   Gain : (norm-0.5) * 60        (±30 dB, 0.5 = 0 dB)
#   Q    : 0.025 * 1600**norm     (0.025 .. 40, log)
#   Type : discrete raw strings (High Pass / Bell / High Shelf / Flat-Top below)
#   Slope: per-type norm (see KEQ_*_SLOPE_NORM above)
#   Stereo Placement: 0.0 = Stereo (Mid/Side codes are a best-guess; opt-in)

# Discrete Type values Kirchhoff stores (index/71); harvested verbatim.
KEQ_TYPE_RAW = {
    KTYPE_HPASS:  "0.014084507042253522",   # 1/71  High Pass
    KTYPE_BELL:   "0.04225352112676056",    # 3/71  Bell
    KTYPE_HSHELF: "0.07042253521126761",    # 5/71  High Shelf
    KTYPE_FLAT:   "0.1267605633802817",     # 9/71  Flat Top
}

# Stereo Placement codes (opt-in M/S), index/5. FULLY VERIFIED in Kirchhoff:
#   0.0 = Stereo (L/R) · 0.2 = Mid/Side · 0.4 = Left · 0.6 = Right · 0.8 = Mid · 1.0 = Side
KEQ_SP = {"stereo": 0.0, "midside": 0.2, "left": 0.4, "right": 0.6, "mid": 0.8, "side": 1.0}

# Only these (genuinely wide / stereo) sources get an air band routed to Side.
# A mono/centre source (kick, bass, lead vocal, solo lead) has ~no Side signal.
# NOTE: flute_bg / violin_bg are NOT here, bed or not. They are ONE player
# holding a note - there is no Side signal to put an air band into. Layer two
# of them (MULTI_ADVICE says to) and the width comes from the panning, not here.
KEQ_WIDE_IDS = {"cymbals", "percussion", "vocals_backing", "vocals_choir_pad",
                "vocals_extra",
                "organ", "accordion", "piano_bg", "piano_riff", "synth_pad",
                "synth_pluck", "synth_mallet", "brass", "horn_section",
                "guitar_acoustic", "string_section"}


def _keq_norm_freq(hz):
    # Kirchhoff's frequency range is 10 Hz .. 30 kHz (log) — VERIFIED: writing this
    # makes the plugin display the same round Hz the cheat sheet shows (the old
    # 20 Hz..20 kHz guess shifted every frequency, e.g. 11 kHz showed as 15 kHz).
    hz = max(10.0, min(30000.0, float(hz)))
    return min(1.0, max(0.0, math.log(hz / 10.0) / math.log(3000.0)))


def _keq_norm_gain(db):
    return min(1.0, max(0.0, float(db) / 60.0 + 0.5))


def _keq_norm_q(q):
    q = max(0.025, min(40.0, float(q)))
    return min(1.0, max(0.0, math.log(q / 0.025) / math.log(40.0 / 0.025)))


# Global defaults (exact, from a known-good hand-made preset; band_list_order/Pan
# get overwritten per build).
KEQ_GLOBAL = {
    "Bypass": "0.0", "Invert Phase": "0.0", "Master Vol.": "0.5", "Gain Scale": "0.75",
    "Enable Auto Gain": "0.0", "Pan": "0.5", "Phase Mode": "0.0",
    "Mix Phase Crossover Freq.": "0.6", "Linear Phase Precision": "0.0",
    "Enable DoubleDouble": "0.0", "Enable Lookahead": "0.0", "Lookahead": "0.0",
    "Width": "0.5", "Upsample Factor": "0.0", "Side Vol.": "0.5",
    "ABIsA": True, "panel_eq_range_db": "1.200000000e+01", "show_keyboard": False,
    "band_list_order": [],
}

# One band's full field set, in 'unused' state (exact, from a real preset).
KEQ_BAND_DEFAULT = {
    "Used": "0.0", "Enabled": "0.0", "Type": "0.04225352112676056", "Slope": "0.0",
    "Freq.": "0.3707130260769751", "Gain": "0.5", "Q": "0.5", "Stereo Placement": "0.0",
    "Speakers Type": "0.0", "Pan/Width": "0.5", "Dyn. On": "0.0",
    "Dyn. Threshold": "0.5833333333333334", "Dyn. Below Ratio": "0.3499999940395355",
    "Dyn. Below Range": "0.5", "Dyn. Above Ratio": "0.3499999940395355",
    "Dyn. Above Range": "0.5", "Dyn. Attack": "0.39860408906973529",
    "Dyn. Release": "0.4362831806885292", "Dyn. Onsets Mix": "0.10000000149011612",
    "Dyn. Rela. Mix": "0.8899999856948853", "Dyn. Det. Use SideChain": "0.0",
    "Dyn. Rela. Use SideChain": "0.0", "Det. Free Mode On": "0.0",
    "Dyn. Det. Freq.": "0.5751884543241926", "Dyn. Det. Q": "0.5",
    "Rela. Free Mode On": "0.0", "Dyn. Rela. Freq.": "0.5751884543241926",
    "Dyn. Rela. Q": "0.5", "Dyn. Above On": "1.0", "Dyn. Below On": "1.0",
    "Dyn. Det. Ch. Type": "0.0", "Dyn. Rela. Ch. Type": "0.0",
}


def build_keq_dict(band_params, pan_norm=0.5):
    """Build a full 32-band Kirchhoff preset dict from a list of band params:
    each = {ktype, freq_hz, gain_db (None for pass), q_val, slope_norm, sp_norm}."""
    d = dict(KEQ_GLOBAL)
    n = len(band_params)
    for i in range(1, 33):
        bd = dict(KEQ_BAND_DEFAULT)
        if i <= n:
            p = band_params[i - 1]
            gdb = p.get("gain_db")
            bd["Used"] = "1.0"
            bd["Enabled"] = "1.0"
            bd["Type"] = KEQ_TYPE_RAW.get(p["ktype"], KEQ_TYPE_RAW[KTYPE_BELL])
            bd["Slope"] = repr(float(p.get("slope_norm", 0.0)))
            bd["Freq."] = repr(_keq_norm_freq(_kirch_round_freq(p["freq_hz"])))
            bd["Gain"] = repr(_keq_norm_gain(gdb if gdb is not None else 0.0))
            bd["Q"] = repr(_keq_norm_q(p.get("q_val", 1.0)))
            bd["Stereo Placement"] = repr(float(p.get("sp_norm", 0.0)))
        for k, v in bd.items():
            d[f"Band{i} {k}"] = v
    d["band_list_order"] = [str(j) for j in range(n)]
    d["Pan"] = repr(float(pan_norm))
    return d


def write_keq(path, d):
    """Write a Kirchhoff preset dict to disk as indented JSON (.keq)."""
    with open(path, "w", encoding="utf-8") as f:
        json.dump(d, f, indent=4, ensure_ascii=False)


def keq_bytes(d):
    """The bytes write_keq() puts on disk (same JSON, same line ends), so a .keq can
    go through write_preset_file() like every other preset."""
    return json.dumps(d, indent=4, ensure_ascii=False).replace("\n", os.linesep).encode("utf-8")


# *************** DEL 02s - PRESET FILE NAMES WITHOUT A DATE, BACKUPS ON REPLACE ***
# His call (2026-10-31): a preset used to be called '2026-06---Cello---Lowcut'. The
# month moved with every generation, so every chain that pointed at the old name went
# MISSING (342 slots in one FxChainChecker scan). The name is now only what the preset
# IS - 'Cello---Lowcut' - and when a newer version is written over it the songs simply
# get the slightly updated preset, which is what he wants. Whatever is replaced is first
# renamed to '<file>.<YYYY-MM-DD_HHMMSS>.bak' beside it: plug-ins and Cubase list presets
# by extension, so a .bak never shows up in a preset list, and nothing is ever lost.
_LEGACY_PREFIX_RE = _re.compile(r"^(?:0|\d{4}-\d\d)---")

# Names this program makes. Used to keep them out of the 'which file do I take as the
# container / seed' choice: a hand-saved preset is the one proven to load.
_GENERATED_NAME_RE = _re.compile(
    r"^(?:0|\d{4}-\d\d)---"                       # legacy: 0---X and 2026-06---X
    r"|---(?:Solo|Lowcut|Chain)(?:__\d\d)?$"      # Kirchhoff / Lowtility / PatchWork
    r"|---Group---"                               # Kirchhoff group presets
    r"|---SubMass_Amp\d"                          # SubMass
    r"|---Knock[12]_"                             # KNOCK 1 / KNOCK 2 (DEL 02e3)
    r"|^(?:Corridor|Omega)---"                    # Corridor / Omega
    r"|^[123]---.+---D\d+---(?:Centre|[LR]\d+)$",  # Virtual Stage (DEL 02t)
    _re.I)


def strip_legacy_prefix(name):
    """'2026-06---Cello---Lowcut' or '0---Cello---Lowcut' -> 'Cello---Lowcut'."""
    return _LEGACY_PREFIX_RE.sub("", name or "", count=1)


def is_generated_name(fname):
    """True for a file name this program makes (extension ignored)."""
    return bool(_GENERATED_NAME_RE.search(os.path.splitext(os.path.basename(fname or ""))[0]))


def write_preset_file(path, data):
    """Write `data` (bytes) to `path`. Returns (state, backup_path):
         ("new", "")      nothing was there
         ("same", "")     an identical file is already there - left untouched
         ("replaced", p)  a different file was there; it is now `p`
                          ('<file>.<YYYY-MM-DD_HHMMSS>.bak', beside it)
    The new bytes go to '<file>.tmp' first, so an interrupted write never leaves half a
    preset, and if the swap fails the old file is put back."""
    bak = ""
    if os.path.exists(path):
        try:
            with open(path, "rb") as f:
                if f.read() == data:
                    return "same", ""
        except OSError:
            pass
    tmp = path + ".tmp"
    with open(tmp, "wb") as f:
        f.write(data)
    try:
        if os.path.exists(path):
            stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
            bak, n = f"{path}.{stamp}.bak", 2
            while os.path.exists(bak):
                bak, n = f"{path}.{stamp}_{n}.bak", n + 1
            os.replace(path, bak)
        os.replace(tmp, path)
    except Exception:
        if bak and os.path.exists(bak) and not os.path.exists(path):
            try:
                os.replace(bak, path)           # put the old one back
            except OSError:
                pass
        try:
            os.remove(tmp)
        except OSError:
            pass
        raise
    return ("replaced", bak) if bak else ("new", "")


# ---- Kirchhoff .vstpreset (VST3 wrapper around the .keq JSON) ---------------
# A Plugin-Alliance / Cubase Kirchhoff ".vstpreset" is a VST3 container whose
# Comp chunk is a JUCE VstW/CcnK/FBCh wrapper holding the .keq JSON VERBATIM,
# followed by a fixed ~61-byte JUCE trailer. CUBASE's own preset browser reads
# these; the plain .keq files only show in Kirchhoff's INTERNAL browser. So to
# put presets where Cubase looks, we wrap our .keq JSON using a TEMPLATE taken
# from an existing .vstpreset the user already has. Verified: rebuilding a
# template from its own JSON is byte-identical, so only the JSON content changes.

def _kirchhoff_vst3_split(template):
    """From a Kirchhoff .vstpreset, return (classid, comp_prefix, trailer, info)
    — the fixed parts reused to wrap a new .keq JSON — or None if unparseable."""
    try:
        listoff = struct.unpack("<q", template[40:48])[0]
        p = listoff + 8
        ent = {}
        for _ in range(struct.unpack("<i", template[listoff + 4:listoff + 8])[0]):
            cid = template[p:p + 4]
            off = struct.unpack("<q", template[p + 4:p + 12])[0]
            sz = struct.unpack("<q", template[p + 12:p + 20])[0]
            ent[cid] = (off, sz)
            p += 20
        comp_off, comp_sz = ent[b"Comp"]
        comp = template[comp_off:comp_off + comp_sz]
        cs_off = comp.find(b"FBCh") + 4 * 5 + 128
        fxb_chunksize = struct.unpack(">i", comp[cs_off:cs_off + 4])[0]
        json_start = cs_off + 4
        payload = comp[json_start:json_start + fxb_chunksize]
        s = payload.decode("utf-8")
        jend = json.JSONDecoder().raw_decode(s)[1]      # char index after the JSON
        trailer = payload[len(s[:jend].encode("utf-8")):]
        info = template[ent[b"Info"][0]:ent[b"Info"][0] + ent[b"Info"][1]]
        return template[8:40], comp[:json_start], trailer, info
    except Exception:
        return None


def keq_json_to_vstpreset(json_bytes, template):
    """Wrap .keq JSON bytes into a Kirchhoff .vstpreset using a template preset.
    Returns the .vstpreset bytes, or None if the template can't be parsed."""
    parts = _kirchhoff_vst3_split(template)
    if not parts:
        return None
    classid, comp_prefix, trailer, info = parts
    comp_prefix = bytearray(comp_prefix)
    payload = json_bytes + trailer
    cs_off = comp_prefix.find(b"FBCh") + 4 * 5 + 128
    struct.pack_into(">i", comp_prefix, cs_off, len(payload))    # FBCh chunkSize (BE)
    comp = bytearray(bytes(comp_prefix) + payload)
    struct.pack_into(">i", comp, 20, len(comp) - 24)            # CcnK byteSize (BE)
    comp = bytes(comp)
    comp_sz, info_sz = len(comp), len(info)
    listoff = 48 + comp_sz + info_sz
    hdr = b"VST3" + struct.pack("<i", 1) + classid + struct.pack("<q", listoff)
    lst = b"List" + struct.pack("<i", 3)
    lst += b"Comp" + struct.pack("<q", 48) + struct.pack("<q", comp_sz)
    lst += b"Cont" + struct.pack("<q", 48 + comp_sz) + struct.pack("<q", 0)
    lst += b"Info" + struct.pack("<q", 48 + comp_sz) + struct.pack("<q", info_sz)
    return hdr + comp + info + lst


# ---- Venomode Lowtility 2 .vstpreset (XML high-pass utility) ----------------
# Lowtility 2's .vstpreset Comp chunk = b"VC2!" + int32-LE(xml_len) + XML + a
# fixed 61-byte JUCE trailer. The XML is <lowtility2 …><PARAM id=… value=…/>…>.
# The LOW-CUT is two params: id="frequencycut" (corner Hz) and id="slope" (an
# INDEX: 0=12, 1=24, 2=36, 3=48 dB/oct — verified: the user's Kick=24→1, Hihat=
# 36→2). We patch only those (and ensure enablecut=1) and rebuild the container.
# Verified: rebuilding a template from its own XML is byte-identical.
LOWTILITY_SLOPE_INDEX = {12: 0, 24: 1, 36: 2, 48: 3}   # dB/oct → Lowtility slope index


def _lowtility_split(template):
    """Return (classid, vc2_header8, xml, trailer, info) or None."""
    try:
        listoff = struct.unpack("<q", template[40:48])[0]
        p = listoff + 8
        ent = {}
        for _ in range(struct.unpack("<i", template[listoff + 4:listoff + 8])[0]):
            cid = template[p:p + 4]
            off = struct.unpack("<q", template[p + 4:p + 12])[0]
            sz = struct.unpack("<q", template[p + 12:p + 20])[0]
            ent[cid] = (off, sz)
            p += 20
        co, cs = ent[b"Comp"]
        comp = template[co:co + cs]
        if comp[:4] != b"VC2!":
            return None
        xml_len = struct.unpack("<i", comp[4:8])[0]
        xml = comp[8:8 + xml_len]
        trailer = comp[8 + xml_len:]
        info = template[ent[b"Info"][0]:ent[b"Info"][0] + ent[b"Info"][1]]
        return template[8:40], comp[:8], xml, trailer, info
    except Exception:
        return None


def make_lowtility_preset(template, hz, slope_db):
    """Return a Lowtility 2 .vstpreset with the low cut set to corner `hz` and the
    slope matching `slope_db` (12/24/36/48). Only frequencycut/slope/enablecut
    change; the width module etc. stay as the template's. None if unparseable."""
    parts = _lowtility_split(template)
    if not parts:
        return None
    classid, vc2, xml, trailer, info = parts
    idx = LOWTILITY_SLOPE_INDEX.get(int(slope_db),
                                    max(0, min(3, round(slope_db / 12) - 1)))

    def setp(pid, val, x):
        pat = (b'(id="' + pid + b'" value=")[^"]*(")')
        new, n = _re.subn(pat, lambda m: m.group(1) + val + m.group(2), x)
        return new if n else x

    xml = setp(b"frequencycut", f"{float(hz):.1f}".encode(), xml)
    xml = setp(b"slope", f"{float(idx):.1f}".encode(), xml)
    xml = setp(b"enablecut", b"1.0", xml)        # make sure the low cut is ON

    vc2 = bytearray(vc2)
    struct.pack_into("<i", vc2, 4, len(xml))
    comp = bytes(vc2) + xml + trailer
    comp_sz, info_sz = len(comp), len(info)
    listoff = 48 + comp_sz + info_sz
    hdr = b"VST3" + struct.pack("<i", 1) + classid + struct.pack("<q", listoff)
    lst = b"List" + struct.pack("<i", 3)
    lst += b"Comp" + struct.pack("<q", 48) + struct.pack("<q", comp_sz)
    lst += b"Cont" + struct.pack("<q", 48 + comp_sz) + struct.pack("<q", 0)
    lst += b"Info" + struct.pack("<q", 48 + comp_sz) + struct.pack("<q", info_sz)
    return hdr + comp + info + lst


# ---- DSPTone SubMass .vstpreset (flat named param stream, JUCE ValueTree) ---
# A SubMass ".vstpreset" is NOT protobuf and NOT XML — its Comp chunk is a
# JUCE ValueTree binary dump: a flat stream of "paramId ... name ... value"
# records, each value an 8-byte little-endian double (0..1 normalised),
# followed by a fixed FxRack/JUCEPrivateData/MetaInfo trailer. Because every
# patched value is a FIXED-SIZE 8-byte double, patching in place changes
# NOTHING else in the file — no length field anywhere needs recalculating
# (same trick as the smart:reverb float patch, simpler still: no protobuf to
# walk, just a text-findable record name before each value).
SUBMASS_PARAM_ID = {"amp": b"MacroParameter_00", "freq": b"MacroParameter_01",
                    "center": b"MacroParameter_02", "level": b"MacroParameter_03",
                    "mono": b"MacroParameter_04"}


def _submass_value_offset(data, param_key):
    """Byte offset of a named SubMass parameter's 8-byte double value, or None."""
    pid = SUBMASS_PARAM_ID.get(param_key)
    if not pid:
        return None
    pat = (rb"paramId\x00\x01.\x05" + _re.escape(pid)
           + rb"\x00name\x00\x01.\x05[A-Za-z]+\x00value\x00\x01\t\x04")
    m = _re.search(pat, data)
    return m.end() if m else None


def make_submass_preset(template, amp=None, freq_hz=None, center_pct=None):
    """Return a SubMass .vstpreset with Amp (0-12), Freq (Hz, 0-350) and/or
    Center (%, 0-150) patched in place into a seed the user already exported
    (e.g. 'Feel a 100'). Any argument left None keeps the seed's own value —
    Level and Mono are always left untouched (no verified mapping yet).
    Raises ValueError if `template` isn't a recognisable SubMass preset."""
    if b'"SubMass"' not in template and b"MacroParameter_00" not in template:
        raise ValueError("not a recognisable SubMass preset")
    data = bytearray(template)
    wants = [("amp", amp, 12.0), ("freq", freq_hz, 350.0), ("center", center_pct, 150.0)]
    patched = False
    for key, val, scale in wants:
        if val is None:
            continue
        off = _submass_value_offset(data, key)
        if off is None:
            continue
        norm = max(0.0, min(1.0, float(val) / scale))
        struct.pack_into("<d", data, off, norm)
        patched = True
    if not patched:
        raise ValueError("no matching SubMass parameters found in template")
    return bytes(data)


def read_submass_values(seed_bytes):
    """Return (amp, freq_hz, center_pct) read back from a SubMass preset (for
    verifying a patch), or None if unparseable."""
    out = {}
    for key, scale in (("amp", 12.0), ("freq", 350.0), ("center", 150.0)):
        off = _submass_value_offset(bytearray(seed_bytes), key)
        if off is None:
            return None
        out[key] = round(struct.unpack_from("<d", seed_bytes, off)[0] * scale, 1)
    return out["amp"], out["freq"], out["center"]


# *************** DEL 02t - VIRTUAL STAGE PRESET WRITER (EVA Instruments) ******
# His call (2026-10-31): "I want to be able to generate Virtual Stage presets too." DEL 02m
# used to say there were none, because every number depends on the rest of the line-up. That
# is still true - so a preset here is NOT a per-instrument constant. It is a snapshot of ONE
# row of stage_plan(), and its NAME says exactly what is in it:
#
#     3---Cello---D46---L10        <room 1|2|3>---<instrument>---D<distance>---<L|R><pct>|Centre
#
# The same numbers always give the same file name and the same bytes, a different line-up
# gives a different name, and nothing is ever overwritten by a different song. (Room digit
# first because his own hand-saved preset is '3---Cello': Small=1, Medium=2, Large=3, and
# the Cubase list then groups by room - one song = one room, DEL 02m rule 1.)
#
# THE FILE (read off his '3---Cello' and four test presets, 2026-10-31). A .vstpreset whose
# Comp chunk is a JUCE VstW/CcnK/FBCh wrapper around a HISE ValueTree dump. Every control is
# a record 'id ... value'; a value is an 8-byte little-endian double (type 04) or an 8-byte
# int64 (type 06). Patching a value in place changes NOTHING else - no length field moves.
#
#   knbVol   DISTANCE x 2          Distance 0..100 -> 0..200. (The knob has half steps, the
#                                  plug-in shows round-half-even(vol / 2): 61 -> 30, 31 -> 16.)
#   knbPan   POSITION + 100        Left 100 % = 0, Centre = 100, Right 100 % = 200.
#   btnDistanceOnly  1.0           Lock Position. ALWAYS on (his call: no reason not to).
#   btnRoomSm / Md / Lg  int64     exactly one of them is 1.
#   cmpImpulses 1, impStore 1, sldIn / sldOut ~1e-6   the same in all five files; kept.
#
# The container is embedded (his '3---Cello.vstpreset', 1626 bytes), so this needs no seed
# file in the folder. Verified: Distance 46, L10, Large rebuilds his file byte for byte.
VSTAGE_VENDOR = "EVA Instruments"
VSTAGE_ROOM_DIGIT = {"Small": 1, "Medium": 2, "Large": 3}
VSTAGE_ROOM_BUTTON = {"Small": b"btnRoomSm", "Medium": b"btnRoomMd",
                      "Large": b"btnRoomLg"}
VSTAGE_TEMPLATE_B64 = (
    "VlNUMwEAAAA1NjUzNTQ1NjczNjY3ODc2Njk3Mjc0NzU2MTZDMjA3MxYGAAAAAAAAVnN0VwAA"
    "AAgAAAABAAAAAENjbksAAAQjRkJDaAAAAAJWc2Z4AAECAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    "AAAAAAAAA4tDb250cm9sRGF0YQABBU1pZGlDaGFubmVsRmlsdGVyRGF0YQABBQEBAAAAUHJv"
    "Z3JhbQABBQEAAAAASG9zdFRlbXBvAAEJBAAAAAAAAPC/VXNlclByZXNldAABAgUAVmVyc2lv"
    "bgABBwUxLjIuMAABA01pZGlBdXRvbWF0aW9uAAAASW50ZXJmYWNlRGF0YQAAAQFDb250ZW50"
    "AAEBUHJvY2Vzc29yAAELBUludGVyZmFjZQABCkNvbnRyb2wAAQN0eXBlAAEOBVNjcmlwdFNs"
    "aWRlcgBpZAABCgVpbXBTdG9yZQB2YWx1ZQABCQQAAAAAAADwPwBDb250cm9sAAEDdHlwZQAB"
    "DgVTY3JpcHRTbGlkZXIAaWQAAQgFa25iUGFuAHZhbHVlAAEJBAAAAAAAgFZAAENvbnRyb2wA"
    "AQN0eXBlAAEOBVNjcmlwdFNsaWRlcgBpZAABCAVrbmJWb2wAdmFsdWUAAQkEAAAAAADAVkAA"
    "Q29udHJvbAABA3R5cGUAARAFU2NyaXB0Q29tYm9Cb3gAaWQAAQ0FY21wSW1wdWxzZXMAdmFs"
    "dWUAAQkEAAAAAAAA8D8AQ29udHJvbAABA3R5cGUAAQ4FU2NyaXB0U2xpZGVyAGlkAAEHBXNs"
    "ZEluAHZhbHVlAAEJBAAAAAAAALk+AENvbnRyb2wAAQN0eXBlAAEOBVNjcmlwdFNsaWRlcgBp"
    "ZAABCAVzbGRPdXQAdmFsdWUAAQkEAAAAAAAAuT4AQ29udHJvbAABA3R5cGUAAQ4FU2NyaXB0"
    "QnV0dG9uAGlkAAERBWJ0bkRpc3RhbmNlT25seQB2YWx1ZQABCQQAAAAAAADwPwBDb250cm9s"
    "AAEDdHlwZQABDQVTY3JpcHRQYW5lbABpZAABCwVidG5Sb29tU20AdmFsdWUAAQkGAAAAAAAA"
    "AAAAQ29udHJvbAABA3R5cGUAAQ0FU2NyaXB0UGFuZWwAaWQAAQsFYnRuUm9vbU1kAHZhbHVl"
    "AAEJBgAAAAAAAAAAAENvbnRyb2wAAQN0eXBlAAENBVNjcmlwdFBhbmVsAGlkAAELBWJ0blJv"
    "b21MZwB2YWx1ZQABCQYBAAAAAAAAAABNUEVEYXRhAAEBRW5hYmxlZAABAQMAAAAAAAAAAABK"
    "VUNFUHJpdmF0ZURhdGEAAQFCeXBhc3MAAQEDAB0AAAAAAAAASlVDRVByaXZhdGVEYXRh77u/"
    "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxNZXRhSW5mbz4NCgk8"
    "QXR0cmlidXRlIGlkPSJNZWRpYVR5cGUiIHZhbHVlPSJWc3RQcmVzZXQiIHR5cGU9InN0cmlu"
    "ZyIgZmxhZ3M9IndyaXRlUHJvdGVjdGVkIi8+DQoJPEF0dHJpYnV0ZSBpZD0iUGx1Z0luQ2F0"
    "ZWdvcnkiIHZhbHVlPSJGeHxSZXZlcmIiIHR5cGU9InN0cmluZyIgZmxhZ3M9IndyaXRlUHJv"
    "dGVjdGVkIi8+DQoJPEF0dHJpYnV0ZSBpZD0iUGx1Z0luTmFtZSIgdmFsdWU9IlZpcnR1YWwg"
    "U3RhZ2UiIHR5cGU9InN0cmluZyIgZmxhZ3M9IndyaXRlUHJvdGVjdGVkIi8+DQoJPEF0dHJp"
    "YnV0ZSBpZD0iUGx1Z0luVmVuZG9yIiB2YWx1ZT0iRVZBIEluc3RydW1lbnRzIiB0eXBlPSJz"
    "dHJpbmciIGZsYWdzPSJ3cml0ZVByb3RlY3RlZCIvPg0KPC9NZXRhSW5mbz4NCkxpc3QDAAAA"
    "Q29tcDAAAAAAAAAAOwQAAAAAAABDb250awQAAAAAAAAAAAAAAAAAAEluZm9rBAAAAAAAAKsB"
    "AAAAAAAA"
)


def _vstage_template():
    return base64.b64decode("".join(VSTAGE_TEMPLATE_B64))


def _vstage_value_offset(data, ident, kind):
    """Offset of the 8 value bytes of control `ident` (kind 4 = double, 6 = int64)."""
    m = _re.search(_re.escape(ident) + b"\x00value\x00\x01\x09" + bytes([kind]), data)
    return m.end() if m else None


def vstage_pos_value(pct):
    """-100..+100 -> the position the SHEET prints (rounded to 5, +-5 = Centre), as an
    int, so a file always says the same as the line on screen."""
    lab = vstage_pos_label(pct)
    if lab == "Centre":
        return 0
    return int(lab[1:]) * (-1 if lab[0] == "L" else 1)


def vstage_pos_tag(pos):
    """0 -> 'Centre', -10 -> 'L10', 45 -> 'R45'."""
    return "Centre" if not pos else ("L%d" % -pos if pos < 0 else "R%d" % pos)


def vstage_preset_name(label, room, dist, pos):
    """'3---Cello---D46---L10' (no extension)."""
    return "%d---%s---D%d---%s" % (VSTAGE_ROOM_DIGIT[room], label, int(dist),
                                   vstage_pos_tag(pos))


def make_vstage_preset(dist, pos, room, raw_vol=None):
    """.vstpreset bytes for Distance `dist` (0-100), Position `pos` (-100..100, + = right),
    `room` (Small|Medium|Large). Lock Position is always ON. `raw_vol` lets a test put in
    the knob value a hand-saved file really holds (an odd number = a half step)."""
    if room not in VSTAGE_ROOM_DIGIT:
        raise ValueError("unknown room %r" % (room,))
    data = bytearray(_vstage_template())
    dist = max(0.0, min(100.0, float(dist)))
    pos = max(-100.0, min(100.0, float(pos)))
    vol = float(raw_vol) if raw_vol is not None else round(dist * 2)
    for ident, val in ((b"knbVol", vol), (b"knbPan", round(pos) + 100),
                       (b"btnDistanceOnly", 1.0)):
        off = _vstage_value_offset(data, ident, 4)
        if off is None:
            raise ValueError("template has no %s" % ident.decode())
        struct.pack_into("<d", data, off, float(val))
    for rm, ident in VSTAGE_ROOM_BUTTON.items():
        off = _vstage_value_offset(data, ident, 6)
        if off is None:
            raise ValueError("template has no %s" % ident.decode())
        struct.pack_into("<q", data, off, 1 if rm == room else 0)
    return bytes(data)


def read_vstage_values(data):
    """(distance, position, room, lock) read back from a Virtual Stage .vstpreset, or None.
    distance = knbVol / 2 (a float: 30.5 is a real half step), position = knbPan - 100."""
    try:
        d = bytes(data)
        if d[:4] != b"VST3" or b"btnRoomLg" not in d:
            return None
        got = {}
        for ident in (b"knbVol", b"knbPan", b"btnDistanceOnly"):
            off = _vstage_value_offset(d, ident, 4)
            got[ident] = struct.unpack_from("<d", d, off)[0]
        rooms = [rm for rm, ident in VSTAGE_ROOM_BUTTON.items()
                 if struct.unpack_from("<q", d, _vstage_value_offset(d, ident, 6))[0]]
        if len(rooms) != 1:
            return None
        return (got[b"knbVol"] / 2.0, got[b"knbPan"] - 100.0, rooms[0],
                got[b"btnDistanceOnly"] >= 0.5)
    except Exception:
        return None


# The label opens with the FAMILY, so the files sort into groups in Cubase's list
# ('Guitar_chord', not 'Chord_Guitar'): the Kirchhoff labels (EQApp.KEQ_LABEL) are the base,
# and the drums and basses follow his own FX chain names ('1---Drum 1 Kick', '1---Bass X').
# Underscores instead of spaces, like every other generated name.
VSTAGE_LABEL = {
    "kick": "Drum_1_Kick", "snare": "Drum_2_Snare", "hihat": "Drum_3_Hihat",
    "ride": "Drum_4_Ride", "toms": "Drum_5_Tom", "percussion": "Drum_6_Percussion",
    "cymbals": "Drum_7_Cymbal", "hand_drums": "Drum_Hand",
    "bass_root": "Bass_ground", "bass_loop": "Bass_X",
    "double_bass": "Bass_double", "double_bass_section": "Bass_double_section",
    "horn_section": "Horn_section", "french_horn": "Horn_french",   # not 'Horns' next to 'Horn'
}


def vstage_label(iid):
    """A file-name-safe label for an instrument ('Cello', 'Guitar_chord', 'Drum_1_Kick')."""
    if iid in VSTAGE_LABEL:
        return VSTAGE_LABEL[iid]
    keq = getattr(globals().get("EQApp"), "KEQ_LABEL", {}).get(iid)
    if keq:
        return keq
    s = _re.sub(r"[^A-Za-z0-9]+", "_", _stage_name(iid)).strip("_")
    return s or iid


def vstage_presets_for(rows, only=None):
    """One entry per DISTINCT preset the stage rows call for, in stage order
    (`only` = a set of instrument ids to keep, the rest of the rows are ignored):
    {"name", "label", "iid", "room", "dist", "pos", "copy"}.
    A row that stays OFF the plug-in (kick, basses) has none; a laddered row (xN) has one
    per copy; a copy that lands on the same numbers as another is written once."""
    out, seen = [], set()
    for iid, r in sorted((rows or {}).items(), key=lambda kv: kv[1].get("pos_pct", 0)):
        if r.get("skip") or r.get("dist") is None or not r.get("room"):
            continue
        if only is not None and iid not in only:
            continue
        pcts = r.get("pos_pcts") or [r["pos_pct"]]
        dists = r.get("dists") or [r["dist"]] * len(pcts)
        if len(dists) != len(pcts):
            dists = [r["dist"]] * len(pcts)
        # A ladder uses the SAME unique 5-steps as its printed label (L5 / R5,
        # never two rungs on one spot) - a file always says what the line says.
        # A part whose copies all stand on ONE spot (two hi-hats) is no ladder.
        snapped = (vstage_snap_ladder(pcts)
                   if len(set(round(p, 6) for p in pcts)) > 1 else None)
        for k, (p, d) in enumerate(zip(pcts, dists)):
            pos = snapped[k] if snapped is not None else vstage_pos_value(p)
            name = vstage_preset_name(vstage_label(iid), r["room"], d, pos)
            if name in seen:
                continue
            seen.add(name)
            out.append({"name": name, "label": vstage_label(iid), "iid": iid,
                        "room": r["room"], "dist": int(d), "pos": pos,
                        "copy": (k + 1) if len(pcts) > 1 else 0})
    return out


# ---- THE LIBRARY ("Generate > Virtual Stage presets: All") ---------------------
# Selected writes the stage of THIS song. All writes the building blocks for any song, so
# a stage can be put together from the Cubase list without generating first. Each scenario
# below is run through the real stage_plan() once per room, and only the rows named in
# `only` are kept. The Distance of a library preset is that of its reference line-up: a
# real song with different company can nudge it a few points, which is the "a little less
# to change by hand" he asked for - not a promise that the numbers are final.
#
#   * every instrument on its own (the kit pieces are not "alone": see the kits below),
#   * rhythm + chord guitar together - they nearly always come as one of each, and then
#     take opposite edges - plus the exceptions (2+1, 1+2, 2+2),
#   * the kit in seven shapes (what is in it decides how wide it may be),
#   * TOMS and CYMBALS for every count 1..9: each count lays its channels out at its own
#     L / C / R spread. Toms with and without overheads (the kit's edge, and so the spread,
#     depends on it); cymbals in the kit with toms.
VSTAGE_LIB_MAX_COUNT = 9
VSTAGE_LIB_KITS = (
    ("full kit",               ("kick", "snare", "hihat", "toms", "cymbals")),
    ("full kit with ride",     ("kick", "snare", "hihat", "ride", "toms", "cymbals")),
    ("no toms",                ("kick", "snare", "hihat", "cymbals")),
    ("no toms, with ride",     ("kick", "snare", "hihat", "ride", "cymbals")),
    ("no overheads",           ("kick", "snare", "hihat", "toms")),
    ("beat: kick, snare, hat", ("kick", "snare", "hihat")),
    ("beat: kick, snare",      ("kick", "snare")),
)


def vstage_library_scenarios():
    """[(group, title, ids, counts, only)] - see the note above."""
    out = []
    for x in EQ_DATA:
        if x["id"] in KIT_IDS:
            continue
        out.append(("Every instrument on its own", x["name"], [x["id"]], {},
                    {x["id"]}))
    gtr = ("guitar_rhythm", "guitar_chords")
    if all(_stage_known(g) for g in gtr):
        for nr, nc in ((1, 1), (2, 1), (1, 2), (2, 2)):
            out.append(("Rhythm + chord guitar together",
                        "rhythm x%d + chord x%d" % (nr, nc), list(gtr),
                        {"guitar_rhythm": nr, "guitar_chords": nc}, set(gtr)))
    for title, ids in VSTAGE_LIB_KITS:
        out.append(("The drum kit", title, list(ids), {}, set(KIT_IDS)))
    for n in range(1, VSTAGE_LIB_MAX_COUNT + 1):
        out.append(("Toms, 1 to %d" % VSTAGE_LIB_MAX_COUNT,
                    "toms x%d, kit with overheads" % n,
                    ["kick", "snare", "hihat", "toms", "cymbals"], {"toms": n},
                    {"toms"}))
        out.append(("Toms, 1 to %d" % VSTAGE_LIB_MAX_COUNT,
                    "toms x%d, kit without overheads" % n,
                    ["kick", "snare", "hihat", "toms"], {"toms": n}, {"toms"}))
    for n in range(1, VSTAGE_LIB_MAX_COUNT + 1):
        out.append(("Cymbals, 1 to %d" % VSTAGE_LIB_MAX_COUNT,
                    "cymbals x%d, kit with toms" % n,
                    ["kick", "snare", "hihat", "toms", "cymbals"], {"cymbals": n},
                    {"cymbals"}))
    return out


def vstage_library(perspective="audience", rooms=VSTAGE_ROOMS):
    """Every preset of the library, scenario by scenario, each in every room in `rooms`.
    Same numbers = same name = ONE entry (the first scenario to produce it names it)."""
    presets, seen = [], set()
    for group, title, ids, counts, only in vstage_library_scenarios():
        for room in rooms:
            rows, _info = stage_plan(ids, counts, perspective,
                                     overrides={STAGE_ROOM_KEY: room})
            for p in vstage_presets_for(rows, only):
                if p["name"] in seen:
                    continue
                seen.add(p["name"])
                p["group"], p["scenario"] = group, title
                presets.append(p)
    return presets


def vstage_selftest():
    """His own '3---Cello' (Distance 46, L10, Large; knob values 91 / 90) rebuilt from the
    three numbers must be the embedded file again, and the readback must agree."""
    errs = []
    tpl = _vstage_template()
    if make_vstage_preset(46, -10, "Large", raw_vol=91) != tpl:
        errs.append("3---Cello is not rebuilt byte for byte")
    for room in VSTAGE_ROOMS:
        for dist, pos in ((0, -100), (46, -10), (100, 100), (30, 0)):
            back = read_vstage_values(make_vstage_preset(dist, pos, room))
            if back != (float(dist), float(pos), room, True):
                errs.append("readback %s %s %s -> %r" % (room, dist, pos, back))
    return errs


# *************** DEL 02n - CORRIDOR REVERB (Quantastical Sound) *************
# Corridor is a room/corridor reverb whose state is, unusually, completely
# readable: the VST3 preset is a JUCE container holding plain XML —
#     <CorridorParameters listenA=".." listenB="..">
#       <PARAM id="decay" value="58.0"/> … <RoomPans count="7" …/>
#     </CorridorParameters>
# — so this program can write real presets for it instead of cloning a seed and
# hoping (which is what smart:reverb and smart:EQ force us to do, see DEL 02f).
#
# WHAT IS KNOWN FOR CERTAIN, AND WHAT IS NOT.
# The parameter ids and their UI names are read straight out of the plug-in, so
# the NAMES below are exact. The plug-in publishes no min/max anywhere in its
# binary, so the RANGES are inferred, and the numbers in this table are kept
# deliberately inside the span the user's own 'corridor-test' preset proves is
# legal (mix 18, decay 58, lp 82, color 40, lowMult 60, erAmount 50, width 110,
# size 2.97, densityCompAmount 100). Everything here is a STARTING POINT that
# loads and plays — the same promise the rest of this program makes.
#
#   size        Size            room scale        (test preset: 2.97)
#   decay       Decay           0–100
#   predelay    Pre-Delay       ms
#   width       Width           100 = natural, >100 wider
#   mix         Mix             0–100 % wet
#   hp / lp     Highpass/Lowpass  damping pair — hp up = less mud in the tail,
#                                 lp down = darker tail
#   color       Color           tone of the room itself
#   lowMult     Low Decay       how much longer the LOWS ring than the mids.
#                               Down = the single most useful knob on a vocal.
#   erAmount    Early Reflections   up = room, down = tail
#   tight       Tight           up = less smear on transients
#   duck        Duck            reverb ducks while the source plays. THE
#                               lead-vocal trick: the words stay dry, the tail
#                               blooms in the gaps.
#   mod/modSpeed  Mod, Mod Speed    movement in the tail (stops it ringing)
#   shimmer     Shimmer         octave-up regeneration — pads and choirs only
#   push, drift, mirror, mirrorUD, symm, pipeScale, freeze*, wetLock, mixCurve,
#   densityCompAmount (Tame)    left at the user's proven values below.

CORRIDOR_COLOUR = "#9fe0ff"      # pale blue — its own colour, not the depth cyan
CORRIDOR_NAME   = "Corridor"
CORRIDOR_VENDOR = "Quantastical Sound"

# The room models named inside the plug-in binary, in the order they appear
# there. The ORDER IS INFERRED — the binary lists the names but not their
# indices — so nothing here selects one by default: every generated preset uses
# CORRIDOR_ROOM_DEFAULT, which is the model in the user's own saved preset and
# is therefore known-good. Check the order once in the plug-in, then flip
# CORRIDOR_USE_ROOM_MODELS to True and the per-preset "room" fields take over.
CORRIDOR_ROOMS = ["Vault", "Shimmer", "Abyss", "Plateau", "Ghost", "Cloud",
                  "Wood", "Ensemble", "Grove", "Atrium", "Ambience", "Velvet",
                  "Arcade"]
CORRIDOR_ROOM_DEFAULT   = 8      # the model in 'corridor-test' — proven to load
CORRIDOR_USE_ROOM_MODELS = False

# Everything a preset does not name keeps these values. They are the user's own
# 'corridor-test' preset, so an untouched parameter is always one this exact
# plug-in has already accepted.
CORRIDOR_BASE = {
    "pipeScale": 0.0, "mirror": 0.0, "mirrorUD": 0.0, "symm": 0.0,
    "push": 0.0, "drift": 0.0, "densityCompAmount": 100.0, "mixCurve": 0.0,
    "freeze": 0.0, "freezeEnv": 0.0, "freezeEnvPolarity": 1.0, "wetLock": 0.0,
    "shimmer": 0.0, "shimmerChord": 0.0, "shimmerTranspose": 0.0,
}

# ---------------------------------------------------------------------------
# THE PRESETS. Weighted hard toward voices, because that is what the user asked
# for and because a voice is the one source where the reverb decision is a
# musical decision rather than a taste one: too much and the words go, too
# little and the singer is standing in a different recording from the band.
#
# Each entry: key · name · role · params (merged over CORRIDOR_BASE) · note.
# ---------------------------------------------------------------------------
CORRIDOR_PRESETS = [
    # ---- LEAD VOCAL --------------------------------------------------------
    {"key": "lead_close", "name": "Lead Vocal · Close", "room": 10,
     "role": "The safest lead reverb there is: you hear the space, not the tail.",
     "params": {"size": 2.4, "decay": 34, "predelay": 28, "mix": 12,
                "hp": 30, "lp": 74, "color": 38, "lowMult": 45,
                "erAmount": 62, "tight": 55, "duck": 45,
                "mod": 8, "modSpeed": 30, "width": 100},
     "note": "Pre-Delay 28 ms is doing the work — it keeps the first 28 ms of "
             "every word completely dry, which is why the vocal stays in front "
             "of its own reverb. Start here on any vocal you have not mixed "
             "before."},
    {"key": "lead_plate", "name": "Lead Vocal · Pop Plate", "room": 3,
     "role": "The everyday one. Bright, medium, ducked.",
     "params": {"size": 3.2, "decay": 48, "predelay": 24, "mix": 16,
                "hp": 28, "lp": 78, "color": 44, "lowMult": 45,
                "erAmount": 45, "tight": 40, "duck": 40,
                "mod": 14, "modSpeed": 34, "width": 108},
     "note": "Low Decay at 45 is the difference between a plate and a puddle: "
             "the lows stop ringing before the mids do, so the tail never "
             "collects under the voice."},
    {"key": "lead_plate_alone", "name": "Lead Vocal · Pop Plate (alone)", "room": 3,
     "role": "The Pop Plate for a lead with NO backing vocals: a little bigger and wetter.",
     "params": {"size": 3.6, "decay": 56, "predelay": 24, "mix": 21,
                "hp": 28, "lp": 78, "color": 44, "lowMult": 45,
                "erAmount": 40, "tight": 35, "duck": 40,
                "mod": 14, "modSpeed": 34, "width": 110},
     "note": "Same plate as the everyday one, with +5 Mix, +8 Decay and +0.4 Size. "
             "With nothing behind it the voice has to make its own space; the "
             "Duck stays at 40 so the words are still clear."},
    {"key": "lead_ballad", "name": "Lead Vocal · Ballad Long", "room": 9,
     "role": "A long tail that survives a slow song without eating the words.",
     "params": {"size": 4.4, "decay": 68, "predelay": 34, "mix": 20,
                "hp": 32, "lp": 72, "color": 40, "lowMult": 38,
                "erAmount": 32, "tight": 25, "duck": 60,
                "mod": 18, "modSpeed": 28, "width": 112},
     "note": "Duck 60 is high on purpose. A tail this long is only usable "
             "because it gets out of the way while the line is being sung and "
             "comes back in the gaps — turn Duck off and listen to what "
             "happens to the consonants."},
    {"key": "lead_ambience", "name": "Lead Vocal · Ambience only", "room": 10,
     "role": "Early reflections, almost no tail. For a dense, busy mix.",
     "params": {"size": 2.0, "decay": 18, "predelay": 12, "mix": 14,
                "hp": 34, "lp": 80, "color": 42, "lowMult": 40,
                "erAmount": 92, "tight": 70, "duck": 35,
                "mod": 6, "modSpeed": 26, "width": 104},
     "note": "When a mix is already full, a tail is just more mud. This one "
             "gives the voice a ROOM instead of a reverb — it stops sounding "
             "like it was dropped in from a dry booth without adding anything "
             "that rings."},
    {"key": "lead_dark", "name": "Lead Vocal · Dark & Warm", "room": 11,
     "role": "For a bright, thin or sibilant voice.",
     "params": {"size": 3.0, "decay": 52, "predelay": 26, "mix": 15,
                "hp": 24, "lp": 58, "color": 26, "lowMult": 55,
                "erAmount": 40, "tight": 45, "duck": 45,
                "mod": 12, "modSpeed": 30, "width": 102},
     "note": "Lowpass 58 and Color 26 pull the top off the TAIL, not off the "
             "voice. That is the fix for a harsh singer that does not cost you "
             "any of the clarity you are actually keeping."},

    # ---- BACKING VOCALS ----------------------------------------------------
    {"key": "backing_wide", "name": "Backing Vocals · Wide Wash", "room": 5,
     "role": "Wide, wet and clearly further away than the lead.",
     "params": {"size": 4.0, "decay": 62, "predelay": 8, "mix": 30,
                "hp": 34, "lp": 76, "color": 46, "lowMult": 35,
                "erAmount": 30, "tight": 20, "duck": 15,
                "mod": 22, "modSpeed": 38, "width": 128},
     "note": "The SHORT pre-delay is the point, and it is the opposite of the "
             "lead setting: 8 ms glues the reverb onto the voices instead of "
             "separating it, which is what pushes them back behind the lead."},
    {"key": "backing_behind", "name": "Backing Vocals · Behind the Lead", "room": 8,
     "role": "Supports without competing. The default for backing vocals.",
     "params": {"size": 3.4, "decay": 52, "predelay": 10, "mix": 24,
                "hp": 36, "lp": 74, "color": 42, "lowMult": 35,
                "erAmount": 38, "tight": 30, "duck": 25,
                "mod": 18, "modSpeed": 34, "width": 118},
     "note": "Highpass 36 keeps the backing tail out of the 200–400 Hz window "
             "the lead vocal's body lives in. Two vocal reverbs sharing that "
             "band is the usual reason a chorus sounds smaller than the verse."},
    {"key": "backing_glue", "name": "Backing Vocals · Doubles Glue", "room": 10,
     "role": "Short and dense — makes stacked doubles read as one part.",
     "params": {"size": 2.6, "decay": 30, "predelay": 6, "mix": 20,
                "hp": 38, "lp": 78, "color": 44, "lowMult": 32,
                "erAmount": 66, "tight": 60, "duck": 20,
                "mod": 10, "modSpeed": 30, "width": 120},
     "note": "For four or six stacked takes that sound like four or six people "
             "instead of one section. The early reflections fill the gaps "
             "between the takes; a long tail would only blur their timing."},

    # ---- CHOIR / VOCAL PAD -------------------------------------------------
    {"key": "choir_bed", "name": "Choir & Vocal Pad · Soft Bed", "room": 5,
     "role": "A held vocal bed at the back of the mix.",
     "params": {"size": 5.0, "decay": 76, "predelay": 0, "mix": 38,
                "hp": 40, "lp": 70, "color": 40, "lowMult": 30,
                "erAmount": 22, "tight": 12, "duck": 10,
                "mod": 26, "modSpeed": 24, "width": 132},
     "note": "Pre-Delay 0 and Mix 38: this is not a vocal with reverb on it, "
             "it IS the reverb. Nothing here needs to stay intelligible."},
    {"key": "choir_cathedral", "name": "Choir & Vocal Pad · Cathedral", "room": 0,
     "role": "Very long, with a little octave-up shimmer on top.",
     "params": {"size": 6.0, "decay": 88, "predelay": 0, "mix": 42,
                "hp": 42, "lp": 66, "color": 36, "lowMult": 28,
                "erAmount": 16, "tight": 8, "duck": 8,
                "mod": 30, "modSpeed": 20, "width": 134,
                "shimmer": 18, "shimmerChord": 0},
     "note": "Shimmer 18 is a small amount on purpose — shimmer is a pitch "
             "effect, and past roughly 25 it stops being a room and starts "
             "being a synth pad you did not write."},

    # ---- EVERYTHING ELSE ---------------------------------------------------
    {"key": "snare_room", "name": "Snare · Room", "room": 10,
     "role": "Short, bright, and off the transient.",
     "params": {"size": 2.6, "decay": 30, "predelay": 12, "mix": 18,
                "hp": 26, "lp": 82, "color": 50, "lowMult": 40,
                "erAmount": 70, "tight": 72, "duck": 30,
                "mod": 4, "modSpeed": 22, "width": 106},
     "note": "Tight 72 keeps the crack of the snare intact. A snare reverb "
             "that softens the hit has already failed, however good the tail "
             "sounds on its own."},
    {"key": "drums_ambience", "name": "Drum kit · Ambience", "room": 10,
     "role": "For the overhead / room bus, not the close mics.",
     "params": {"size": 3.2, "decay": 26, "predelay": 6, "mix": 14,
                "hp": 30, "lp": 80, "color": 48, "lowMult": 35,
                "erAmount": 84, "tight": 68, "duck": 25,
                "mod": 4, "modSpeed": 20, "width": 116},
     "note": "Put this on ONE drum bus, never on each drum. Six close mics "
             "each with their own room is six rooms, and the kit stops sounding "
             "like one instrument in one place."},
    {"key": "guitar_room", "name": "Guitar · Natural Room", "room": 6,
     "role": "Acoustic and rhythm guitars — a room, not an effect.",
     "params": {"size": 3.0, "decay": 44, "predelay": 18, "mix": 14,
                "hp": 32, "lp": 76, "color": 44, "lowMult": 40,
                "erAmount": 48, "tight": 45, "duck": 20,
                "mod": 12, "modSpeed": 30, "width": 110},
     "note": "An acoustic guitar already contains its own body resonance. Mix "
             "14 is low because you are adding a room, not a second guitar."},
    {"key": "guitar_solo", "name": "Lead Guitar · Solo Space", "room": 3,
     "role": "A solo has to sound like it walked forward into a bigger room.",
     "params": {"size": 3.8, "decay": 58, "predelay": 22, "mix": 18,
                "hp": 28, "lp": 74, "color": 42, "lowMult": 42,
                "erAmount": 36, "tight": 32, "duck": 25,
                "mod": 16, "modSpeed": 32, "width": 112},
     "note": "Longer than the rhythm guitar room on purpose. If both guitars "
             "sit in the same space the solo does not read as a solo."},
    {"key": "piano_room", "name": "Piano & Mallets · Room", "room": 7,
     "role": "Keeps a piano from sounding sampled.",
     "params": {"size": 3.6, "decay": 50, "predelay": 16, "mix": 14,
                "hp": 30, "lp": 78, "color": 42, "lowMult": 42,
                "erAmount": 44, "tight": 40, "duck": 15,
                "mod": 10, "modSpeed": 28, "width": 112},
     "note": "Low Decay 42 matters more on a piano than on anything else: the "
             "left hand will ring the room out on its own if you let it."},
    {"key": "organ_hall", "name": "Organ & Accordion · Hall", "room": 0,
     "role": "A big instrument standing in one fixed place.",
     "params": {"size": 4.2, "decay": 62, "predelay": 0, "mix": 20,
                "hp": 34, "lp": 72, "color": 38, "lowMult": 34,
                "erAmount": 28, "tight": 22, "duck": 15,
                "mod": 20, "modSpeed": 26, "width": 118},
     "note": "Pre-Delay 0 — an organ belongs to its building. Separating it "
             "from its own room is the one thing that makes it sound fake."},
    {"key": "horns_hall", "name": "Horns · Section Hall", "room": 9,
     "role": "One shared space so the section reads as a section.",
     "params": {"size": 4.0, "decay": 56, "predelay": 14, "mix": 18,
                "hp": 32, "lp": 74, "color": 44, "lowMult": 38,
                "erAmount": 40, "tight": 35, "duck": 18,
                "mod": 14, "modSpeed": 30, "width": 116},
     "note": "Use the SAME preset on every horn. Different reverbs on trumpet "
             "and trombone is three overdubs; one reverb is a horn section."},
    {"key": "strings_hall", "name": "Strings & Winds · Hall", "room": 9,
     "role": "Long and wide — strings are the one place that is allowed.",
     "params": {"size": 4.6, "decay": 70, "predelay": 10, "mix": 26,
                "hp": 34, "lp": 72, "color": 40, "lowMult": 32,
                "erAmount": 26, "tight": 18, "duck": 12,
                "mod": 22, "modSpeed": 24, "width": 126},
     "note": "Mod 22 keeps a long string tail from turning into one sustained "
             "ringing note. Without movement a hall this size starts to sound "
             "like a pitch."},
    {"key": "pad_backwall", "name": "Synth Pad · Back Wall", "room": 2,
     "role": "The furthest thing in the mix, with shimmer.",
     "params": {"size": 5.4, "decay": 82, "predelay": 0, "mix": 34,
                "hp": 38, "lp": 68, "color": 36, "lowMult": 28,
                "erAmount": 18, "tight": 10, "duck": 8,
                "mod": 28, "modSpeed": 22, "width": 134,
                "shimmer": 24, "shimmerChord": 0},
     "note": "A pad is the back wall of the mix, so it gets the biggest number "
             "on the page. Highpass 38 is what stops that from arriving in the "
             "bass player's octave."},
    {"key": "perc_room", "name": "Percussion · Small Room", "room": 10,
     "role": "Places a shaker or tambourine in the same room as the kit.",
     "params": {"size": 2.4, "decay": 26, "predelay": 8, "mix": 12,
                "hp": 36, "lp": 82, "color": 50, "lowMult": 34,
                "erAmount": 76, "tight": 70, "duck": 20,
                "mod": 6, "modSpeed": 26, "width": 114},
     "note": "Almost all early reflections. Percussion needs to be IN the room "
             "with the drums; it does not need a tail of its own."},
]

CORRIDOR_BY_KEY = {p["key"]: p for p in CORRIDOR_PRESETS}

# instrument id → the preset to reach for first.
# DRY channels (kick, both basses, double bass) are deliberately absent: no
# entry means no line, the same rule the depth engine uses (DEL 02e).
CORRIDOR_FOR = {
    "vocals_lead": "lead_plate",
    "vocals_backing": "backing_behind",
    "vocals_choir_pad": "choir_bed",
    "vocals_extra": "choir_bed",
    "snare": "snare_room",
    "toms": "drums_ambience",
    "cymbals": "drums_ambience",
    "hihat": "drums_ambience",
    "ride": "drums_ambience",
    "percussion": "perc_room",
    "hand_drums": "drums_ambience",
    "guitar_acoustic": "guitar_room",
    "guitar_rhythm": "guitar_room",
    "guitar_chords": "guitar_room",
    "guitar_lead": "guitar_solo",
    "guitar_single_low": "guitar_solo",
    "piano_bg": "piano_room",
    "piano_riff": "piano_room",
    "synth_mallet": "piano_room",
    "synth_pluck": "piano_room",
    "organ": "organ_hall",
    "organ_lead": "organ_hall",
    "organ_melody": "organ_hall",
    "brass_lead": "horns_hall",
    "accordion_lead": "organ_hall",
    "flute_bg": "strings_hall",
    "violin_bg": "strings_hall",
    "strings_lead": "strings_hall",
    "accordion": "organ_hall",
    "brass": "horns_hall",
    "trumpet": "horns_hall",
    "trombone": "horns_hall",
    "tenor_trombone": "horns_hall",
    "tenor_bass_trombone": "horns_hall",
    "saxophone": "horns_hall",
    "horn_section": "horns_hall",
    "harmonica": "guitar_solo",
    "violin": "strings_hall",
    "viola": "strings_hall",
    "viola_front": "strings_hall",
    "cello": "strings_hall",
    "string_section": "strings_hall",
    "flute": "strings_hall",
    "woodwind": "strings_hall",
    "clarinet": "strings_hall",
    "oboe": "strings_hall",
    "bassoon": "strings_hall",
    "contrabassoon": "strings_hall",
    "flugelhorn": "horns_hall",
    "french_horn": "horns_hall",
    "tuba": "horns_hall",
    "english_horn": "strings_hall",
    "euphonium": "horns_hall",
    "bass_clarinet": "strings_hall",
    "contrabass_clarinet": "strings_hall",
    "piccolo": "strings_hall",
    "alto_flute": "strings_hall",
    "bass_flute": "strings_hall",
    "soprano_sax": "horns_hall",
    "alto_sax": "horns_hall",
    "tenor_sax": "horns_hall",
    "baritone_sax": "horns_hall",
    "piccolo_trumpet": "horns_hall",
    "alto_trombone": "horns_hall",
    "bass_trombone": "horns_hall",
    "double_bass_trombone": "horns_hall",
    "synth_pad": "pad_backwall",
}

# The alternatives worth knowing about, per channel. Vocals get several,
# because "a vocal reverb" is a decision, not a value.
CORRIDOR_ALSO = {
    "vocals_lead":      ["lead_close", "lead_ballad", "lead_ambience", "lead_dark"],
    "vocals_backing":   ["backing_wide", "backing_glue"],
    "vocals_choir_pad": ["choir_cathedral"],
    "synth_pad":        ["choir_cathedral"],
    "organ_lead":       ["guitar_solo"],
    "organ_melody":     ["guitar_solo"],
    "brass_lead":       ["guitar_solo"],
    "accordion_lead":   ["guitar_solo"],
    "flute_bg":         ["pad_backwall", "choir_cathedral"],
    "violin_bg":        ["pad_backwall", "choir_cathedral"],
    "strings_lead":     ["guitar_solo", "piano_room"],
}


def corridor_for(iid, sel=None):
    """(preset, alternatives) for an instrument, or (None, []) when Corridor
    has nothing to say about it — every dry channel, by design. `sel` (the song's
    line-up) only matters for the lead vocal on its own - see lead_alone()."""
    key = CORRIDOR_FOR.get(iid)
    if not key or key not in CORRIDOR_BY_KEY:
        return None, []
    also = list(CORRIDOR_ALSO.get(iid, []))
    if iid == "vocals_lead" and lead_alone(sel) and "lead_plate_alone" in CORRIDOR_BY_KEY:
        also = [key] + [k for k in also if k != "lead_plate_alone"]
        key = "lead_plate_alone"
    alts = [CORRIDOR_BY_KEY[k] for k in also if k in CORRIDOR_BY_KEY]
    return CORRIDOR_BY_KEY[key], alts


def corridor_params(preset):
    """The full parameter set a preset writes: the proven base, then the room
    model, then whatever the preset itself names."""
    out = dict(CORRIDOR_BASE)
    out["preset"] = float(preset.get("room", CORRIDOR_ROOM_DEFAULT)
                          if CORRIDOR_USE_ROOM_MODELS else CORRIDOR_ROOM_DEFAULT)
    out.update(preset.get("params", {}))
    return out


def corridor_head(preset):
    """The one-line header: '🌀 Corridor: Lead Vocal · Pop Plate — Mix 16 % ·
    Decay 48 · Pre-Delay 24 ms · Size 3.2'."""
    if not preset:
        return ""
    p = preset["params"]
    return ("🌀 Corridor: %s  —  Mix %g %%  ·  Decay %g  ·  Pre-Delay %g ms  ·  "
            "Size %g" % (preset["name"], p.get("mix", 0), p.get("decay", 0),
                         p.get("predelay", 0), p.get("size", 0)))


def corridor_detail(preset):
    """The rest of the numbers, as one line. These ARE settings, so they are
    never hidden by the extra-comments switch."""
    if not preset:
        return ""
    p = preset["params"]
    bits = ["Highpass %g" % p.get("hp", 0), "Lowpass %g" % p.get("lp", 0),
            "Color %g" % p.get("color", 0), "Low Decay %g" % p.get("lowMult", 0),
            "Early Refl %g" % p.get("erAmount", 0), "Tight %g" % p.get("tight", 0),
            "Duck %g" % p.get("duck", 0), "Width %g" % p.get("width", 100),
            "Mod %g / %g" % (p.get("mod", 0), p.get("modSpeed", 0))]
    if p.get("shimmer"):
        bits.append("Shimmer %g" % p["shimmer"])
    return "  ·  ".join(bits)


# ---- THE PRESET WRITER -----------------------------------------------------
# A Corridor .vstpreset is the standard VST3 container:
#     "VST3" · int32 version · 32-byte class id · int64 offset of the chunk list
#     …chunks, back to back…
#     "List" · int32 count · count × (4-byte id, int64 offset, int64 size)
# The "Comp" chunk is JUCE's: b"VC2!" · int32 xml length · the XML · JUCE's own
# private trailer (the bypass flag). Only the XML changes here, so the class id,
# the JUCE trailer, the Info chunk and the <RoomPans> element are all carried
# across from the template byte for byte. The XML length changes, so the chunk
# sizes and the list offsets are recomputed rather than patched in place.

CORRIDOR_XML_PARAM = _re.compile(r'<PARAM\s+id="([^"]+)"\s+value="[^"]*"\s*/>')


def _corridor_fmt(v):
    """Format a value the way the plug-in writes them: always a decimal point."""
    s = ("%.4f" % float(v)).rstrip("0")
    return s + "0" if s.endswith(".") else s


def _corridor_chunks(data):
    """(version, class_id, [(tag, bytes), …]) from a VST3 preset container."""
    if data[:4] != b"VST3":
        raise ValueError("not a VST3 preset")
    version = struct.unpack("<i", data[4:8])[0]
    class_id = data[8:40]
    list_off = struct.unpack("<q", data[40:48])[0]
    if data[list_off:list_off + 4] != b"List":
        raise ValueError("chunk list not found")
    n = struct.unpack("<i", data[list_off + 4:list_off + 8])[0]
    out, p = [], list_off + 8
    for _ in range(n):
        tag = data[p:p + 4]
        off, size = struct.unpack("<qq", data[p + 4:p + 20])
        out.append([tag, data[off:off + size]])
        p += 20
    return version, class_id, out


def _corridor_build(version, class_id, chunks):
    """Re-assemble a container from (tag, bytes) chunks, fixing every offset."""
    body, entries, off = b"", [], 48
    for tag, blob in chunks:
        entries.append((tag, off, len(blob)))
        body += blob
        off += len(blob)
    head = (b"VST3" + struct.pack("<i", version) + class_id
            + struct.pack("<q", 48 + len(body)))
    lst = b"List" + struct.pack("<i", len(entries))
    for tag, o, s in entries:
        lst += tag + struct.pack("<qq", o, s)
    return head + body + lst


def make_corridor_preset(template, params):
    """Return a Corridor .vstpreset built from `template` with `params`
    (parameter id → value) written into its XML.

    Raises ValueError if the template is not a Corridor preset, so a wrong file
    dropped in the seed folder fails loudly instead of producing a file that
    silently will not load."""
    if b"CorridorParameters" not in template:
        raise ValueError("not a Corridor preset")
    version, class_id, chunks = _corridor_chunks(template)
    done = set()
    for entry in chunks:
        tag, blob = entry
        if tag != b"Comp" or blob[:4] != b"VC2!":
            continue
        xml_len = struct.unpack("<i", blob[4:8])[0]
        xml = blob[8:8 + xml_len].decode("utf-8")
        trailer = blob[8 + xml_len:]

        def repl(m):
            pid = m.group(1)
            if pid not in params:
                return m.group(0)
            done.add(pid)
            return '<PARAM id="%s" value="%s"/>' % (pid, _corridor_fmt(params[pid]))

        xml = CORRIDOR_XML_PARAM.sub(repl, xml)
        new = xml.encode("utf-8")
        entry[1] = b"VC2!" + struct.pack("<i", len(new)) + new + trailer
        break
    else:
        raise ValueError("no JUCE component state in the template")
    missing = [k for k in params if k not in done]
    if missing:
        raise ValueError("template has no parameter(s): " + ", ".join(sorted(missing)))
    return _corridor_build(version, class_id, chunks)


def read_corridor_values(preset_bytes):
    """{id: value} read back out of a Corridor preset — used to verify a write."""
    try:
        _v, _c, chunks = _corridor_chunks(preset_bytes)
    except Exception:
        return None
    for tag, blob in chunks:
        if tag == b"Comp" and blob[:4] == b"VC2!":
            n = struct.unpack("<i", blob[4:8])[0]
            xml = blob[8:8 + n].decode("utf-8", "replace")
            return {m.group(1): float(m.group(2)) for m in
                    _re.finditer(r'<PARAM\s+id="([^"]+)"\s+value="([^"]*)"\s*/>', xml)}
    return None


# *************** DEL 02o - OMEGA 458a SATURATION (Kush Audio) ***************
# Kush Audio "Omega 2 458a" — a transformer/preamp saturator. Its .vstpreset is
# the same JUCE container Corridor uses (DEL 02n): "VC2!" + plain XML, values in
# REAL UNITS, so this program writes real presets for it.
#
# WHAT IS KNOWN HERE IS KNOWN EXACTLY — this is the best-documented plug-in in
# the whole program. It ships an <ENGINEDATA> block inside its own binary that
# names every parameter, its range, its step, its default and its skew, plus the
# complete signal path and the fixed EQ curve baked into the model. Nothing
# below is inferred the way the Corridor ranges had to be. Where something IS a
# judgement call it says so on the line.
#
# THE SIGNAL PATH, read out of the plug-in's own PatchBay:
#
#     IN ──▶ EQ ──▶ [-20 dB Pad] ──▶ SATURATOR ──▶ COMPRESSOR ──▶ [+20 dB]
#            │                                                       │
#            │  (the fixed 458a curve + YOUR HPF/LPF)             MAKEUP
#            │                                                       │
#            └───────── dry, untouched ──────────────────▶ BLEND ◀───┘
#                                                            │
#                                                         OUTPUT ──▶ OUT
#
# Three consequences fall straight out of that picture, and they are the whole
# reason this engine is worth having:
#
#  1. THE HPF AND LPF SIT BEFORE THE SATURATOR, AND THE DRY PATH IS TAPPED
#     BEFORE THEM. So HPF 140 Hz + Blend 50 % means the saturator never sees the
#     sub at all, while half of the original — sub included — arrives at the
#     output untouched. That is the only honest way to saturate a bass or a
#     kick: distortion of a 45 Hz fundamental lands as intermodulation right
#     across the mids, and no amount of EQ afterwards puts that back.
#  2. MAKEUP AND OUTPUT GAIN ARE NOT THE SAME KNOB. Makeup is before the Blend,
#     so it changes the level of the PROCESSED path only — up means more effect
#     at the same output. Output Gain is after the Blend and moves everything.
#     At Blend 100 % they are identical; the moment you blend, they are not.
#  3. THE -20 dB PAD IS COMPENSATED (-20 in, +20 out around the saturator).
#     Pulling Input Gain down makes the whole thing quieter AND less saturated;
#     the Pad leaves the level where it was and takes 20 dB off the SATURATION
#     alone. On a hot bus, the Pad is the right answer and Input Gain is not.
#
# INTENSITY IS NOT A DRIVE KNOB, IT IS A MACRO. One control moves five things:
#     saturator drive     -28.25 dB … +15.45 dB   (skew 1.1)
#     61 Hz peak            0 dB … +0.35 dB
#     12.5 kHz peak         0 dB … +1.00 dB
#     1.79 kHz peak         0 dB … -0.30 dB
#     compressor make-up  +17 dB …  -10 dB        (reversed — the compensation)
# So more Intensity is not only more harmonics: it is also a little more low
# end, a little more top, a small scoop where a mix goes honky, and 27 dB of
# automatic level compensation against 43.7 dB of added drive. It compensates
# MOST of the level, not all of it. Match loudness by ear before deciding a
# setting is better than another one.
#
# AND THERE IS A COMPRESSOR IN THE PATH THAT YOU CANNOT SWITCH OFF. The model
# runs a Kush compressor after the saturator at attack 3.24 ms / release 135 ms,
# with no user control at all. That is why Omega thickens a part even at low
# Intensity, and why it is not a neutral colour box.

OMEGA_COLOUR = "#ffc98a"        # warm amber — saturation, not the reverb blues
OMEGA_NAME   = "Omega 2 458a"
OMEGA_VENDOR = "Kush Audio"

# The parameters as the plug-in itself declares them: id → (UI name, min, max,
# step, unit). Read from <ENGINEDATA><userParameters> in the .vst3 binary, so
# these are exact and a value clamped to them cannot be out of range.
OMEGA_RANGE = {
    "HPFFREQ":    ("HPF Freq",    20.0,   5000.0,  1.0,   "Hz"),
    "LPFFREQ":    ("LPF Freq",    40.0,  22000.0,  1.0,   "Hz"),
    "INTENSITY":  ("Intensity",    0.0,      1.0,  0.01,  "%"),
    "BLEND":      ("Blend",        0.0,      1.0,  0.01,  "%"),
    "INPUTGAIN":  ("Input Gain", -18.0,     18.0,  0.25,  "dB"),
    "OUTPUTGAIN": ("Output Gain",-18.0,     18.0,  0.25,  "dB"),
    "MAKEUP":     ("Makeup",      -9.0,      9.0,  0.25,  "dB"),
    "VUTRIM":     ("VU Trim",    -30.0,      0.0,  1.0,   "dB"),
}
OMEGA_SLOPES = ["6 dB/oct", "12 dB/oct", "18 dB/oct", "24 dB/oct"]   # HPF/LPF choice

# The 458a's own voice, before you touch anything. These are the model's fixed
# EQ defaults, read from the same block; the two marked (Intensity) are the ones
# the Intensity macro drives, so they are zero at 0 % and reach the figure shown
# at 100 %. Worth knowing because it tells you which Kirchhoff moves would be
# doing the same job twice — see omega_overlap().
OMEGA_FIXED_CURVE = [
    (376.0,   +6.42, "Low-mid weight — the biggest single move the model makes"),
    (416.0,   -0.73, "A shelf below it, so the weight lands as body, not as mud"),
    (2134.0,  +0.32, "A gentle shelf from here up"),
    (16212.0, +1.21, "Top air"),
    (61.0,    +0.35, "(Intensity) a touch more low as you drive it"),
    (12533.0, +1.00, "(Intensity) and a touch more top"),
    (1788.0,  -0.30, "(Intensity) with a small scoop where things go honky"),
]
# The three that are worth checking a Kirchhoff boost against — the fixed ones
# big enough to matter, as (hz, db, what).
OMEGA_OVERLAP_POINTS = [
    (376.0,   +6.4, "low-mid weight"),
    (2134.0,  +0.3, "presence shelf"),
    (16212.0, +1.2, "air"),
]

# Everything a preset does not name keeps these. They are the user's own
# 'Kush-omega' preset — the factory default with Intensity at 25 % — so an
# untouched parameter is always one this exact build has already accepted.
OMEGA_BASE = {
    "20DBPAD": 0.0, "BLEND": 1.0,
    "HPFFREQ": 20.0, "HPFONOFF": 1.0, "HPFSLOPE": 0.0,
    "LPFFREQ": 18000.001953125, "LPFONOFF": 1.0, "LPFSLOPE": 0.0,
    "INPUTGAIN": 0.0, "OUTPUTGAIN": 0.0, "MAKEUP": 0.0,
    "INTENSITY": 0.25, "OVERSAMPLING": 1.0, "PHASE": 0.0,
    "SOFTBYPASS": 0.0, "VUTRIM": -18.0,
}
# Written into every file but NOT restored by Kush's preset manager (the plug-in
# marks them ignoreInPreset), so they are global switches, not preset settings.
OMEGA_NOT_RECALLED = ("OVERSAMPLING", "SOFTBYPASS")


def omega_drive_db(intensity):
    """Roughly how hard the saturator is being driven, in dB, at a given
    Intensity. The plug-in declares the range (-28.25 … +15.45 dB) and the skew
    (1.1) but not the curve function; this uses the standard JUCE skew, which is
    what the 'type="standard"' on that element means. Treat it as a good
    approximation for reading, not as a number to dial."""
    x = max(0.0, min(1.0, float(intensity)))
    prop = x ** (1.0 / 1.1) if x > 0 else 0.0
    return -28.25 + 43.70 * prop


def omega_clamp(pid, value):
    """Keep a value inside the range the plug-in publishes for that parameter."""
    spec = OMEGA_RANGE.get(pid)
    if not spec:
        return value
    _n, lo, hi, _s, _u = spec
    return max(lo, min(hi, float(value)))


# ---------------------------------------------------------------------------
# THE PRESETS.
#
# Unlike Corridor, Omega is a per-channel insert: one instance on every track
# that wants it, not one shared space. So these are grouped by what the SOURCE
# is, and several channels share a preset only when they genuinely want the
# same treatment.
#
# The rule every one of them follows: LEVEL IS NOT PART OF THE PRESET. Input
# Gain, Output Gain and Makeup stay at 0 unless there is a reason on the line,
# because a preset that arrives louder always sounds better and that is not a
# decision, it is an illusion. Intensity carries its own compensation; use the
# VU and your ears.
#
# Each entry: key · name · role · params (merged over OMEGA_BASE) · note ·
# optional caution (printed in red, never hidden).
# ---------------------------------------------------------------------------
OMEGA_PRESETS = [
    # ---- VOICES ------------------------------------------------------------
    {"key": "vocal_lead", "name": "Lead Vocal · Weight & Air",
     "role": "The everyday lead setting: body from the model, air from the top.",
     "params": {"INTENSITY": 0.32, "HPFFREQ": 80.0, "HPFSLOPE": 1,
                "LPFFREQ": 18000.0, "BLEND": 1.0},
     "note": "The high-pass at 80 Hz is not there to thin the voice — it is "
             "there so the saturator never sees the proximity boom under it. "
             "Saturating 60 Hz of chest on a close mic is what makes a vocal "
             "sound like it is shouting through a wall."},
    {"key": "vocal_light", "name": "Lead Vocal · Light Touch",
     "role": "When the take is already good and you only want it glued.",
     "params": {"INTENSITY": 0.18, "HPFFREQ": 70.0, "HPFSLOPE": 1,
                "BLEND": 1.0},
     "note": "Start here on a voice you have not mixed before. At 18 % the "
             "compressor in the path is doing about as much of the work as the "
             "saturation is, which is usually exactly what a good take wants."},
    {"key": "vocal_push", "name": "Lead Vocal · Push it Forward",
     "role": "A quiet or shy vocal that will not stay in front of the band.",
     "params": {"INTENSITY": 0.48, "HPFFREQ": 90.0, "HPFSLOPE": 1,
                "LPFFREQ": 16000.0, "BLEND": 0.85},
     "note": "Blend 85 % keeps 15 % of the untouched take, and that 15 % is "
             "where the consonants and the breaths still live. Pushed to 100 % "
             "this same setting starts to sound like a compressor fighting a "
             "singer instead of a singer standing closer."},
    {"key": "vocal_backing", "name": "Backing Vocals · Density",
     "role": "Backing parts want to be dense and to sit BEHIND the lead.",
     "params": {"INTENSITY": 0.40, "HPFFREQ": 110.0, "HPFSLOPE": 1,
                "LPFFREQ": 15000.0, "LPFSLOPE": 1, "BLEND": 1.0},
     "note": "Backing vocals take far more saturation than a lead does, and "
             "the reason is the same one that makes them work: nobody is "
             "listening to the words. High-pass at 110 and lowpass at 15 k "
             "leave the lead's body and its air both free."},
    {"key": "vocal_choir", "name": "Choir & Vocal Pad · Soft",
     "role": "A held vocal bed. Colour, not grit.",
     "params": {"INTENSITY": 0.22, "HPFFREQ": 90.0, "HPFSLOPE": 1,
                "LPFFREQ": 16000.0, "BLEND": 0.70},
     "note": "A pad is many voices already summed, so it arrives at the "
             "saturator much hotter than one voice does and distorts sooner "
             "than the Intensity number suggests. Blend 70 % is the safety "
             "margin, not timidity."},

    # ---- DRUMS -------------------------------------------------------------
    {"key": "kick_weight", "name": "Kick · Weight without Mud",
     "role": "THE preset to understand. Saturate the beater, never the sub.",
     "params": {"INTENSITY": 0.45, "HPFFREQ": 110.0, "HPFSLOPE": 1,
                "BLEND": 0.55},
     "note": "High-pass 110 means the saturator only ever sees the body and "
             "the click. Blend 55 % brings 45 % of the original back — sub "
             "included, because the dry path is tapped before the filters. "
             "That combination is the whole trick: harmonics on the part of "
             "the kick you hear on a phone, and an untouched bottom octave."},
    {"key": "snare_crack", "name": "Snare · Crack",
     "role": "More snap and more body, without softening the hit.",
     "params": {"INTENSITY": 0.40, "HPFFREQ": 90.0, "HPFSLOPE": 1,
                "LPFFREQ": 17000.0, "BLEND": 0.85},
     "note": "The compressor in the path attacks in 3.24 ms, which is slower "
             "than a snare transient — so the crack gets through and the body "
             "behind it gets squeezed. That is why this works on a snare and "
             "why turning Intensity up does not blunt the hit the way a normal "
             "compressor would."},
    {"key": "toms_body", "name": "Toms · Body",
     "role": "Wood and sustain on toms that sound like cardboard.",
     "params": {"INTENSITY": 0.35, "HPFFREQ": 60.0, "HPFSLOPE": 1,
                "LPFFREQ": 16000.0, "BLEND": 0.80},
     "note": "Toms are the one drum where the fixed +6 dB of 376 Hz in this "
             "model is doing most of the work for you. If you have already "
             "boosted the tom's body band in Kirchhoff, take that back before "
             "you decide Omega is too much."},
    {"key": "cymbals_light", "name": "Hats, Ride & Cymbals · Barely There",
     "role": "The least this plug-in can do, on the source that wants least.",
     "params": {"INTENSITY": 0.12, "HPFFREQ": 300.0, "HPFSLOPE": 1,
                "LPFFREQ": 14000.0, "LPFSLOPE": 1, "BLEND": 0.60},
     "caution": "Cymbals are where saturation turns to harshness first, and "
                "the model adds about +1 dB at 16 kHz on its own before you "
                "turn anything. If in doubt, leave Omega OFF the cymbals "
                "entirely — nothing in a mix is improved by a brighter hi-hat.",
     "note": "Lowpass 14 k and Blend 60 % exist to keep the top of the cymbal "
             "out of the saturator altogether. What is left to saturate is the "
             "stick and the low body, which is the part that helps."},
    {"key": "perc_snap", "name": "Percussion · Snap",
     "role": "Shakers, tambourine, congas — presence without volume.",
     "params": {"INTENSITY": 0.28, "HPFFREQ": 150.0, "HPFSLOPE": 1,
                "LPFFREQ": 15000.0, "BLEND": 0.80},
     "note": "Percussion usually needs to be heard rather than loud, and "
             "harmonics buy that at no cost in fader. Push the fader instead "
             "and it starts competing with the hi-hat for the same space."},

    # ---- BASS --------------------------------------------------------------
    {"key": "bass_parallel", "name": "Bass · Growl, Sub kept clean",
     "role": "The default for any bass sharing the low end with a kick.",
     "params": {"INTENSITY": 0.50, "HPFFREQ": 140.0, "HPFSLOPE": 1,
                "BLEND": 0.50},
     "note": "Everything above 140 Hz gets driven hard, and that band is what "
             "carries a bass on a laptop speaker. Half the untouched signal "
             "comes back for the fundamental. Turn Blend to 100 % once to hear "
             "what saturating a 45 Hz note actually does to the mids — then "
             "turn it back."},
    {"key": "bass_full", "name": "Bass · Full Fat (only bass in the song)",
     "role": "When there is no second bass layer and no kick fighting it.",
     "params": {"INTENSITY": 0.30, "HPFFREQ": 30.0, "HPFSLOPE": 1,
                "BLEND": 0.85},
     "note": "With the whole range going through the saturator, Intensity has "
             "to come down — 30 % here is doing more damage than 50 % on the "
             "high-passed setting. That trade is the point: you either "
             "saturate everything gently or the top of it hard."},
    {"key": "lowstring_wood", "name": "Cello & Double Bass · Wood",
     "role": "Bowed and upright low end. Warmth, not grind.",
     "params": {"INTENSITY": 0.25, "HPFFREQ": 45.0, "HPFSLOPE": 1,
                "LPFFREQ": 15000.0, "BLEND": 0.80},
     "note": "A bowed low instrument lives on the noise between the notes as "
             "much as on the notes, and that bow noise is the first thing "
             "saturation exaggerates. Keep Intensity low and let the fixed "
             "376 Hz weight do the warming."},

    # ---- GUITARS -----------------------------------------------------------
    {"key": "gtr_rhythm", "name": "Electric Guitar · Rhythm Grit",
     "role": "Rhythm and power chords. Omega is at home here.",
     "params": {"INTENSITY": 0.45, "HPFFREQ": 90.0, "HPFSLOPE": 1,
                "LPFFREQ": 12000.0, "LPFSLOPE": 1, "BLEND": 1.0},
     "note": "Lowpass 12 k is not taste, it is arithmetic: an amp cabinet "
             "stops at about 5 kHz, so anything the saturator adds above 12 k "
             "was never part of a guitar sound and only ever reads as fizz."},
    {"key": "gtr_lead", "name": "Electric Guitar · Lead Sustain",
     "role": "A lead line that dies before the phrase ends.",
     "params": {"INTENSITY": 0.55, "HPFFREQ": 110.0, "HPFSLOPE": 1,
                "LPFFREQ": 10000.0, "LPFSLOPE": 1, "BLEND": 1.0},
     "note": "Sustain here comes from the compressor in the path, not from the "
             "saturation — 135 ms of release is long enough to hold the tail "
             "of a note up. Intensity 55 % is as far as this model goes before "
             "the sound becomes the plug-in's rather than the guitar's."},
    {"key": "gtr_clean", "name": "Guitar · Clean & Chords",
     "role": "Clean electric, chord beds, anything that must stay open.",
     "params": {"INTENSITY": 0.30, "HPFFREQ": 100.0, "HPFSLOPE": 1,
                "LPFFREQ": 16000.0, "BLEND": 1.0},
     "note": "A clean guitar chord is mostly the interval between two strings, "
             "and saturation adds sum and difference tones between them. A "
             "little reads as richness; a lot reads as an out-of-tune chord "
             "that you will spend an hour blaming on the player."},
    {"key": "gtr_acoustic", "name": "Acoustic Guitar · Air",
     "role": "A steel-string that is either boomy or brittle, rarely neither.",
     "params": {"INTENSITY": 0.20, "HPFFREQ": 90.0, "HPFSLOPE": 1,
                "LPFFREQ": 18000.0, "BLEND": 0.85},
     "note": "Acoustic guitar is the source where an under-turned Omega beats "
             "a well-turned anything else: it wants the top shelf and the "
             "376 Hz weight the model gives away for free, and almost none of "
             "the drive."},

    # ---- KEYS --------------------------------------------------------------
    {"key": "keys_body", "name": "Piano, Organ & Accordion · Body",
     "role": "Keys sitting in the bed of the arrangement.",
     "params": {"INTENSITY": 0.28, "HPFFREQ": 60.0, "HPFSLOPE": 1,
                "LPFFREQ": 17000.0, "BLEND": 0.90},
     "note": "A piano covers the whole keyboard, so it is the one source where "
             "a single Intensity setting is a compromise between a bass note "
             "and a top note by definition. 28 % is chosen to be safe at the "
             "bottom rather than exciting at the top."},
    {"key": "keys_riff", "name": "Piano Riff, Pluck & Mallet · Forward",
     "role": "A hook that has to be heard: riffs, plucks, mallets.",
     "params": {"INTENSITY": 0.38, "HPFFREQ": 120.0, "HPFSLOPE": 1,
                "LPFFREQ": 16000.0, "BLEND": 0.90},
     "note": "A repeating hook is the one part where being slightly too loud "
             "and being slightly too saturated sound the same from the "
             "listener's chair. Use the saturation, keep the fader down."},

    # ---- HORNS & REEDS -----------------------------------------------------
    {"key": "brass_push", "name": "Brass & Horn Section · Push",
     "role": "Trumpet, trombone, a horn line. Brass loves a transformer.",
     "params": {"INTENSITY": 0.45, "HPFFREQ": 120.0, "HPFSLOPE": 1,
                "LPFFREQ": 11000.0, "LPFSLOPE": 1, "BLEND": 0.90},
     "caution": "Brass and saturation both live at 2–4 kHz. Check this against "
                "your Kirchhoff presence boost before you keep both.",
     "note": "The lowpass matters more here than the Intensity does. A real "
             "brass section played loud is already at the edge of harsh; "
             "adding harmonics above 11 kHz is adding them exactly where a "
             "listener flinches."},
    {"key": "reed_warm", "name": "Sax, Harmonica & Reeds · Warm",
     "role": "Reeds — a warmer, rounder version of the brass setting.",
     "params": {"INTENSITY": 0.30, "HPFFREQ": 110.0, "HPFSLOPE": 1,
                "LPFFREQ": 12000.0, "LPFSLOPE": 1, "BLEND": 0.90},
     "note": "A reed instrument already produces the odd harmonics that a "
             "saturator adds, so it reaches 'enough' much earlier than brass "
             "does. If a sax starts sounding like a harmonica, this is why."},
    {"key": "flute_light", "name": "Flute & Woodwind · Barely There",
     "role": "The near-pure tones. Almost nothing.",
     "params": {"INTENSITY": 0.14, "HPFFREQ": 150.0, "HPFSLOPE": 1,
                "LPFFREQ": 16000.0, "BLEND": 0.70},
     "note": "A flute is close to a sine wave with breath around it, and a "
             "sine wave is the one signal where every harmonic you add is "
             "audibly NEW rather than louder. This is the setting that admits "
             "the plug-in has little to offer here."},

    # ---- STRINGS & PADS ----------------------------------------------------
    {"key": "strings_warm", "name": "Strings · Warm, not Nasal",
     "role": "Violin, viola, a string desk.",
     "params": {"INTENSITY": 0.18, "HPFFREQ": 90.0, "HPFSLOPE": 1,
                "LPFFREQ": 14000.0, "LPFSLOPE": 1, "BLEND": 0.75},
     "note": "Strings go nasal before they go warm — the 1–2 kHz region is "
             "where a saturated violin stops sounding like a violin, and it is "
             "also where the model's own Intensity-driven dip at 1.79 kHz is "
             "quietly helping you. Below 20 % it helps; above it, it cannot "
             "keep up."},
    {"key": "pad_soft", "name": "Synth Pad · Soft Saturation",
     "role": "A held synth bed that is too clean to sit in a real mix.",
     "params": {"INTENSITY": 0.22, "HPFFREQ": 100.0, "HPFSLOPE": 1,
                "LPFFREQ": 16000.0, "BLEND": 0.60},
     "note": "A synth pad is the source most likely to be mathematically "
             "perfect and therefore the one that gains most from something "
             "slightly wrong happening to it. Blend rather than Intensity is "
             "the control to move here: at 60 % you get the colour without "
             "losing the pad's own movement."},

    # ---- BUSES -------------------------------------------------------------
    {"key": "bus_glue", "name": "Bus / Mix · Pad & Glue",
     "role": "A drum bus, an instrument bus, the mix bus. The Pad goes IN.",
     "params": {"INTENSITY": 0.20, "HPFFREQ": 25.0, "HPFSLOPE": 1,
                "LPFFREQ": 20000.0, "BLEND": 0.85, "20DBPAD": 1.0},
     "caution": "This is the ONLY preset here with the -20 dB Pad engaged, and "
                "it is engaged because a bus arrives about 20 dB hotter than a "
                "channel. Without it, Intensity 20 % on a bus is doing what "
                "Intensity 60 % does on a track.",
     "note": "One instance on the bus beats an instance on every channel "
             "under it — six saturators feeding a bus is six sets of "
             "intermodulation products summing, and that is a different sound "
             "from one saturator hearing the whole kit at once."},
]

OMEGA_BY_KEY = {p["key"]: p for p in OMEGA_PRESETS}

# Which preset each channel starts on. Every instrument gets one: unlike a
# reverb, there is no channel a colour box has nothing to say about — but
# 'nothing to say' is exactly what the cymbal entry says, and it says it in red.
OMEGA_FOR = {
    "vocals_lead":       "vocal_lead",
    "vocals_backing":    "vocal_backing",
    "vocals_choir_pad":  "vocal_choir",
    "vocals_extra":      "vocal_backing",
    "kick":              "kick_weight",
    "snare":             "snare_crack",
    "hihat":             "cymbals_light",
    "ride":              "cymbals_light",
    "cymbals":           "cymbals_light",
    "toms":              "toms_body",
    "percussion":        "perc_snap",
    "hand_drums":        "toms_body",
    "bass_root":         "bass_parallel",
    "bass_loop":         "bass_parallel",
    "guitar_rhythm":     "gtr_rhythm",
    "guitar_chords":     "gtr_clean",
    "guitar_acoustic":   "gtr_acoustic",
    "guitar_lead":       "gtr_lead",
    "guitar_single_low": "gtr_lead",
    "organ":             "keys_body",
    "organ_lead":        "keys_riff",
    "organ_melody":      "keys_body",
    "brass_lead":        "brass_push",
    "accordion_lead":    "keys_riff",
    "flute_bg":          "pad_soft",
    "violin_bg":         "strings_warm",
    "strings_lead":      "strings_warm",
    "accordion":         "keys_body",
    "piano_bg":          "keys_body",
    "piano_riff":        "keys_riff",
    "flute":             "flute_light",
    "brass":             "brass_push",
    "trumpet":           "brass_push",
    "trombone":          "brass_push",
    "tenor_trombone":          "brass_push",
    "tenor_bass_trombone":          "brass_push",
    "saxophone":         "reed_warm",
    "horn_section":      "brass_push",
    "harmonica":         "reed_warm",
    "woodwind":          "flute_light",
    "clarinet":          "reed_warm",
    "oboe":              "reed_warm",
    "bassoon":           "reed_warm",
    "contrabassoon":     "reed_warm",
    "flugelhorn":        "brass_push",
    "french_horn":       "brass_push",
    "tuba":              "brass_push",
    "english_horn":      "reed_warm",
    "euphonium":         "brass_push",
    "bass_clarinet":     "reed_warm",
    "contrabass_clarinet": "reed_warm",
    "double_bass_section": "lowstring_wood",
    "piccolo": "flute_light",
    "alto_flute": "flute_light",
    "bass_flute": "flute_light",
    "soprano_sax": "reed_warm",
    "alto_sax": "reed_warm",
    "tenor_sax": "reed_warm",
    "baritone_sax": "reed_warm",
    "piccolo_trumpet": "brass_push",
    "alto_trombone": "brass_push",
    "bass_trombone": "brass_push",
    "double_bass_trombone": "brass_push",
    "synth_pad":         "pad_soft",
    "synth_pluck":       "keys_riff",
    "synth_mallet":      "keys_riff",
    "violin":            "strings_warm",
    "viola":             "strings_warm",
    "viola_front":       "strings_warm",
    "cello":             "lowstring_wood",
    "double_bass":       "lowstring_wood",
    "string_section":    "strings_warm",
}

# The other setting worth knowing about per channel.
OMEGA_ALSO = {
    "vocals_lead":       ["vocal_light", "vocal_push"],
    "vocals_backing":    ["vocal_light"],
    "bass_root":         ["bass_full"],
    "bass_loop":         ["bass_full"],
    "guitar_single_low": ["gtr_clean"],
    "guitar_chords":     ["gtr_rhythm"],
    "piano_riff":        ["keys_body"],
    "organ_lead":        ["keys_body"],
    "organ_melody":      ["keys_riff"],
    "brass_lead":        ["reed_warm"],
    "accordion_lead":    ["keys_body", "reed_warm"],
    "flute_bg":          ["flute_light"],
    "violin_bg":         ["pad_soft"],
    "strings_lead":      ["lowstring_wood"],
    "toms":              ["snare_crack"],
    "synth_pad":         ["vocal_choir"],
    "double_bass":       ["bass_full"],
}


def omega_for(iid):
    """(preset, alternatives) for an instrument. Everything is covered, so this
    only returns (None, []) for an id the chart does not know."""
    key = OMEGA_FOR.get(iid)
    if not key or key not in OMEGA_BY_KEY:
        return None, []
    alts = [OMEGA_BY_KEY[k] for k in OMEGA_ALSO.get(iid, []) if k in OMEGA_BY_KEY]
    return OMEGA_BY_KEY[key], alts


def omega_params(preset):
    """The full parameter set a preset writes: the proven base, then whatever
    the preset names, every value clamped to the plug-in's own range."""
    out = dict(OMEGA_BASE)
    out.update(preset.get("params", {}))
    for pid in list(out):
        out[pid] = omega_clamp(pid, out[pid])
    # A filter that is asked for is a filter that is switched on.
    if out.get("HPFFREQ", 20.0) > 20.0:
        out["HPFONOFF"] = 1.0
    if out.get("LPFFREQ", 22000.0) < 22000.0:
        out["LPFONOFF"] = 1.0
    return out


def _omega_hz(hz):
    """'110 Hz' / '12.0 kHz', the way the plug-in's own readout shows it."""
    hz = float(hz)
    return ("%g kHz" % round(hz / 1000.0, 1)) if hz >= 1000 else ("%g Hz" % round(hz))


def omega_head(preset):
    """'🔥 Omega 458a: Kick · Weight without Mud — Intensity 45 % · Blend 55 %
    · HPF 110 Hz'."""
    if not preset:
        return ""
    p = omega_params(preset)
    bits = ["Intensity %g %%" % round(p["INTENSITY"] * 100),
            "Blend %g %%" % round(p["BLEND"] * 100)]
    if p.get("HPFONOFF") and p["HPFFREQ"] > 20.0:
        bits.append("HPF " + _omega_hz(p["HPFFREQ"]))
    return "🔥 Omega 458a: %s  —  %s" % (preset["name"], "  ·  ".join(bits))


def omega_detail(preset):
    """The rest of the panel, as one line. All settings, so never hidden."""
    if not preset:
        return ""
    p = omega_params(preset)
    bits = ["HPF %s (%s)" % (_omega_hz(p["HPFFREQ"]),
                            OMEGA_SLOPES[int(p["HPFSLOPE"])]),
            "LPF %s (%s)" % (_omega_hz(p["LPFFREQ"]),
                             OMEGA_SLOPES[int(p["LPFSLOPE"])])]
    bits.append("-20 dB Pad " + ("IN" if p.get("20DBPAD") else "out"))
    for pid, lab in (("INPUTGAIN", "Input"), ("MAKEUP", "Makeup"),
                     ("OUTPUTGAIN", "Output")):
        if p.get(pid):
            bits.append("%s %+g dB" % (lab, p[pid]))
    bits.append("VU Trim %g dB" % p["VUTRIM"])
    return "  ·  ".join(bits)


def omega_overlap(inst):
    """Where this instrument's own EQ chart asks for a BOOST that the 458a has
    already made for free. Returns a list of short strings, or [] — the point
    being that dialling the same move twice in Kirchhoff is the commonest way
    to end up wondering why a channel sounds thick."""
    out = []
    for band in inst.get("bands", []):
        if band.get("type") not in ("boost", "char"):
            continue
        db = _band_cur_db(band)
        if not db or db <= 0:
            continue
        lo, hi = _parse_hz_lo_hi(band.get("hz", ""))
        if not lo or not hi:
            continue
        for hz, fixed, what in OMEGA_OVERLAP_POINTS:
            if lo <= hz <= hi:
                out.append("%s (your %s band) — Omega gives %+g dB of %s here "
                           "before you touch anything"
                           % (_omega_hz(hz), band.get("note", "that"), fixed, what))
    return out


# ---- THE PRESET WRITER -----------------------------------------------------
# Same container as Corridor, so the two helpers in DEL 02n do the work:
# _corridor_chunks() and _corridor_build() are plain VST3 container routines
# with nothing Corridor-specific in them. Only the recognition string and the
# XML dialect differ — Omega's state is
#     <StateInformation><userParameters><PARAM id=".." value=".."/>…
# with real-unit values, plus <paramLocks> and <GUIDATA> which are carried
# across untouched.

OMEGA_XML_PARAM = _re.compile(r'<PARAM\s+id="([^"]+)"\s+value="[^"]*"\s*/>')


def _omega_fmt(v):
    """Format the way the plug-in writes them — always with a decimal point."""
    s = ("%.6f" % float(v)).rstrip("0")
    return s + "0" if s.endswith(".") else s


def make_omega_preset(template, params):
    """Return an Omega .vstpreset built from `template` with `params` written
    into its XML. Raises ValueError if the template is not an Omega preset, so
    a wrong file dropped in the folder fails loudly instead of producing one
    that silently will not load."""
    if b"StateInformation" not in template or b"INTENSITY" not in template:
        raise ValueError("not an Omega preset")
    version, class_id, chunks = _corridor_chunks(template)
    done = set()
    for entry in chunks:
        tag, blob = entry
        if tag != b"Comp" or blob[:4] != b"VC2!":
            continue
        xml_len = struct.unpack("<i", blob[4:8])[0]
        xml = blob[8:8 + xml_len].decode("utf-8")
        trailer = blob[8 + xml_len:]

        def repl(m):
            pid = m.group(1)
            if pid not in params:
                return m.group(0)
            done.add(pid)
            return '<PARAM id="%s" value="%s"/>' % (pid, _omega_fmt(params[pid]))

        xml = OMEGA_XML_PARAM.sub(repl, xml)
        new = xml.encode("utf-8")
        entry[1] = b"VC2!" + struct.pack("<i", len(new)) + new + trailer
        break
    else:
        raise ValueError("no JUCE component state in the template")
    missing = [k for k in params if k not in done]
    if missing:
        raise ValueError("template has no parameter(s): " + ", ".join(sorted(missing)))
    return _corridor_build(version, class_id, chunks)


def read_omega_values(preset_bytes):
    """{id: value} read back out of an Omega preset — used to verify a write."""
    try:
        _v, _c, chunks = _corridor_chunks(preset_bytes)
    except Exception:
        return None
    for tag, blob in chunks:
        if tag == b"Comp" and blob[:4] == b"VC2!":
            n = struct.unpack("<i", blob[4:8])[0]
            xml = blob[8:8 + n].decode("utf-8", "replace")
            return {m.group(1): float(m.group(2)) for m in
                    _re.finditer(r'<PARAM\s+id="([^"]+)"\s+value="([^"]*)"\s*/>', xml)}
    return None


# *************** DEL 02q - BANDWIDTH STEREO WIDTH (In The Mix) ***************
# In The Mix "Bandwidth" — a stereo-width plug-in that is 100 % mono compatible.
# Its presets are NOT a binary blob: a user preset is a tiny plain-text
# `.itmpreset` file (XML, CRLF line ends, ~640 bytes) that holds twelve numbers.
# So this program needs no seed/template — it writes the file from scratch, and
# every preset can be recreated at any time (the 13 the user made by hand on
# 2026-07-26 are in the list below, value for value).
#
# WHAT THE MANUAL (BandwidthManual.pdf) SAYS, AND WHAT THAT MEANS HERE
#
#   THREE BANDS, each with its own width mix ("Low" / "Mid" / "High", 0-200 %).
#     Width is ADDED to the band; 0 % leaves it exactly as it was.
#   TWO CROSSOVERS (paramX1 = low/mid, paramX2 = mid/high), 24 dB/oct. Default
#     400 Hz and 4000 Hz. "LOW CROSS 200 Hz" means the Low slider widens
#     everything below 200 Hz.
#   STRENGTH — "controls the time domain of the processing, larger values
#     induce more delay". 3-6 suits most sources; the manual says to keep it
#     BELOW 6 for bass sounds because more starts to shift the L/R balance.
#   HOW IT WORKS: it synthesises delayed copies of the signal and the width sums
#     to nothing in mono — so the original is never damaged on a mono system.
#   OUTPUT GAIN — "level match with your ears"; some sources get quieter when
#     widened, others louder.
#   MONITORING — STEREO (normal), SIDE (hear only what was ADDED), MID (hear
#     what is preserved no matter how much width is added). This program always
#     writes STEREO (2.0); the Solo buttons are always off.
#
# WHAT IS KNOWN EXACTLY AND WHAT IS NOT — said plainly, as everywhere here:
#   * The file format and every parameter id come from the user's own saved
#     presets and the 12 factory presets installed with the plug-in.
#   * Only the 0-200 % range of the three mix sliders is documented. The other
#     limits below are deliberately kept inside what the factory presets prove
#     legal (Strength 3.8-17, X1 201-753 Hz, X2 4000-11566 Hz); the bounds in
#     BANDWIDTH_RANGE are a safety net around that, not the plug-in's own table.
#   * The figures in the NEW presets are starting points chosen by the rules
#     above (low band mono on anything with weight, Strength under 6 on low
#     sources, lead sources barely widened) — not measurements. Listen, then use
#     the MID monitor to confirm the centre of the part is still intact.
#
# ToDo: if the plug-in ever publishes a parameter table (as Omega does), replace
# the inferred bounds in BANDWIDTH_RANGE with the real ones.

BANDWIDTH_COLOUR = "#8fe3c0"      # cool mint — space and width, not the saturation amber
BANDWIDTH_NAME   = "Bandwidth"
BANDWIDTH_VENDOR = "In The Mix"

# short key -> (xml id, label, lo, hi). Mix sliders are the documented 0-200 %.
BANDWIDTH_RANGE = {
    "low":      ("paramLow",        "Low",       0.0,  200.0),
    "mid":      ("paramMid",        "Mid",       0.0,  200.0),
    "high":     ("paramHigh",       "High",      0.0,  200.0),
    "strength": ("paramStrength",   "Strength",  1.0,   20.0),
    "x1":       ("paramX1",         "Low cross", 60.0, 1200.0),
    "x2":       ("paramX2",         "High cross", 1500.0, 16000.0),
    "out":      ("paramOutputGain", "Output",   -6.0,    6.0),
}

# Written into every file, never varied: plug-in ON, STEREO monitoring, no Solo.
BANDWIDTH_BASE = {
    "paramMonitorMode": 2.0, "paramPower": 1.0,
    "paramSoloHigh": 0.0, "paramSoloLow": 0.0, "paramSoloMid": 0.0,
}

# Where the plug-in looks for the user's own presets. The user's backup of this
# folder (B:\...\Presence---Bandwidth\ProgramData\In The Mix\Bandwidth\Presets\User)
# mirrors this exact path, and the Factory presets sit beside it.
BANDWIDTH_DEFAULT_DIR = os.path.join(os.environ.get("PROGRAMDATA", r"C:\ProgramData"),
                                     "In The Mix", "Bandwidth", "Presets", "User")


def _bw(low, mid, high, strength, x1, x2, out=0.0):
    return {"low": low, "mid": mid, "high": high, "strength": strength,
            "x1": x1, "x2": x2, "out": out}


# ---------------------------------------------------------------------------
# THE PRESETS. Each entry: key · name · file (the .itmpreset name, no ext) ·
# role · p (the seven numbers) · note · optional caution (printed in red).
# `mine` marks the 13 presets the user made by hand — kept value for value, so
# generating them restores exactly what was lost, nothing re-interpreted.
#
# House rules, in the order they decide a number:
#   1. LOW stays 0 on kick and basses, and low on anything with weight: the low
#      band is where width costs punch and where a speaker system folds to mono.
#   2. STRENGTH stays under 6 on anything bass-heavy (the manual's own advice).
#   3. LEAD parts are widened very little; the width goes to backing parts.
#   4. OUTPUT is -0.2 … -0.4 dB on the big presets only, because a wide part is
#      usually perceived as louder — and it is a level match, not a decision.
# ---------------------------------------------------------------------------
BANDWIDTH_PRESETS = [
    # ---- VOICES ------------------------------------------------------------
    {"key": "vocal_lead_air", "name": "Lead Vocal · Air Only",
     "file": "Vocal_Lead_Air",
     "role": "A lead vocal that stays in the middle and only gets some air.",
     "p": _bw(0, 18, 34, 3.5, 250, 4500),
     "note": "The lead is the one part that must stay a point in the centre. "
             "Low is 0 so the chest and proximity stay mono; Mid is nearly "
             "untouched so the words stay in front; only the top is opened so "
             "breath and sheen surround the voice. If the voice starts to feel "
             "'in the room' instead of 'in your head', High is too high - check "
             "it on the MID monitor."},
    {"key": "vocal_backing_wide", "name": "Backing Vocals · Wide",
     "file": "Vocal_Backing_Wide",
     "role": "Backing vocals that frame the lead from both sides.",
     "p": _bw(0, 120, 90, 5.5, 280, 5200, -0.3),
     "note": "Wide in the mids, where harmonies live, with no low band at all. "
             "This is the one that makes the lead sound narrow by comparison - "
             "which is the point: contrast, not size, is what reads as wide."},
    {"key": "vocal_harmony_open", "name": "Extra Vocals · Open Harmony",
     "file": "Vocal_Harmony_Open",
     "role": "Ad-libs, doubles and extra harmony lines.",
     "p": _bw(0, 100, 80, 5.0, 300, 5000, -0.2),
     "note": "A step narrower than the backing vocals so the extra lines sit "
             "between the lead and the choir instead of competing with the "
             "backing vocals for the same width."},
    {"key": "vocal_choir_huge", "name": "Choir / Vocal Pad · Huge",
     "file": "Vocal_Choir_Huge",
     "role": "A choir or vocal pad that fills the whole picture behind the song.",
     "p": _bw(10, 160, 130, 6.0, 250, 6000, -0.4),
     "note": "Almost the width ceiling in Mid and High. A pad can afford it "
             "because nothing in it has to be pin-pointed. Do NOT also put the "
             "lead through this."},
    # ---- DRUMS -------------------------------------------------------------
    {"key": "kick_beater_air", "name": "Kick · Beater & Air", "file": "Kick_Beater_Air",
     "mine": True,
     "role": "Keeps the kick a solid centre punch; only the click and air open up.",
     "p": _bw(0, 14, 42, 4.0, 118, 2950),
     "note": "Low is 0 on purpose and the low crossover sits at 118 Hz, so the "
             "thump is untouched and only the beater click and the top get "
             "any width."},
    {"key": "snare_crack_body", "name": "Snare · Crack & Body", "file": "Snare_Crack_and_Body",
     "mine": True,
     "role": "A snare with a little width in the crack and the body around it.",
     "p": _bw(18, 76, 58, 4.5, 196, 4980),
     "note": "Moderate everywhere: the snare should feel bigger, not move away "
             "from the centre."},
    {"key": "toms_wide_full", "name": "Toms · Wide & Full", "file": "Toms_Wide_and_Full",
     "mine": True,
     "role": "Toms that spread across the kit and keep their weight.",
     "p": _bw(78, 104, 68, 5.2, 128, 4180, -0.2),
     "note": "The low band is allowed to open here because a tom's weight is "
             "what makes a fill feel like it sweeps across the kit."},
    {"key": "drum_bus_glue", "name": "Drum Bus · Glue", "file": "Drum_Bus_Glue",
     "mine": True,
     "role": "A whisper of width over the whole kit - cohesion, not size.",
     "p": _bw(8, 44, 33, 4.5, 152, 4870),
     "note": "Meant for the drum BUS, one instance, after the kit is balanced."},
    {"key": "drum_room_wide", "name": "Drum Room / Overheads · Wide", "file": "Drum_Room_Wide",
     "mine": True,
     "role": "Room mics and overheads opened up for a big, wide kit.",
     "p": _bw(66, 158, 126, 5.8, 147, 5960, -0.3),
     "note": "Strong width for the ROOM channel only. Never on the close mics, "
             "or the kit stops being a kit."},
    {"key": "hihat_sparkle", "name": "Hi-Hat · Sparkle", "file": "Hihat_Sparkle",
     "role": "Hi-hat with a shimmer of width - no body to spread.",
     "p": _bw(0, 30, 90, 4.0, 600, 7000),
     "note": "A hi-hat is nearly all top, so only the High band is opened. If "
             "the hi-hat is panned, keep this modest: width on a panned part "
             "pulls it back towards the middle."},
    {"key": "ride_shimmer", "name": "Ride · Shimmer", "file": "Ride_Shimmer",
     "role": "A ride that blooms without losing its ping.",
     "p": _bw(0, 40, 100, 4.5, 500, 6500),
     "note": "A little more Mid than the hi-hat because a ride's bell and "
             "wash live lower."},
    {"key": "cymbals_overhead", "name": "Cymbals · Overhead Wide", "file": "Cymbals_Overhead_Wide",
     "role": "Crash and overhead cymbals spread across the picture.",
     "p": _bw(0, 60, 140, 5.0, 700, 6000, -0.2),
     "note": "Cymbals are the safest thing to make very wide - they have no "
             "centre-weight to lose. (The plug-in's own factory 'Cymbals and "
             "Hi Hats' preset is a good second opinion.)"},
    {"key": "perc_snap_wide", "name": "Percussion · Snap Wide", "file": "Percussion_Snap_Wide",
     "role": "Shakers, tambourine and small percussion spread wide.",
     "p": _bw(0, 90, 70, 4.5, 400, 5500),
     "note": "Small percussion is how a mix gets its width cheaply - but keep "
             "one element (usually the main shaker) closer to the middle."},
    {"key": "hand_drums_round", "name": "Hand Drums · Round", "file": "Hand_Drums_Round",
     "role": "Congas and bongos with width but a round, centred body.",
     "p": _bw(20, 80, 50, 4.5, 180, 4500),
     "note": "A touch of Low keeps the drum's shell resonance, which is what "
             "makes a conga sound like wood and skin."},
    # ---- BASS --------------------------------------------------------------
    {"key": "bass_top_only", "name": "Bass · Top Only", "file": "Bass_Top_Only",
     "role": "The low end stays dead centre; only the harmonics get a little width.",
     "p": _bw(0, 24, 18, 3.0, 250, 3000),
     "note": "Low is 0 and Strength is 3 - both straight from the manual's "
             "advice for bass. Everything below 250 Hz is left exactly as "
             "recorded, which is what keeps the mix solid on a club system or "
             "a phone.",
     "caution": "Do not raise Strength above 6 on a bass: it starts to move "
                "the L/R balance of the low end."},
    {"key": "bass_loop_harmonics", "name": "Bass Loop · Harmonics", "file": "Bass_Loop_Harmonics",
     "role": "A bass loop or synth bass: centred weight, wider upper harmonics.",
     "p": _bw(0, 40, 30, 3.5, 220, 3500),
     "note": "Slightly more width than the plucked bass because a synth-bass "
             "loop is rich in harmonics and a mono centre needs less of them "
             "to be audible.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    {"key": "double_bass_body", "name": "Double Bass · Body", "file": "Double_Bass_Body",
     "role": "An upright bass with a hint of room and the fundamental untouched.",
     "p": _bw(0, 30, 20, 3.0, 220, 3000),
     "note": "A double bass is a wooden box: the body sound is in the lower "
             "mids, which is where the small Mid amount goes. Low stays 0.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    # ---- GUITARS -----------------------------------------------------------
    {"key": "guitar_rhythm_wide", "name": "Rhythm Guitar · Wide", "file": "Guitar_Rhythm_Wide",
     "role": "A rhythm guitar that opens out, panned or doubled.",
     "p": _bw(10, 120, 80, 5.5, 250, 4500, -0.3),
     "note": "For a guitar that is meant to be a wall. If it is already hard "
             "panned left or right, use less - width on a hard-panned part "
             "mostly just drags it towards the centre."},
    {"key": "guitar_chords_open", "name": "Chord Guitar · Open", "file": "Guitar_Chords_Open",
     "role": "Chords and clean strums with a modest opening.",
     "p": _bw(6, 90, 70, 5.0, 250, 4500),
     "note": "A step narrower than the rhythm guitar so the two can sit "
             "together without the chord part dissolving."},
    {"key": "acoustic_bloom", "name": "Acoustic Guitar · Bloom", "file": "Acoustic_Guitar_Bloom",
     "role": "An acoustic guitar that blooms from the middle.",
     "p": _bw(0, 80, 90, 4.5, 220, 5000),
     "note": "Low is 0 so the body of the guitar stays put; the width is in the "
             "strum and the string shimmer, which is what you want to hear."},
    {"key": "guitar_lead_focus", "name": "Lead Guitar · Focus", "file": "Guitar_Lead_Focus",
     "role": "A lead guitar with a little air, still firmly in front.",
     "p": _bw(0, 30, 40, 4.0, 300, 4500),
     "note": "Like the lead vocal: the width only needs to be enough that it "
             "does not sound dry."},
    {"key": "guitar_low_tight", "name": "Single-Note Low Guitar · Tight", "file": "Guitar_Low_Tight",
     "role": "A low riff or single-note guitar that must stay tight.",
     "p": _bw(0, 24, 20, 3.5, 300, 3500),
     "note": "Treated like a bass: nothing below the low crossover is touched."},
    # ---- KEYS ---------------------------------------------------------------
    {"key": "organ_drawbar_warmth", "name": "Organ · Drawbar Warmth", "file": "Organ_Drawbar_Warmth",
     "mine": True,
     "role": "A warm organ with a little extra space.",
     "p": _bw(28, 87, 38, 5.0, 312, 4460),
     "note": "A mild setting; the body of the organ is left mostly central."},
    {"key": "organ_leslie_wide", "name": "Organ · Leslie Wide", "file": "Organ_Leslie_Wide",
     "mine": True,
     "role": "An organ opened out for the swirl of a rotary speaker.",
     "p": _bw(58, 152, 112, 6.0, 246, 5540, -0.3),
     "note": "Wide. Good for a held organ pad; too much for a busy organ lead."},
    {"key": "organ_melody_focus", "file": "Organ_Melody_Focus",
     "name": "Organ Melody \u00b7 Focus",
     "role": "An organ line or harmony: more width than the lead, less than the bed.",
     "p": _bw(14, 70, 52, 5.0, 280, 4600),
     "note": "Halfway between 'Organ \u00b7 Drawbar Warmth' and the Leslie-wide setting. A "
             "line among other lines wants some space around it, but not so much that "
             "it stops sounding like the organ is playing WITH the vocal."},
    {"key": "accordion_reeds_wide", "name": "Accordion · Reeds Wide", "file": "Accordion_Reeds_Wide",
     "role": "An accordion accompaniment with the reeds spread out.",
     "p": _bw(20, 120, 90, 5.0, 240, 4800),
     "note": "Accordion reeds are slightly out of tune with each other by "
             "design; widening them exaggerates that natural chorus."},
    {"key": "accordion_lead_focus", "name": "Accordion Lead · Focus", "file": "Accordion_Lead_Focus",
     "role": "An accordion playing the melody - present, not enormous.",
     "p": _bw(6, 50, 40, 4.5, 280, 4200),
     "note": "Less than the accompaniment setting so the melody stays in front."},
    {"key": "piano_bed_wide", "name": "Piano · Bed Wide", "file": "Piano_Bed_Wide",
     "role": "A piano that supports the song and fills the picture.",
     "p": _bw(14, 110, 90, 5.0, 200, 5000, -0.2),
     "note": "A real piano is already wide (low notes left, high notes right "
             "in most recordings). This widens the sound of each note, not "
             "the spread - check it is not smearing fast passages."},
    {"key": "piano_riff_focus", "name": "Piano Riff · Focus", "file": "Piano_Riff_Focus",
     "role": "A piano playing a riff or a lead line.",
     "p": _bw(4, 44, 40, 4.5, 220, 4800),
     "note": "Held back so the riff stays articulate."},
    # ---- WINDS & BRASS ------------------------------------------------------
    {"key": "flute_air", "name": "Flute · Air", "file": "Flute_Air",
     "role": "A solo flute with breath and room.",
     "p": _bw(0, 40, 60, 4.0, 350, 6000),
     "note": "Mostly top: the breath noise is the part that benefits from "
             "width."},
    {"key": "flute_bed_wide", "name": "Flute Background · Wide", "file": "Flute_Bed_Wide",
     "role": "Flutes and background winds spread behind the melody.",
     "p": _bw(0, 90, 110, 5.0, 350, 6500, -0.2),
     "note": "Backgrounds can take much more than leads."},
    {"key": "sax_body_wide", "name": "Saxophone · Body Wide", "file": "Sax_Body_Wide",
     "role": "A saxophone with warmth and a little spread.",
     "p": _bw(8, 60, 40, 4.5, 260, 4500),
     "note": "A solo sax is a lead voice - keep it moderate."},
    {"key": "harmonica_reed_wide", "name": "Harmonica · Reed Wide", "file": "Harmonica_Reed_Wide",
     "role": "A harmonica with the reeds opened out.",
     "p": _bw(0, 90, 70, 4.5, 300, 5000),
     "note": "Harmonica has no low end to protect, so Low is 0 and the "
             "width goes into the reeds."},
    {"key": "woodwind_section_wide", "name": "Woodwinds · Section Wide", "file": "Woodwind_Section_Wide",
     "role": "A woodwind section that fills the stage.",
     "p": _bw(6, 110, 80, 5.2, 260, 5000, -0.2),
     "note": "For several winds on one bus; one instance on the bus."},
    {"key": "brass_solo_presence", "name": "Brass Solo · Presence", "file": "Brass_Solo_Presence",
     "mine": True,
     "role": "A solo trumpet or trombone: a little width, still a lead.",
     "p": _bw(12, 52, 42, 5.0, 298, 4020),
     "note": "A solo brass voice should keep its centre."},
    {"key": "brass_stabs_punch", "name": "Brass Stabs · Punch", "file": "Brass_Stabs_Punch",
     "mine": True,
     "role": "Short brass hits that keep their punch.",
     "p": _bw(8, 88, 66, 4.0, 205, 4460),
     "note": "Lower Strength so the stab stays tight in time."},
    {"key": "brass_section_wide", "name": "Brass Section · Wide", "file": "Brass_Section_Wide",
     "mine": True,
     "role": "A whole brass section spread across the stage.",
     "p": _bw(22, 143, 104, 6.0, 241, 5120, -0.2),
     "note": "For the section BUS, one instance."},
    {"key": "clarinet_reed_focus", "name": "Clarinet · Reed Focus", "file": "Clarinet_Reed_Focus",
     "role": "A solo or section clarinet with a little air around the reed.",
     "p": _bw(0, 50, 50, 4.5, 280, 4500),
     "note": "Low is 0: the chalumeau register is where the clarinet's body is, "
             "and it stays central. The width goes into the reed's upper "
             "partials."},
    {"key": "oboe_reed_focus", "name": "Oboe · Reed Focus", "file": "Oboe_Reed_Focus",
     "role": "An oboe that stays a lead voice, with a hint of space.",
     "p": _bw(0, 30, 40, 4.0, 350, 5000),
     "note": "An oboe is a lead: the width only needs to be enough that it "
             "does not sound dry."},
    {"key": "bassoon_body_focus", "name": "Bassoon · Body Focus", "file": "Bassoon_Body_Focus",
     "role": "A bassoon whose weight stays central.",
     "p": _bw(0, 40, 24, 3.5, 200, 3500),
     "note": "Low stays 0 as for any low source; the width is in the reed "
             "colour above the crossover.",
     "caution": "Keep Strength under 6 on low sources (manual)."},
    {"key": "contrabassoon_foundation", "name": "Contrabassoon · Foundation", "file": "Contrabassoon_Foundation",
     "role": "The lowest woodwind: nothing below the crossover is touched.",
     "p": _bw(0, 16, 14, 3.0, 150, 2500),
     "note": "Treated like a bass: Low is 0 and Strength is 3. Only the reed "
             "buzz above 150 Hz gets a little width.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    {"key": "flugelhorn_mellow", "name": "Flugelhorn · Mellow", "file": "Flugelhorn_Mellow",
     "role": "A flugelhorn with a little width, still a lead.",
     "p": _bw(8, 44, 36, 4.5, 280, 4000),
     "note": "A solo flugelhorn keeps its centre; the width stays moderate "
             "because the tone is already round."},
    {"key": "french_horn_wide", "name": "French Horn · Wide", "file": "French_Horn_Wide",
     "role": "A French horn (or section) with the room that its backward-pointing bell creates.",
     "p": _bw(10, 70, 56, 5.0, 220, 4200),
     "note": "More than a trumpet: the horn's bell points away from the "
             "listener, so the tone is already diffuse and takes more width."},
    {"key": "tuba_foundation", "name": "Tuba · Foundation", "file": "Tuba_Foundation",
     "role": "A tuba as a bass line: nothing below the crossover is touched.",
     "p": _bw(0, 12, 12, 3.0, 150, 2500),
     "note": "Treated like a bass: Low is 0 and Strength is 3.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    {"key": "english_horn_reed_focus", "name": "English Horn · Reed Focus", "file": "English_Horn_Reed_Focus",
     "role": "An English horn with a little room, still a colour line.",
     "p": _bw(0, 40, 36, 4.0, 300, 4500),
     "note": "Like the oboe, a lead-ish voice - width only so it does not sound dry."},
    {"key": "euphonium_warm", "name": "Euphonium · Warm", "file": "Euphonium_Warm",
     "role": "A euphonium with a little width and a central body.",
     "p": _bw(6, 44, 30, 4.5, 240, 3800),
     "note": "A tenor brass line keeps its centre; the round tone needs little width."},
    {"key": "bass_clarinet_body", "name": "Bass Clarinet · Body", "file": "Bass_Clarinet_Body",
     "role": "A bass clarinet whose weight stays central.",
     "p": _bw(0, 40, 30, 4.0, 220, 3800),
     "note": "Low stays 0 as for any low source; the width is in the reed above the crossover.",
     "caution": "Keep Strength under 6 on low sources (manual)."},
    {"key": "contrabass_clarinet_foundation", "name": "Contrabass Clarinet · Foundation", "file": "Contrabass_Clarinet_Foundation",
     "role": "The lowest clarinet: nothing below the crossover is touched.",
     "p": _bw(0, 16, 14, 3.0, 150, 2500),
     "note": "Treated like a bass: Low is 0 and Strength is 3.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    {"key": "double_bass_section_body", "name": "Double Bass Section · Body", "file": "Double_Bass_Section_Body",
     "role": "A bass section with the fundamental untouched and a little breadth above it.",
     "p": _bw(0, 50, 30, 3.5, 220, 3200),
     "note": "A section is several players, so it can take more Mid than a solo bass; Low stays 0.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    {"key": "piccolo_air", "name": "Piccolo · Air", "file": "Piccolo_Air",
     "role": "A piccolo with breath and sparkle, never wider than it is bright.",
     "p": _bw(0, 20, 50, 3.5, 500, 6500),
     "note": "A piccolo is already piercing; the width goes to the breath on top."},
    {"key": "alto_flute_breath", "name": "Alto Flute · Breath", "file": "Alto_Flute_Breath",
     "role": "An alto flute with a little air and room.",
     "p": _bw(0, 36, 50, 4.0, 300, 5500),
     "note": "Mostly top: the breath noise is what benefits from width."},
    {"key": "bass_flute_breath", "name": "Bass Flute · Breath", "file": "Bass_Flute_Breath",
     "role": "A bass flute that keeps its weight in the centre.",
     "p": _bw(0, 30, 40, 3.5, 250, 5000),
     "note": "Low is 0: it is quiet and the body must stay put."},
    {"key": "soprano_sax_focus", "name": "Soprano Saxophone · Focus", "file": "Soprano_Sax_Focus",
     "role": "A soprano sax with a little spread, still a lead voice.",
     "p": _bw(4, 40, 36, 4.0, 300, 4500),
     "note": "A solo sax is a lead voice - keep it moderate."},
    {"key": "alto_sax_focus", "name": "Alto Saxophone · Focus", "file": "Alto_Sax_Focus",
     "role": "An alto sax with warmth and a little spread.",
     "p": _bw(6, 50, 40, 4.5, 280, 4500),
     "note": "A solo sax is a lead voice - keep it moderate."},
    {"key": "tenor_sax_focus", "name": "Tenor Saxophone · Focus", "file": "Tenor_Sax_Focus",
     "role": "A tenor sax with warmth and a little spread.",
     "p": _bw(8, 56, 40, 4.5, 260, 4500),
     "note": "A solo sax is a lead voice - keep it moderate."},
    {"key": "baritone_sax_body", "name": "Baritone Saxophone · Body", "file": "Baritone_Sax_Body",
     "role": "A baritone sax whose weight stays central.",
     "p": _bw(0, 40, 30, 4.0, 200, 3800),
     "note": "Low stays 0 as for any low source; the width is in the reed above the crossover.",
     "caution": "Keep Strength under 6 on low sources (manual)."},
    {"key": "piccolo_trumpet_bright", "name": "Piccolo Trumpet · Bright", "file": "Piccolo_Trumpet_Bright",
     "role": "A piccolo trumpet with a little width, still a lead.",
     "p": _bw(8, 40, 40, 4.5, 340, 4500),
     "note": "A solo brass voice should keep its centre."},
    {"key": "alto_trombone_presence", "name": "Alto Trombone · Presence", "file": "Alto_Trombone_Presence",
     "role": "An alto trombone with a little width, still a lead.",
     "p": _bw(10, 50, 40, 5.0, 290, 4000),
     "note": "A solo brass voice should keep its centre."},
    {"key": "tenor_trombone_presence", "name": "Tenor Trombone · Presence", "file": "Tenor_Trombone_Presence",
     "role": "A tenor trombone with a little width, still a lead or a horn-line voice.",
     "p": _bw(10, 50, 40, 5.0, 260, 3800),
     "note": "A solo brass voice should keep its centre."},
    {"key": "tenor_bass_trombone_presence", "name": "Tenor-Bass Trombone · Presence", "file": "Tenor_Bass_Trombone_Presence",
     "role": "A tenor-bass trombone with a little width, still a lead or a horn-line voice.",
     "p": _bw(8, 44, 34, 4.5, 230, 3600),
     "note": "A solo brass voice should keep its centre."},
    {"key": "bass_trombone_foundation", "name": "Bass Trombone · Foundation", "file": "Bass_Trombone_Foundation",
     "role": "A bass trombone as a bass line: nothing below the crossover is touched.",
     "p": _bw(0, 36, 24, 3.5, 180, 3200),
     "note": "Treated like a bass: Low is 0 and Strength stays under 6.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    {"key": "double_bass_trombone_foundation", "name": "Double Bass Trombone · Foundation", "file": "Double_Bass_Trombone_Foundation",
     "role": "A double-bass trombone as a bass line: nothing below the crossover is touched.",
     "p": _bw(0, 30, 20, 3.0, 150, 2800),
     "note": "Treated like a bass: Low is 0 and Strength stays under 6.",
     "caution": "Keep Strength under 6 on bass sounds (manual)."},
    # ---- SYNTHS -------------------------------------------------------------
    {"key": "synth_pad_huge", "name": "Synth Pad · Huge", "file": "Synth_Pad_Huge",
     "role": "A synth pad that surrounds the listener.",
     "p": _bw(20, 150, 140, 6.0, 260, 5500, -0.4),
     "note": "Pads are the source that benefits most from width and loses "
             "least. (The factory 'Synth Pad Clarity and Space' is a more "
             "polished alternative.)"},
    {"key": "synth_pluck_spread", "name": "Synth Pluck · Spread", "file": "Synth_Pluck_Spread",
     "role": "Plucks and arps with a wide, rhythmic spread.",
     "p": _bw(0, 110, 100, 5.0, 350, 5000),
     "note": "Low is 0: a pluck's attack is the part to keep centred and "
             "clear."},
    {"key": "mallet_shimmer", "name": "Mallets & Bells · Shimmer", "file": "Mallet_Shimmer",
     "role": "Vibraphone, marimba, bells and similar.",
     "p": _bw(0, 70, 110, 4.5, 400, 6000),
     "note": "The top of a mallet instrument is where the shimmer is."},
    # ---- STRINGS ------------------------------------------------------------
    {"key": "strings_solo_presence", "name": "Strings Solo · Presence", "file": "Strings_Solo_Presence",
     "mine": True,
     "role": "A solo violin or lead string: a little width, mostly presence.",
     "p": _bw(13, 48, 37, 5.0, 305, 3960),
     "note": "Keeps a solo string a lead, not a pad."},
    {"key": "strings_pizzicato", "name": "Strings · Pizzicato", "file": "Strings_Pizzicato",
     "mine": True,
     "role": "Plucked strings with tight, clear transients.",
     "p": _bw(17, 82, 63, 4.0, 248, 4530),
     "note": "Lower Strength so the plucks do not smear."},
    {"key": "strings_section_wide", "name": "Strings Section · Wide", "file": "Strings_Section_Wide",
     "mine": True,
     "role": "A full string section across the stage.",
     "p": _bw(48, 157, 118, 5.8, 213, 6080, -0.3),
     "note": "For the section BUS, one instance."},
    {"key": "violin_bed_wide", "name": "Violins Background · Wide", "file": "Violin_Bed_Wide",
     "role": "Background violins that fill the sides.",
     "p": _bw(20, 130, 100, 5.5, 240, 5500, -0.3),
     "note": "Wider than a solo violin because they are a texture."},
    {"key": "viola_warm_wide", "name": "Viola · Warm Wide", "file": "Viola_Warm_Wide",
     "role": "Viola in the middle of the section, warm and slightly wide.",
     "p": _bw(14, 90, 60, 5.0, 240, 4500),
     "note": "Less top than the violins: a viola's character is its warmth."},
    {"key": "cello_body_wide", "name": "Cello · Body Wide", "file": "Cello_Body_Wide",
     "role": "A cello whose weight stays central.",
     "p": _bw(0, 56, 40, 4.5, 200, 3500),
     "note": "A cello is mostly low-mid energy: Low stays 0, and Strength "
             "stays under 5 as for any low string.",
     "caution": "Keep Strength under 6 on low sources (manual)."},
    # ---- GENERAL -------------------------------------------------------------
    {"key": "mono_source_open", "name": "Mono Source · Open It Up", "file": "Mono_Source_Open",
     "role": "Any mono recording that needs to become a stereo picture.",
     "p": _bw(0, 100, 80, 5.0, 300, 5000, -0.2),
     "note": "Use this for a mono sample, an old mono recording, or a DI. "
             "Bandwidth works on mono sources too; the width is synthesised."},
    {"key": "mix_bus_subtle", "name": "Mix Bus · Subtle", "file": "Mix_Bus_Subtle",
     "role": "A few percent of extra width over the whole mix, for finishing.",
     "p": _bw(0, 20, 25, 3.5, 150, 5000),
     "note": "One instance, at the end of the chain. The low band is 0 so the "
             "kick and bass stay mono and the mix still collapses cleanly.",
     "caution": "Do NOT stack this on top of bus presets that already widen."},
]

def preset_file_name(name):
    """The file name of a preset = the name this program shows, so what you read in
    EQ Cheat Sheet is what you look for in the plug-in's browser. ' \u00b7 ' becomes
    ' - ' and characters Windows does not allow in a file name are dropped."""
    s = name.replace(" \u00b7 ", " - ").replace("/", "-")
    s = _re.sub(r'[<>:"|?*\\]', "", s)
    return " ".join(s.split())


# Until 2026-10-20 the files were named differently from what the program shows
# (Kick_Beater_Air for 'Kick \u00b7 Beater & Air'; Swedish names for Cascadia). Keep
# the old name only to point out leftovers in the folder - see the reports.
for _p in BANDWIDTH_PRESETS:
    _p["old_file"] = _p["file"]
    _p["file"] = preset_file_name(_p["name"])

BANDWIDTH_BY_KEY = {p["key"]: p for p in BANDWIDTH_PRESETS}

# Which preset each channel starts on. Every instrument gets one.
BANDWIDTH_FOR = {
    "vocals_lead":       "vocal_lead_air",
    "vocals_backing":    "vocal_backing_wide",
    "vocals_choir_pad":  "vocal_choir_huge",
    "vocals_extra":      "vocal_harmony_open",
    "kick":              "kick_beater_air",
    "snare":             "snare_crack_body",
    "hihat":             "hihat_sparkle",
    "ride":              "ride_shimmer",
    "cymbals":           "cymbals_overhead",
    "toms":              "toms_wide_full",
    "percussion":        "perc_snap_wide",
    "hand_drums":        "hand_drums_round",
    "bass_root":         "bass_top_only",
    "bass_loop":         "bass_loop_harmonics",
    "guitar_chords":     "guitar_chords_open",
    "guitar_rhythm":     "guitar_rhythm_wide",
    "guitar_acoustic":   "acoustic_bloom",
    "guitar_lead":       "guitar_lead_focus",
    "guitar_single_low": "guitar_low_tight",
    "organ":             "organ_drawbar_warmth",
    "organ_lead":        "organ_drawbar_warmth",
    "organ_melody":      "organ_melody_focus",
    "accordion":         "accordion_reeds_wide",
    "accordion_lead":    "accordion_lead_focus",
    "piano_bg":          "piano_bed_wide",
    "piano_riff":        "piano_riff_focus",
    "flute":             "flute_air",
    "flute_bg":          "flute_bed_wide",
    "brass":             "brass_stabs_punch",
    "brass_lead":        "brass_solo_presence",
    "trumpet":           "brass_solo_presence",
    "trombone":          "brass_solo_presence",
    "tenor_trombone":          "tenor_trombone_presence",
    "tenor_bass_trombone":          "tenor_bass_trombone_presence",
    "saxophone":         "sax_body_wide",
    "horn_section":      "brass_section_wide",
    "harmonica":         "harmonica_reed_wide",
    "woodwind":          "woodwind_section_wide",
    "clarinet":          "clarinet_reed_focus",
    "oboe":              "oboe_reed_focus",
    "bassoon":           "bassoon_body_focus",
    "contrabassoon":     "contrabassoon_foundation",
    "flugelhorn":        "flugelhorn_mellow",
    "french_horn":       "french_horn_wide",
    "tuba":              "tuba_foundation",
    "english_horn":      "english_horn_reed_focus",
    "euphonium":         "euphonium_warm",
    "bass_clarinet":     "bass_clarinet_body",
    "contrabass_clarinet": "contrabass_clarinet_foundation",
    "double_bass_section": "double_bass_section_body",
    "piccolo": "piccolo_air",
    "alto_flute": "alto_flute_breath",
    "bass_flute": "bass_flute_breath",
    "soprano_sax": "soprano_sax_focus",
    "alto_sax": "alto_sax_focus",
    "tenor_sax": "tenor_sax_focus",
    "baritone_sax": "baritone_sax_body",
    "piccolo_trumpet": "piccolo_trumpet_bright",
    "alto_trombone": "alto_trombone_presence",
    "bass_trombone": "bass_trombone_foundation",
    "double_bass_trombone": "double_bass_trombone_foundation",
    "synth_pad":         "synth_pad_huge",
    "synth_pluck":       "synth_pluck_spread",
    "synth_mallet":      "mallet_shimmer",
    "violin":            "strings_solo_presence",
    "violin_bg":         "violin_bed_wide",
    "viola":             "viola_warm_wide",
    "viola_front":       "strings_solo_presence",
    "cello":             "cello_body_wide",
    "double_bass":       "double_bass_body",
    "string_section":    "strings_section_wide",
    "strings_lead":      "strings_solo_presence",
}

# The other setting worth knowing about per channel.
BANDWIDTH_ALSO = {
    "vocals_lead":       ["mono_source_open"],
    "vocals_backing":    ["vocal_harmony_open"],
    "vocals_extra":      ["vocal_backing_wide"],
    "snare":             ["drum_bus_glue"],
    "toms":              ["drum_room_wide"],
    "hihat":             ["cymbals_overhead"],
    "cymbals":           ["ride_shimmer"],
    "percussion":        ["hand_drums_round"],
    "hand_drums":        ["perc_snap_wide"],
    "guitar_rhythm":     ["guitar_chords_open"],
    "guitar_chords":     ["guitar_rhythm_wide"],
    "guitar_acoustic":   ["guitar_chords_open"],
    "organ":             ["organ_leslie_wide"],
    "organ_lead":        ["organ_leslie_wide"],
    "organ_melody":      ["organ_drawbar_warmth", "organ_leslie_wide"],
    "accordion":         ["accordion_lead_focus"],
    "piano_bg":          ["piano_riff_focus"],
    "piano_riff":        ["piano_bed_wide"],
    "brass":             ["brass_section_wide"],
    "horn_section":      ["brass_stabs_punch"],
    "trumpet":           ["brass_stabs_punch"],
    "trombone":          ["brass_stabs_punch"],
    "tenor_trombone":          ["brass_stabs_punch"],
    "tenor_bass_trombone":          ["brass_stabs_punch"],
    "violin":            ["strings_pizzicato"],
    "violin_bg":         ["strings_section_wide"],
    "strings_lead":      ["strings_pizzicato"],
    "string_section":    ["strings_pizzicato"],
    "cello":             ["strings_solo_presence"],
    "synth_pad":         ["vocal_choir_huge"],
    "synth_pluck":       ["mono_source_open"],
    "flute":             ["flute_bed_wide"],
}


def bandwidth_for(iid):
    """(preset, alternatives) for an instrument, or (None, [])."""
    key = BANDWIDTH_FOR.get(iid)
    if not key or key not in BANDWIDTH_BY_KEY:
        return None, []
    alts = [BANDWIDTH_BY_KEY[k] for k in BANDWIDTH_ALSO.get(iid, [])
            if k in BANDWIDTH_BY_KEY]
    return BANDWIDTH_BY_KEY[key], alts


def bandwidth_clamp(short, value):
    """Keep a number inside the bounds kept for it (see BANDWIDTH_RANGE)."""
    spec = BANDWIDTH_RANGE.get(short)
    if not spec:
        return float(value)
    return max(spec[2], min(spec[3], float(value)))


def bandwidth_params(preset):
    """{xml id: value} — everything one preset writes, clamped. The crossovers
    are kept in order (the low cross can never end up above the high cross)."""
    out = dict(BANDWIDTH_BASE)
    p = preset["p"]
    vals = {k: bandwidth_clamp(k, p[k]) for k in BANDWIDTH_RANGE}
    if vals["x1"] >= vals["x2"]:
        vals["x1"] = min(vals["x1"], vals["x2"] * 0.5)
    for short, (pid, _lab, _lo, _hi) in BANDWIDTH_RANGE.items():
        out[pid] = vals[short]
    return out


def _bw_hz(hz):
    hz = float(hz)
    return ("%g kHz" % round(hz / 1000.0, 2)) if hz >= 1000 else ("%g Hz" % round(hz))


def bandwidth_head(preset):
    """'↔ Bandwidth: Lead Vocal · Air Only — Low 0 % · Mid 18 % · High 34 %
    · Strength 3.5'."""
    if not preset:
        return ""
    p = preset["p"]
    bits = ["Low %g %%" % round(p["low"]), "Mid %g %%" % round(p["mid"]),
            "High %g %%" % round(p["high"]), "Strength %g" % p["strength"]]
    return "\u2194 Bandwidth: %s  \u2014  %s" % (preset["name"], "  \u00b7  ".join(bits))


def bandwidth_detail(preset):
    """The rest of the panel, as one line. All settings, so never hidden."""
    if not preset:
        return ""
    p = preset["p"]
    bits = ["Crossovers %s / %s" % (_bw_hz(p["x1"]), _bw_hz(p["x2"]))]
    if p["out"]:
        bits.append("Output %+g dB" % p["out"])
    bits.append("Monitor STEREO")
    return "  \u00b7  ".join(bits)


def bandwidth_issues(preset):
    """Sanity check on a preset against the plug-in manual's own advice. Returns
    short strings; [] means clean. Used as a self-test of the table above."""
    p = preset["p"]
    out = []
    if p["strength"] > 6 and p["low"] > 0:
        out.append("Strength above 6 with the Low band widened")
    if p["x1"] >= p["x2"]:
        out.append("low crossover is not below the high crossover")
    for k in ("low", "mid", "high"):
        if not 0 <= p[k] <= 200:
            out.append("%s is outside 0-200 %%" % k)
    return out


# ---- THE PRESET WRITER -----------------------------------------------------
# Byte-for-byte what the plug-in itself saves: UTF-8 without BOM, CRLF line
# ends, one blank line after the XML declaration, a trailing CRLF. Verified
# against all 13 hand-made presets (see bandwidth_selftest()).

def _bw_fmt(v):
    s = ("%.4f" % float(v)).rstrip("0")
    return s + "0" if s.endswith(".") else s


def make_bandwidth_preset(params):
    """`.itmpreset` bytes for a {xml id: value} dict from bandwidth_params()."""
    lines = ['<?xml version="1.0" encoding="UTF-8"?>', "",
             "<inthemix_bandwidth>"]
    for pid in sorted(params):
        lines.append('  <PARAM id="%s" value="%s"/>' % (pid, _bw_fmt(params[pid])))
    lines.append('  <PARAM id="additional_data" preset_version="1.0.0"/>')
    lines.append("</inthemix_bandwidth>")
    return ("\r\n".join(lines) + "\r\n").encode("utf-8")


def read_bandwidth_values(data):
    """{xml id: float} read back out of an .itmpreset — used to verify a write."""
    try:
        text = data.decode("utf-8", "replace")
        if "<inthemix_bandwidth" not in text:
            return None
        return {m.group(1): float(m.group(2)) for m in
                _re.finditer(r'<PARAM\s+id="(param[A-Za-z0-9]+)"\s+value="([^"]*)"\s*/>',
                             text)}
    except Exception:
        return None


def bandwidth_selftest():
    """[] when every preset in the table survives write -> read and respects the
    manual's rules; otherwise a list of problems. Cheap enough to run on demand."""
    bad = []
    seen_files = set()
    for pr in BANDWIDTH_PRESETS:
        if pr["file"] in seen_files:
            bad.append("%s: duplicate file name" % pr["key"])
        seen_files.add(pr["file"])
        for msg in bandwidth_issues(pr):
            bad.append("%s: %s" % (pr["key"], msg))
        want = bandwidth_params(pr)
        back = read_bandwidth_values(make_bandwidth_preset(want))
        if not back or any(abs(back.get(k, 1e9) - v) > 1e-4 for k, v in want.items()):
            bad.append("%s: does not survive a round trip" % pr["key"])
    for iid, key in BANDWIDTH_FOR.items():
        if key not in BANDWIDTH_BY_KEY:
            bad.append("%s: unknown preset %s" % (iid, key))
    return bad


# *************** DEL 02r - CASCADIA DELAY (iZotope) *************************
# iZotope "Cascadia" - a delay with an "unmask" processor that ducks the echo
# wherever the dry signal needs the room. In this program it is a SEND at the end
# of the chain: rhythmic echo and movement, never size (a delay cannot be a hall;
# depth comes from a reverb send - see the plug-in library notes).
#
# THE FILE, decoded from the user's own saved preset ('radera-cascadia') and from
# the factory presets, so nothing below is a guess about the container:
#
#   *.vstpreset =  "VST3" + version + 32-byte class id + u64 list offset   (48 bytes)
#                  Comp chunk = u32 20240507 | u32 0 | u32 (zlib bytes + 4)
#                               | u32 JSON length | zlib(JSON, level 6)
#                  Info chunk = the Steinberg MetaInfo XML (copied from a template)
#                  List       = 'List' + 3 entries (Comp / Cont / Info)
#   The JSON is the plug-in's own state: "Context State" (current preset name,
#   analytics ids, window size) and "DSP State" > "DSP Elements" > "Cascadia"
#   with 20 typed values. Rebuilding the user's own file from its own JSON gives
#   the SAME BYTES, so the writer below is exact - checked in cascadia_selftest().
#
# WHAT IS KNOWN AND WHAT IS NOT - said plainly:
#   * Every parameter name, type and the whole container: exact.
#   * Ranges are NOT published; the bounds in CASCADIA_RANGE sit just around what
#     the 57 factory presets prove legal.
#   * TEMPO SYNC: with Tempo Sync ON the plug-in ignores Delay Time (ms) and uses
#     an index into its note-value list. Only ONE index is confirmed: 7 = 1/8
#     (the factory 'Basic Delay'). Presets carried over from the user's first set
#     keep their original index (4 / 6 / 9) exactly as they were; every NEW preset
#     either uses 7 or switches Tempo Sync OFF and states a time in ms.
#
# ToDo: save a Cascadia preset for each note value (1/4, 1/8., 1/16 ...) and add
# its index to CASCADIA_SYNC_KNOWN; then the unconfirmed presets can be pinned down.

import json as _json
import zlib as _zlib

CASCADIA_COLOUR = "#c9a8ff"      # soft violet - echo, apart from the reverb blues
CASCADIA_NAME   = "Cascadia"
CASCADIA_VENDOR = "iZotope"

# short key -> JSON key inside DSP Elements > Cascadia, and its JSON "Type".
CASCADIA_KEYS = {
    "amount":    ("DelayAmount",           "Float"),
    "feedback":  ("DelayFeedback",         "Float"),
    "mod_depth": ("DelayModDepth",         "Float"),
    "mod_rate":  ("DelayModRate",          "Float"),
    "pingpong":  ("DelayPingPongEnable",   "Bool"),
    "reverse":   ("DelayReverseEnable",    "Bool"),
    "sync":      ("DelayTempoSyncEnable",  "Bool"),
    "time_ms":   ("DelayTime",             "Float"),
    "sync_idx":  ("DelayTimeTempoSynced",  "UInt"),
    "width":     ("DelayWidth",            "Float"),
    "hp":        ("FinalHighPassFrequency", "Float"),
    "lp":        ("FinalLowPassFrequency", "Float"),
    "u_amount":  ("UnmaskAmount",          "Float"),
    "u_attack":  ("UnmaskAttack",          "Float"),
    "u_delta":   ("UnmaskDelta",           "Bool"),
    "u_power":   ("UnmaskPower",           "Bool"),
    "u_release": ("UnmaskRelease",         "Float"),
    "u_sens":    ("UnmaskSensitivity",     "Float"),
}
# lo, hi - a safety net around what the factory presets use, not the plug-in's table.
CASCADIA_RANGE = {
    "amount": (0.0, 100.0), "feedback": (0.0, 95.0), "mod_depth": (0.0, 100.0),
    "mod_rate": (0.1, 10.0), "time_ms": (1.0, 1000.0), "width": (0.0, 200.0),
    "hp": (20.0, 1500.0), "lp": (100.0, 20000.0),
    "u_amount": (0.0, 100.0), "u_attack": (0.0, 100.0),
    "u_release": (10.0, 1000.0), "u_sens": (0.0, 100.0),
}
CASCADIA_SYNC_KNOWN = {7: "1/8"}        # the only confirmed note-value index

CASCADIA_BASE = {
    "amount": 30.0, "feedback": 30.0, "mod_depth": 10.0, "mod_rate": 1.0,
    "pingpong": False, "reverse": False, "sync": False, "time_ms": 250.0,
    "sync_idx": 7, "width": 100.0, "hp": 250.0, "lp": 5000.0,
    "u_amount": 20.0, "u_attack": 10.0, "u_delta": False, "u_power": True,
    "u_release": 300.0, "u_sens": 50.0,
}


def _cc(**kw):
    out = dict(CASCADIA_BASE)
    out.update(kw)
    return out


# ---------------------------------------------------------------------------
# THE PRESETS. Each entry: key · name (English, as shown here) · file (the
# .vstpreset name, no extension) · role · p · note · optional caution.
# `mine` marks the 15 presets the user made on 2026-07-26: kept value for value.
# Their file names are now the English names shown here (until 2026-10-20 they
# kept the original Swedish ones - see `old_file`). Their `sync_idx` values are the originals.
#
# House rules: it is a SEND, so Amount is the send level and stays modest (15-35);
# anything with low end gets a Low cut (hp) well above the bass; the Unmask
# processor is the reason a dense part can take an echo at all, so it is raised
# on busy parts and lowered on pads; Feedback stays low on leads and rises on
# pads and effects.
# ---------------------------------------------------------------------------
CASCADIA_PRESETS = [
    # ---- the user's own 15 -------------------------------------------------
    {"key": "all_huge_room", "mine": True, "file": "Allt – Massivt Rummet Ekar",
     "name": "Everything · Huge Echoing Room",
     "role": "A big, long, ping-ponging echo for a part that is allowed to ring out.",
     "p": _cc(amount=35.0, feedback=70.0, mod_depth=20.0, mod_rate=0.7, pingpong=True,
              sync=True, time_ms=500.0, sync_idx=9, width=100.0, hp=150.0, lp=4000.0,
              u_amount=18.0, u_attack=15.0, u_release=500.0, u_sens=40.0),
     "note": "70 % feedback is a LOT of repeats - use it on one send for a "
             "spot effect (a held chord, a final hit), not on a channel that "
             "plays all the way through."},
    {"key": "all_subtle_depth", "mine": True, "file": "Allt – Subtilt Djup",
     "name": "Everything · Subtle Depth",
     "role": "The all-round gentle send: a quiet eighth-note echo under almost anything.",
     "p": _cc(amount=20.0, feedback=20.0, mod_depth=8.0, mod_rate=1.0, sync=True,
              time_ms=250.0, sync_idx=7, width=70.0, hp=250.0, lp=5500.0,
              u_amount=22.0, u_attack=10.0, u_release=300.0, u_sens=50.0),
     "note": "The safest preset in the list: if you cannot decide, this one. "
             "It is also the one for a whole bus."},
    {"key": "bass_solo_pulse", "mine": True, "file": "Basgitarr Solo – Ekopuls",
     "name": "Bass Guitar Solo · Echo Pulse",
     "role": "An echo for a bass SOLO only: tight, high-passed, ducked hard.",
     "p": _cc(amount=18.0, feedback=30.0, mod_depth=6.0, mod_rate=0.5, sync=True,
              time_ms=187.0, sync_idx=6, width=50.0, hp=400.0, lp=3000.0,
              u_amount=35.0, u_attack=5.0, u_release=200.0, u_sens=65.0),
     "caution": "Only for a bass SOLO. On a bass that plays the song, any delay "
                "smears the low end - keep it dry."},
    {"key": "brass_concert_hall", "mine": True, "file": "Blas – Eko i Konserthall",
     "name": "Brass & Winds · Concert-Hall Echo",
     "role": "Horns and winds with a slow, hall-like echo.",
     "p": _cc(amount=22.0, feedback=28.0, mod_depth=7.0, mod_rate=0.6, sync=True,
              time_ms=375.0, sync_idx=7, width=85.0, hp=250.0, lp=7000.0,
              u_amount=22.0, u_attack=8.0, u_release=350.0, u_sens=50.0),
     "note": "The 375 ms figure stored in the file is ignored while Tempo Sync "
             "is on - the echo runs at the 1/8 note."},
    {"key": "guitar_pingpong_wide", "mine": True, "file": "Gitarr – Ping Pong Bred",
     "name": "Guitar · Wide Ping-Pong",
     "role": "A guitar whose echoes bounce left and right.",
     "p": _cc(amount=22.0, feedback=45.0, mod_depth=8.0, mod_rate=1.2, pingpong=True,
              sync=True, time_ms=250.0, sync_idx=7, width=100.0, hp=220.0, lp=5000.0,
              u_amount=20.0, u_attack=10.0, u_release=300.0, u_sens=50.0)},
    {"key": "guitar_space_depth", "mine": True, "file": "Gitarr – Rymd och Djup",
     "name": "Guitar · Space and Depth",
     "role": "A lead or featured guitar with an echo that opens the space behind it.",
     "p": _cc(amount=25.0, feedback=35.0, mod_depth=12.0, mod_rate=1.5, sync=True,
              time_ms=375.0, sync_idx=7, width=100.0, hp=180.0, lp=4500.0,
              u_amount=18.0, u_attack=12.0, u_release=350.0, u_sens=45.0)},
    {"key": "guitar_bounce_fades", "mine": True, "file": "Gitarr – Studs som Dor Ut",
     "name": "Guitar · Bounce That Dies Away",
     "role": "Rhythm guitar with a long, fading tail of repeats.",
     "p": _cc(amount=20.0, feedback=65.0, mod_depth=15.0, mod_rate=0.8, sync=True,
              time_ms=375.0, sync_idx=7, width=80.0, hp=150.0, lp=3500.0,
              u_amount=15.0, u_attack=15.0, u_release=400.0, u_sens=40.0),
     "note": "The low pass at 3.5 kHz is what makes each repeat darker than the "
             "last, so the tail fades away instead of piling up."},
    {"key": "organ_rotating_space", "mine": True, "file": "Orgel – Roterande Rymd",
     "name": "Organ · Rotating Space",
     "role": "An organ whose echoes swirl, like a rotary speaker in a room.",
     "p": _cc(amount=28.0, feedback=40.0, mod_depth=25.0, mod_rate=3.5, pingpong=True,
              sync=True, time_ms=250.0, sync_idx=7, width=100.0, hp=120.0, lp=6000.0,
              u_amount=20.0, u_attack=10.0, u_release=300.0, u_sens=50.0)},
    {"key": "vocal_air_behind", "mine": True, "file": "Sang – Luft Bakom Rosten",
     "name": "Vocal · Air Behind the Voice",
     "role": "A short, quiet echo that gives a vocal air without being heard as an echo.",
     "p": _cc(amount=30.0, feedback=15.0, mod_depth=5.0, mod_rate=1.0, sync=True,
              time_ms=120.0, sync_idx=4, width=60.0, hp=300.0, lp=8000.0,
              u_amount=25.0, u_attack=8.0, u_release=250.0, u_sens=55.0)},
    {"key": "vocal_slapback_punch", "mine": True, "file": "Sang – Slapback Punch",
     "name": "Vocal · Slapback Punch",
     "role": "A single 85 ms slap with no repeats - thickens a vocal.",
     "p": _cc(amount=20.0, feedback=0.0, mod_depth=3.0, mod_rate=0.8, sync=False,
              time_ms=85.0, sync_idx=4, width=40.0, hp=200.0, lp=6000.0,
              u_amount=30.0, u_attack=5.0, u_release=200.0, u_sens=60.0),
     "note": "Free time (Tempo Sync off), so 85 ms is exact whatever the "
             "tempo is."},
    {"key": "strings_flow_float", "mine": True, "file": "Strangar – Flodar och Svavar",
     "name": "Strings · Flowing and Floating",
     "role": "Strings in a slow, wide, drifting echo - kept quiet so the instrument stays clear.",
     # v3.37: was amount 30 / feedback 55 / ping-pong / lp 8000 / unmask 15 - far too many bouncing repeats
     # (the instrument was hard to hear). Same name; the echo is now a few soft, dark repeats that duck
     # while the instrument plays (unmask up) and bloom in the gaps.
     "p": _cc(amount=18.0, feedback=20.0, mod_depth=10.0, mod_rate=0.5, pingpong=False,
              sync=True, time_ms=500.0, sync_idx=9, width=100.0, hp=220.0, lp=6000.0,
              u_amount=35.0, u_attack=10.0, u_release=350.0, u_sens=55.0),
     "note": "Toned down in v3.37: no ping-pong, 20 % feedback (was 55), Amount 18 (was 30), a darker "
             "6 kHz low pass and more Unmask, so the echo steps back while the instrument plays. "
             "Presets made before that keep the old, wetter sound until they are made again."},
    {"key": "synth_reversed_mystery", "mine": True, "file": "Synth – Omvant Mystiskt",
     "name": "Synth · Reversed Mystery",
     "role": "A synth with REVERSED echoes - the repeat swells into the next note.",
     "p": _cc(amount=28.0, feedback=40.0, mod_depth=18.0, mod_rate=1.0, reverse=True,
              sync=True, time_ms=375.0, sync_idx=7, width=90.0, hp=200.0, lp=7000.0,
              u_amount=20.0, u_attack=10.0, u_release=350.0, u_sens=45.0)},
    {"key": "synth_plucks_bounce", "mine": True, "file": "Synth-Plopp – Studsande Punkter",
     "name": "Synth Plucks · Bouncing Dots",
     "role": "Plucks and arps whose echoes bounce between the sides.",
     "p": _cc(amount=25.0, feedback=50.0, mod_depth=15.0, mod_rate=2.5, pingpong=True,
              sync=True, time_ms=187.0, sync_idx=6, width=100.0, hp=200.0, lp=9000.0,
              u_amount=25.0, u_attack=6.0, u_release=250.0, u_sens=55.0)},
    {"key": "drums_snare_rumble", "mine": True, "file": "Trummor – Snare Rumble",
     "name": "Drums · Snare Rumble",
     "role": "A short, high-passed, heavily ducked echo that adds a rumble behind the snare.",
     "p": _cc(amount=15.0, feedback=20.0, mod_depth=4.0, mod_rate=2.0, sync=True,
              time_ms=125.0, sync_idx=4, width=70.0, hp=500.0, lp=6000.0,
              u_amount=40.0, u_attack=3.0, u_release=150.0, u_sens=70.0)},
    {"key": "drums_half_echo", "mine": True, "file": "Trummor – Stomt Halveko",
     "name": "Drums · Half-Note Echo",
     "role": "A slow echo for a drum FILL or a single hit, ducked so the kit stays clear.",
     "p": _cc(amount=20.0, feedback=25.0, mod_depth=8.0, mod_rate=1.8, pingpong=True,
              sync=True, time_ms=500.0, sync_idx=9, width=90.0, hp=400.0, lp=7000.0,
              u_amount=35.0, u_attack=4.0, u_release=180.0, u_sens=65.0)},
    # ---- NEW, for the channels the first 15 did not cover -----------------
    {"key": "lead_vocal_eighth", "file": "Lead Vocal – Eighth Echo",
     "name": "Lead Vocal · Eighth-Note Echo",
     "role": "A quiet eighth-note echo that only appears in the gaps between phrases.",
     "p": _cc(amount=17.0, feedback=22.0, mod_depth=6.0, mod_rate=0.8, sync=True,
              sync_idx=7, width=80.0, hp=300.0, lp=5500.0,
              u_amount=32.0, u_attack=8.0, u_release=300.0, u_sens=55.0),
     "note": "Unmask is raised so the echo ducks while the voice is singing and "
             "blooms after the word - the voice stays in front."},
    {"key": "lead_vocal_eighth_alone", "file": "Lead Vocal – Eighth Echo (alone)",
     "name": "Lead Vocal · Eighth-Note Echo (alone)",
     "role": "The eighth-note echo for a lead with NO backing vocals: a little more of it.",
     "p": _cc(amount=24.0, feedback=30.0, mod_depth=8.0, mod_rate=0.8, sync=True,
              sync_idx=7, width=90.0, hp=300.0, lp=5500.0,
              u_amount=28.0, u_attack=8.0, u_release=300.0, u_sens=55.0),
     "note": "+7 Amount and +8 Feedback against the one used with backing vocals. "
             "Unmask is a little lower, because a lone voice leaves bigger gaps for "
             "the echo to bloom into."},
    {"key": "backing_soft_wash", "file": "Backing Vocals – Soft Wash",
     "name": "Backing Vocals · Soft Wash",
     "role": "Backing vocals in a short, wide wash that sits behind the lead.",
     "p": _cc(amount=22.0, feedback=28.0, mod_depth=12.0, mod_rate=1.2, sync=False,
              time_ms=180.0, width=150.0, hp=300.0, lp=5500.0,
              u_amount=25.0, u_attack=10.0, u_release=300.0, u_sens=50.0),
     "note": "Free time, so it does not turn into a rhythm of its own."},
    {"key": "choir_slow_bloom", "file": "Choir – Slow Bloom",
     "name": "Choir / Vocal Pad · Slow Bloom",
     "role": "A choir or vocal pad that opens slowly into a wide, long echo.",
     "p": _cc(amount=26.0, feedback=48.0, mod_depth=20.0, mod_rate=0.5, sync=False,
              time_ms=420.0, width=180.0, hp=200.0, lp=6500.0,
              u_amount=15.0, u_attack=20.0, u_release=500.0, u_sens=35.0),
     "note": "Unmask is low because a pad has gaps nowhere - ducking it would "
             "only make it pump."},
    {"key": "extra_vocals_pingpong", "file": "Extra Vocals – Light Ping-Pong",
     "name": "Extra Vocals · Light Ping-Pong",
     "role": "Ad-libs and extra lines that answer from the sides.",
     "p": _cc(amount=20.0, feedback=30.0, mod_depth=8.0, mod_rate=1.0, pingpong=True,
              sync=True, sync_idx=7, width=120.0, hp=300.0, lp=6000.0,
              u_amount=28.0, u_attack=8.0, u_release=300.0, u_sens=50.0)},
    {"key": "toms_short_slap", "file": "Toms – Short Slap",
     "name": "Toms · Short Slap",
     "role": "A very short echo that makes the toms bigger without muddying the kit.",
     "p": _cc(amount=14.0, feedback=12.0, mod_depth=4.0, mod_rate=1.5, sync=False,
              time_ms=90.0, width=80.0, hp=400.0, lp=6000.0,
              u_amount=38.0, u_attack=4.0, u_release=180.0, u_sens=65.0)},
    {"key": "perc_tight_pingpong", "file": "Percussion – Tight Ping-Pong",
     "name": "Percussion · Tight Ping-Pong",
     "role": "Shakers and small percussion bouncing between the sides.",
     "p": _cc(amount=18.0, feedback=28.0, mod_depth=6.0, mod_rate=1.5, pingpong=True,
              sync=True, sync_idx=7, width=110.0, hp=500.0, lp=8000.0,
              u_amount=30.0, u_attack=5.0, u_release=200.0, u_sens=60.0)},
    {"key": "hand_drums_warm", "file": "Hand Drums – Warm Echo",
     "name": "Hand Drums · Warm Echo",
     "role": "Congas and bongos with a warm, short echo.",
     "p": _cc(amount=18.0, feedback=25.0, mod_depth=8.0, mod_rate=1.0, sync=False,
              time_ms=160.0, width=90.0, hp=250.0, lp=4500.0,
              u_amount=28.0, u_attack=6.0, u_release=250.0, u_sens=55.0)},
    {"key": "guitar_lead_singing", "file": "Guitar Lead – Singing Echo",
     "name": "Guitar Lead · Singing Echo",
     "role": "A lead guitar with a longer echo that sustains the notes.",
     "p": _cc(amount=28.0, feedback=40.0, mod_depth=10.0, mod_rate=1.0, sync=True,
              sync_idx=7, width=100.0, hp=200.0, lp=5000.0,
              u_amount=35.0, u_attack=10.0, u_release=350.0, u_sens=55.0),
     "note": "Raised Unmask keeps the echo out of the way during the phrase and "
             "lets it bloom into the gaps."},
    {"key": "piano_gentle_echo", "file": "Piano – Gentle Echo",
     "name": "Piano · Gentle Echo",
     "role": "A piano riff with a soft eighth-note echo.",
     "p": _cc(amount=17.0, feedback=24.0, mod_depth=6.0, mod_rate=0.8, sync=True,
              sync_idx=7, width=90.0, hp=300.0, lp=6000.0,
              u_amount=30.0, u_attack=8.0, u_release=300.0, u_sens=55.0)},
    {"key": "accordion_wide_slap", "file": "Accordion – Wide Slap",
     "name": "Accordion · Wide Slap",
     "role": "An accordion with a short wide slap, like a small room.",
     "p": _cc(amount=18.0, feedback=15.0, mod_depth=8.0, mod_rate=1.0, sync=False,
              time_ms=110.0, width=130.0, hp=300.0, lp=5500.0,
              u_amount=25.0, u_attack=8.0, u_release=250.0, u_sens=50.0)},
    {"key": "flute_airy_echo", "file": "Flute – Airy Echo",
     "name": "Flute · Airy Echo",
     "role": "A flute with a light, airy echo behind each phrase.",
     "p": _cc(amount=22.0, feedback=35.0, mod_depth=10.0, mod_rate=0.8, sync=False,
              time_ms=300.0, width=120.0, hp=400.0, lp=7500.0,
              u_amount=22.0, u_attack=10.0, u_release=350.0, u_sens=45.0)},
    {"key": "sax_smoky_slap", "file": "Sax – Smoky Slap",
     "name": "Saxophone / Harmonica · Smoky Slap",
     "role": "A short, dark slap that gives a sax or harmonica a little room.",
     "p": _cc(amount=16.0, feedback=14.0, mod_depth=5.0, mod_rate=0.8, sync=False,
              time_ms=95.0, width=70.0, hp=300.0, lp=4500.0,
              u_amount=25.0, u_attack=6.0, u_release=250.0, u_sens=50.0)},
    {"key": "synth_pad_drift", "file": "Synth Pad – Drifting Echo",
     "name": "Synth Pad · Drifting Echo",
     "role": "A pad in a wide, slowly modulated echo.",
     "p": _cc(amount=26.0, feedback=55.0, mod_depth=40.0, mod_rate=0.4, sync=True,
              sync_idx=7, width=200.0, hp=200.0, lp=7500.0,
              u_amount=15.0, u_attack=20.0, u_release=500.0, u_sens=35.0)},
    {"key": "violin_short_room", "file": "Violin – Short Room Echo",
     "name": "Solo Violin · Short Room Echo",
     "role": "A solo violin with a short echo like a small hall.",
     "p": _cc(amount=18.0, feedback=18.0, mod_depth=6.0, mod_rate=0.8, sync=False,
              time_ms=140.0, width=100.0, hp=300.0, lp=7500.0,
              u_amount=25.0, u_attack=8.0, u_release=300.0, u_sens=50.0)},
    {"key": "organ_melody_echo", "file": "Organ_Melody_Echo",
     "name": "Organ Melody \u00b7 Clear Echo",
     "role": "A quiet eighth-note echo for an organ line, ducked so the notes stay clear.",
     "p": _cc(amount=18.0, feedback=25.0, mod_depth=10.0, mod_rate=1.5, sync=True,
              sync_idx=7, width=90.0, hp=250.0, lp=5500.0,
              u_amount=30.0, u_attack=8.0, u_release=300.0, u_sens=55.0)},
    # ---- AIR-ONLY versions for what used to be kept dry --------------------
    # Every channel gets some space. For the low end and the cymbals the safe way
    # to do it is a LOW CUT far above the fundamental (600-900 Hz), so the echo is
    # made of the click, the harmonics and the top only - the weight stays exactly
    # where it was, and the repeats add air instead of smear.
    {"key": "kick_tiny_room", "file": "Kick \u2013 Tiny Room",
     "name": "Kick \u00b7 Tiny Room",
     "role": "A tiny, ducked room around the beater click - no repeats.",
     "p": _cc(amount=8.0, feedback=0.0, mod_depth=0.0, mod_rate=1.0, sync=False,
              time_ms=45.0, width=60.0, hp=600.0, lp=4000.0,
              u_amount=50.0, u_attack=2.0, u_release=100.0, u_sens=70.0),
     "note": "The low cut at 600 Hz means the thump never reaches the delay - "
             "only the click does - and Unmask ducks even that while the kick "
             "hits. It adds a sense of space without touching the weight."},
    {"key": "bass_air_only", "file": "Bass \u2013 Air Only",
     "name": "Bass \u00b7 Air Only",
     "role": "Space for a bass made of its harmonics only - the low end is untouched.",
     "p": _cc(amount=10.0, feedback=10.0, mod_depth=4.0, mod_rate=0.8, sync=False,
              time_ms=110.0, width=60.0, hp=800.0, lp=4000.0,
              u_amount=45.0, u_attack=4.0, u_release=150.0, u_sens=65.0),
     "note": "Everything below 800 Hz bypasses the echo completely, so the "
             "fundamental stays mono and tight; what echoes is the pick or "
             "finger noise and the upper harmonics."},
    {"key": "hihat_airy_echo", "file": "Hi-Hat \u2013 Airy Echo",
     "name": "Hi-Hat \u00b7 Airy Echo",
     "role": "A light, bouncing echo that lifts the hi-hat into the room.",
     "p": _cc(amount=14.0, feedback=22.0, mod_depth=6.0, mod_rate=1.5, pingpong=True,
              sync=True, sync_idx=7, width=140.0, hp=900.0, lp=9000.0,
              u_amount=35.0, u_attack=4.0, u_release=200.0, u_sens=60.0)},
    {"key": "ride_shimmer_echo", "file": "Ride \u2013 Shimmer Echo",
     "name": "Ride \u00b7 Shimmer Echo",
     "role": "A ride with a wide, shimmering tail.",
     "p": _cc(amount=14.0, feedback=25.0, mod_depth=8.0, mod_rate=1.0, pingpong=True,
              sync=False, time_ms=190.0, width=150.0, hp=800.0, lp=9000.0,
              u_amount=30.0, u_attack=5.0, u_release=250.0, u_sens=55.0)},
    {"key": "cymbals_wide_tail", "file": "Cymbals \u2013 Wide Tail",
     "name": "Cymbals \u00b7 Wide Tail",
     "role": "Crashes and overheads that bloom into a wide tail.",
     "p": _cc(amount=16.0, feedback=30.0, mod_depth=10.0, mod_rate=0.8, pingpong=True,
              sync=False, time_ms=280.0, width=180.0, hp=700.0, lp=9500.0,
              u_amount=28.0, u_attack=6.0, u_release=300.0, u_sens=50.0)},
    {"key": "guitar_low_air", "file": "Low Guitar \u2013 Air",
     "name": "Single-Note Low Guitar \u00b7 Air",
     "role": "A low riff or single-note guitar with a little air above its notes.",
     "p": _cc(amount=12.0, feedback=15.0, mod_depth=5.0, mod_rate=0.8, sync=False,
              time_ms=130.0, width=70.0, hp=600.0, lp=4500.0,
              u_amount=40.0, u_attack=4.0, u_release=200.0, u_sens=60.0)},
]

for _p in CASCADIA_PRESETS:
    _p["old_file"] = _p["file"]
    _p["file"] = preset_file_name(_p["name"])

CASCADIA_BY_KEY = {p["key"]: p for p in CASCADIA_PRESETS}

# Which preset each channel starts on. EVERY channel gets one, because every
# channel wants some space around it. For the kick, the basses, the cymbals and a
# single-note low guitar that is an AIR-ONLY preset: a low cut far above the
# fundamental, so the echo is made of the top only and the weight is untouched.
# (A channel missing from this table would simply print no line.)
CASCADIA_FOR = {
    "kick":              "kick_tiny_room",
    "hihat":             "hihat_airy_echo",
    "ride":              "ride_shimmer_echo",
    "cymbals":           "cymbals_wide_tail",
    "bass_root":         "bass_air_only",
    "bass_loop":         "bass_air_only",
    "double_bass":       "bass_air_only",
    "guitar_single_low": "guitar_low_air",
    "vocals_lead":       "lead_vocal_eighth",
    "vocals_backing":    "backing_soft_wash",
    "vocals_choir_pad":  "choir_slow_bloom",
    "vocals_extra":      "extra_vocals_pingpong",
    "snare":             "drums_snare_rumble",
    "toms":              "toms_short_slap",
    "percussion":        "perc_tight_pingpong",
    "hand_drums":        "hand_drums_warm",
    "guitar_chords":     "all_subtle_depth",
    "guitar_rhythm":     "guitar_bounce_fades",
    "guitar_acoustic":   "guitar_pingpong_wide",
    "guitar_lead":       "guitar_lead_singing",
    "organ":             "organ_rotating_space",
    "organ_lead":        "organ_rotating_space",
    "organ_melody":      "organ_melody_echo",
    "accordion":         "accordion_wide_slap",
    "accordion_lead":    "accordion_wide_slap",
    "piano_bg":          "all_subtle_depth",
    "piano_riff":        "piano_gentle_echo",
    "flute":             "flute_airy_echo",
    "flute_bg":          "flute_airy_echo",
    "brass":             "brass_concert_hall",
    "brass_lead":        "brass_concert_hall",
    "trumpet":           "brass_concert_hall",
    "trombone":          "brass_concert_hall",
    "tenor_trombone":          "brass_concert_hall",
    "tenor_bass_trombone":          "brass_concert_hall",
    "horn_section":      "brass_concert_hall",
    "woodwind":          "brass_concert_hall",
    "saxophone":         "sax_smoky_slap",
    "harmonica":         "sax_smoky_slap",
    "clarinet":          "brass_concert_hall",
    "oboe":              "brass_concert_hall",
    "bassoon":           "brass_concert_hall",
    "contrabassoon":     "bass_air_only",
    "flugelhorn":        "brass_concert_hall",
    "french_horn":       "brass_concert_hall",
    "tuba":              "bass_air_only",
    "english_horn":      "brass_concert_hall",
    "euphonium":         "brass_concert_hall",
    "bass_clarinet":     "brass_concert_hall",
    "contrabass_clarinet": "bass_air_only",
    "double_bass_section": "bass_air_only",
    "piccolo": "flute_airy_echo",
    "alto_flute": "flute_airy_echo",
    "bass_flute": "flute_airy_echo",
    "soprano_sax": "sax_smoky_slap",
    "alto_sax": "sax_smoky_slap",
    "tenor_sax": "sax_smoky_slap",
    "baritone_sax": "sax_smoky_slap",
    "piccolo_trumpet": "brass_concert_hall",
    "alto_trombone": "brass_concert_hall",
    "bass_trombone": "brass_concert_hall",
    "double_bass_trombone": "brass_concert_hall",
    "synth_pad":         "synth_pad_drift",
    "synth_pluck":       "synth_plucks_bounce",
    "synth_mallet":      "synth_plucks_bounce",
    "violin":            "violin_short_room",
    "violin_bg":         "strings_flow_float",
    "viola":             "strings_flow_float",
    "viola_front":       "violin_short_room",
    "cello":             "strings_flow_float",
    "string_section":    "strings_flow_float",
    "strings_lead":      "violin_short_room",
}

CASCADIA_ALSO = {
    "hihat":             ["cymbals_wide_tail"],
    "ride":              ["cymbals_wide_tail"],
    "cymbals":           ["ride_shimmer_echo"],
    "bass_root":         ["bass_solo_pulse"],
    "guitar_single_low": ["guitar_space_depth"],
    "vocals_lead":       ["vocal_air_behind", "vocal_slapback_punch"],
    "vocals_backing":    ["vocal_air_behind"],
    "vocals_choir_pad":  ["all_huge_room"],
    "snare":             ["drums_half_echo"],
    "toms":              ["drums_half_echo"],
    "guitar_rhythm":     ["guitar_space_depth"],
    "guitar_acoustic":   ["guitar_space_depth"],
    "guitar_lead":       ["guitar_space_depth", "guitar_pingpong_wide"],
    "organ":             ["all_subtle_depth"],
    "synth_pad":         ["synth_reversed_mystery", "all_huge_room"],
    "synth_pluck":       ["synth_reversed_mystery"],
    "brass":             ["all_subtle_depth"],
    "string_section":    ["all_subtle_depth"],
    "violin":            ["vocal_air_behind"],
}
# Presets that belong to no single channel - written by 'All', and offered with a
# multi-channel selection.
CASCADIA_BUS_KEYS = ["all_subtle_depth", "all_huge_room", "bass_solo_pulse"]


def cascadia_for(iid, sel=None):
    """(preset, alternatives) for an instrument, or (None, []) for a channel that
    has none. `sel` only matters for the lead vocal on its own (lead_alone())."""
    key = CASCADIA_FOR.get(iid)
    if not key or key not in CASCADIA_BY_KEY:
        return None, []
    also = list(CASCADIA_ALSO.get(iid, []))
    if iid == "vocals_lead" and lead_alone(sel) and "lead_vocal_eighth_alone" in CASCADIA_BY_KEY:
        also = [key] + also
        key = "lead_vocal_eighth_alone"
    alts = [CASCADIA_BY_KEY[k] for k in also if k in CASCADIA_BY_KEY]
    return CASCADIA_BY_KEY[key], alts


def cascadia_clamp(short, value):
    spec = CASCADIA_RANGE.get(short)
    if not spec:
        return value
    return max(spec[0], min(spec[1], float(value)))


def cascadia_params(preset):
    """The full parameter set a preset writes, every number clamped. The low cut
    is kept below the high cut."""
    out = dict(CASCADIA_BASE)
    out.update(preset["p"])
    for k in list(out):
        if k in CASCADIA_RANGE:
            out[k] = cascadia_clamp(k, out[k])
    if out["hp"] >= out["lp"]:
        out["hp"] = out["lp"] * 0.5
    out["sync_idx"] = int(out["sync_idx"])
    for k in ("pingpong", "reverse", "sync", "u_power", "u_delta"):
        out[k] = bool(out[k])
    return out


def _cc_hz(hz):
    hz = float(hz)
    return ("%g kHz" % round(hz / 1000.0, 2)) if hz >= 1000 else ("%g Hz" % round(hz))


def cascadia_time_text(p):
    """'1/8 note' / 'note index 6 (unconfirmed)' / '180 ms'."""
    if p["sync"]:
        if p["sync_idx"] in CASCADIA_SYNC_KNOWN:
            return "Sync " + CASCADIA_SYNC_KNOWN[p["sync_idx"]]
        return "Sync note #%d (unconfirmed)" % p["sync_idx"]
    return "%g ms" % round(p["time_ms"])


def cascadia_head(preset):
    """'≈ Cascadia: Lead Vocal · Eighth-Note Echo — Amount 17 % ·
    Sync 1/8 · Feedback 22 % · Width 80 %'."""
    if not preset:
        return ""
    p = cascadia_params(preset)
    bits = ["Amount %g %%" % round(p["amount"]), cascadia_time_text(p),
            "Feedback %g %%" % round(p["feedback"]), "Width %g %%" % round(p["width"])]
    if p["pingpong"]:
        bits.append("Ping-Pong")
    if p["reverse"]:
        bits.append("REVERSE")
    return "≈ Cascadia: %s  —  %s" % (preset["name"], "  ·  ".join(bits))


def cascadia_detail(preset):
    """The rest of the panel, as one line. All settings, so never hidden."""
    if not preset:
        return ""
    p = cascadia_params(preset)
    bits = ["Low cut %s" % _cc_hz(p["hp"]), "High cut %s" % _cc_hz(p["lp"]),
            "Mod %g %% @ %g Hz" % (round(p["mod_depth"]), round(p["mod_rate"], 2))]
    if p["u_power"]:
        bits.append("Unmask %g %% (attack %g ms, release %g ms, sens %g %%)"
                    % (round(p["u_amount"]), round(p["u_attack"]),
                       round(p["u_release"]), round(p["u_sens"])))
    else:
        bits.append("Unmask OFF")
    return "  ·  ".join(bits)


def cascadia_caution(preset):
    """The preset's own caution, plus - never hidden - a warning when it relies on
    a tempo-sync index nobody has confirmed."""
    msgs = []
    if preset.get("caution"):
        msgs.append(preset["caution"])
    p = cascadia_params(preset)
    if p["sync"] and p["sync_idx"] not in CASCADIA_SYNC_KNOWN:
        msgs.append("Tempo Sync is ON with note index %d, carried over from the "
                    "original file. Only index 7 (1/8) is confirmed, so check the "
                    "note value in the plug-in once." % p["sync_idx"])
    return msgs


# ---- THE PRESET WRITER -----------------------------------------------------
# Needs ONE existing Cascadia .vstpreset as the container (the class id, the
# MetaInfo XML and the user's own analytics block come from it). The user's
# 'radera-cascadia' is exactly that.

CASCADIA_MAGIC = 20240507


def _cascadia_parse(data):
    """(head40, info_bytes, json_object) from a Cascadia .vstpreset. Reads the
    compressed state leniently, so the first set of presets (whose Comp chunk is
    a few bytes short) can be read too."""
    if data[:4] != b"VST3":
        raise ValueError("not a .vstpreset")
    off = struct.unpack("<Q", data[40:48])[0]
    n = struct.unpack("<i", data[off + 4:off + 8])[0]
    ents, p = {}, off + 8
    for _ in range(n):
        tag = data[p:p + 4]
        o, s = struct.unpack("<QQ", data[p + 4:p + 20])
        ents[tag] = (o, s)
        p += 20
    co, cs = ents[b"Comp"]
    magic, _z, _plen, _ulen = struct.unpack("<IIII", data[co:co + 16])
    if magic != CASCADIA_MAGIC:
        raise ValueError("not a Cascadia state")
    raw = _zlib.decompressobj().decompress(data[co + 16:off])
    obj = _json.loads(raw.decode("utf-8"))
    io, isz = ents[b"Info"]
    return data[:40], data[io:io + isz], obj


def _cascadia_element(obj):
    return obj["DSP State"]["Value"]["DSP Elements"]["Value"]["Cascadia"]["Value"]


def _cascadia_plain(o):
    """The plug-in writes whole numbers without a decimal point."""
    if isinstance(o, float) and o == int(o) and abs(o) < 1e15:
        return int(o)
    if isinstance(o, dict):
        return {k: _cascadia_plain(v) for k, v in o.items()}
    if isinstance(o, list):
        return [_cascadia_plain(v) for v in o]
    return o


def make_cascadia_preset(template, params):
    """Return a Cascadia .vstpreset built from `template` with `params` written
    into its state. Raises ValueError if the template is not a Cascadia preset."""
    head, info, obj = _cascadia_parse(template)
    el = _cascadia_element(obj)
    for short, (jkey, jtype) in CASCADIA_KEYS.items():
        if jkey not in el:
            raise ValueError("template has no parameter " + jkey)
        v = params[short]
        el[jkey]["Value"] = (bool(v) if jtype == "Bool" else
                             int(v) if jtype == "UInt" else float(v))
    js = (_json.dumps(_cascadia_plain(obj), indent=3, separators=(",", " : "),
                      ensure_ascii=False) + "\n").encode("utf-8")
    stream = _zlib.compress(js, 6)
    comp = struct.pack("<IIII", CASCADIA_MAGIC, 0, len(stream) + 4, len(js)) + stream
    off = 48 + len(comp) + len(info)
    lst = (b"List" + struct.pack("<i", 3)
           + b"Comp" + struct.pack("<QQ", 48, len(comp))
           + b"Cont" + struct.pack("<QQ", 48 + len(comp), 0)
           + b"Info" + struct.pack("<QQ", 48 + len(comp), len(info)))
    return head[:40] + struct.pack("<Q", off) + comp + info + lst


def read_cascadia_values(data):
    """{short key: value} read back out of a Cascadia .vstpreset, or None."""
    try:
        _h, _i, obj = _cascadia_parse(data)
        el = _cascadia_element(obj)
        return {short: el[jkey]["Value"] for short, (jkey, _t) in CASCADIA_KEYS.items()}
    except Exception:
        return None


def cascadia_same(a, b):
    """Do two value dicts describe the same sound?"""
    if not a or not b:
        return False
    for k in CASCADIA_KEYS:
        x, y = a.get(k), b.get(k)
        if x is None or y is None:      # a value one side cannot hold (native: index)
            continue
        if isinstance(x, bool) or isinstance(y, bool):
            if bool(x) != bool(y):
                return False
        elif abs(float(x) - float(y)) > 1e-3:
            return False
    return True


# ---- THE NATIVE .preset WRITER (Cascadia's OWN preset browser) ---------------
# Cascadia's built-in browser (Classic / Creative / User presets) does NOT read
# .vstpreset files. It reads plain JSON `.preset` files from
# Documents\iZotope\Cascadia\Presets - the format of the factory presets and of a
# preset saved with the plug-in's own New button. No template is needed. The tempo
# note is stored as a STRING ("1/8", "1/16." ...), so unlike the .vstpreset there
# is no unconfirmed index here. The plug-in itself writes LF line ends.

CASCADIA_NOTE_AT_120 = [("1/16", 125.0), ("1/16.", 187.5), ("1/8", 250.0),
                        ("1/8.", 375.0), ("1/4", 500.0)]


def cascadia_native_note(p):
    """The note-value string for a native file. Index 7 is the confirmed 1/8; any
    other index is unknown, so the note the stored time implies at 120 BPM is used
    (125 ms = 1/16, 187 = 1/16., 250 = 1/8, 375 = 1/8., 500 = 1/4) - which is what
    the original presets were clearly aiming at. Tempo Sync off: the string is not
    used, 1/8 is written as the factory presets do."""
    if not p["sync"] or p["sync_idx"] in CASCADIA_SYNC_KNOWN:
        return CASCADIA_SYNC_KNOWN.get(p["sync_idx"], "1/8")
    return min(CASCADIA_NOTE_AT_120, key=lambda nv: abs(nv[1] - p["time_ms"]))[0]


def make_cascadia_native(params):
    """Bytes of a Cascadia-browser `.preset` for a cascadia_params() dict."""
    vals = {}
    for short, (jkey, jtype) in CASCADIA_KEYS.items():
        v = params[short]
        if jtype == "Bool":
            vals["dsp.Cascadia." + jkey] = {"Type": "Bool", "Value": bool(v)}
        elif short == "sync_idx":
            vals["dsp.Cascadia." + jkey] = {"Type": "String",
                                            "Value": cascadia_native_note(params)}
        else:
            vals["dsp.Cascadia." + jkey] = {"Type": "Float", "Value": float(v)}
    obj = {"data": {"Type": "Dictionary", "Value": dict(sorted(vals.items()))},
           "version": {"Type": "Int", "Value": 0}}
    return (_json.dumps(_cascadia_plain(obj), indent=3, separators=(",", " : "),
                        ensure_ascii=False) + "\n").encode("utf-8")


def read_cascadia_native(data):
    """{short key: value} from a native `.preset` (note value as 'note'), or None."""
    try:
        v = _json.loads(data.decode("utf-8"))["data"]["Value"]
        out = {s: v["dsp.Cascadia." + k]["Value"] for s, (k, _t) in CASCADIA_KEYS.items()
               if s != "sync_idx"}
        out["sync_idx"] = None      # a native file stores the note as text, not an index
        out["note"] = v["dsp.Cascadia.DelayTimeTempoSynced"]["Value"]
        return out
    except Exception:
        return None


def cascadia_selftest(template=None):
    """[] when the table is consistent and (given a template) the writer is exact:
    a template rewritten with its OWN values must come back byte for byte."""
    bad, names = [], set()
    for pr in CASCADIA_PRESETS:
        if pr["file"] in names:
            bad.append("%s: duplicate file name" % pr["key"])
        names.add(pr["file"])
    for iid, key in CASCADIA_FOR.items():
        if key not in CASCADIA_BY_KEY:
            bad.append("%s: unknown preset %s" % (iid, key))
    for pr in CASCADIA_PRESETS:
        p = cascadia_params(pr)
        back = read_cascadia_native(make_cascadia_native(p))
        if not back or not cascadia_same(back, p) or back["note"] != cascadia_native_note(p):
            bad.append("%s: native .preset does not survive a round trip" % pr["key"])
    if template:
        own = read_cascadia_values(template)
        if not own or make_cascadia_preset(template, own) != template:
            bad.append("writer does not reproduce the template byte for byte")
        for pr in CASCADIA_PRESETS:
            vp = make_cascadia_preset(template, cascadia_params(pr))
            if not cascadia_same(read_cascadia_values(vp), cascadia_params(pr)):
                bad.append("%s: does not survive a round trip" % pr["key"])
    return bad


# *************** DEL 02p - DEFAULTS & DEVIATIONS ****************************
# "Then I do not have to double-check whether I really have the right setting
# in every VST."
#
# Every other engine in this program answers "what should this channel be in
# THIS song". That is the right answer, and it is also the tiring one: nine
# plug-ins on a channel, and most of their knobs say exactly the same thing in
# every song he will ever mix. What he actually has to read is the DIFFERENCE.
#
# So each instrument gets a DEFAULT — what it is set to when there is ONE of it
# in the kind of song it usually turns up in — and that is what he saves as the
# plug-in's own preset. From then on the sheet is read the other way round:
#
#     a value that MATCHES the default is greyed out   -> the preset already
#                                                          did it, do not touch
#     a value that does NOT match stays in full colour -> this song is the
#                                                          exception, dial it
#
# WHERE A DEFAULT COMES FROM. Not from the instrument standing on its own: one
# instrument alone on a stage gets a small room and a centre position, and that
# is a song nobody mixes. It comes from a VOTE. The engines are run over the
# reference line-ups below, the instrument at x1 in each of them, and the answer
# that wins the most line-ups becomes the default. That is literally "the one
# most likely to be the one that turns up most often", and the Defaults window
# prints the vote, so a 5-3 split is never mistaken for a certainty.
#
# The vote is also what settles the question he asked about the room: Virtual
# Stage's Room is a SONG-level choice, so on a solo instrument it would just be
# whatever the smallest line-up wants. Across the reference songs it settles on
# one size, and that size is the one that goes in the preset.
#
# THE DELIBERATE HOLE: an engine that ignores the line-up entirely — the low
# cut, SubMass, the compressor tiers, the smart:EQ tier, the Corridor and Omega
# presets — can never deviate, so once its preset is saved it is grey forever.
# That is not a bug, it is the whole point: those are the rows he stops reading.
# What is left in colour is Virtual Stage, the ducks whose source is or is not
# in this song, and the xN block — which is exactly where the answers really do
# move.
#
# ONE SOURCE OF TRUTH: engine_bits() builds the field list, the footnotes draw
# from it and the vote counts on it. Neither can drift away from the other.

# ---------------------------------------------------------------------------
# THE DEFAULT BAND — his own answer to "what is a normal song", and the one
# the program uses unless he asks for the vote instead.
#
# His list, and what measuring it settled:
#
#   IN THE BAND (13 channels): lead vocal and backing vocals — "jag har
#   nästan alltid sång + bakgrundssång" — then chord guitar, rhythm guitar,
#   bass, bass X, kick, snare, hi-hat, tom, cymbal, and piano and organ, which
#   he called very common. Neither pair moves anything else on the stage, so
#   both were free to keep. The vocals earn their place twice over: with a lead
#   vocal permanently in the family, the backing vocals sit at R50 — properly
#   off the lead — instead of the R30 they got as a lone guest.
#
#   NOT IN THE BAND, on his own condition. He wrote the solo guitar down with
#   "if it does not affect the other guitars". It does: a third guitar in the
#   family widens the row, and the two rhythm guitars go R65/L65 -> R75/L75.
#   So it stays out and is placed as a GUEST instead, which is also what he
#   asked for the ride ("as if it is with one hi-hat") and the percussion
#   ("as if it is with the default kit"). Both of those move the hi-hat
#   (R20 -> R25) when they are permanent members, and neither of them needs to
#   be one to get a sensible default of its own.
#
# THE GUEST RULE: anything not in the band gets its default by standing IN the
# band, at x1. So the ride is placed next to the band's hi-hat, the percussion
# next to the band's kit, a cello in front of the band's guitars — which is
# the context he described for each of them, and it comes out of one rule
# instead of a special case per instrument.
#
# WHY 13 AND NOT 16: at 15 channels the room engine steps up to Large. A band
# of 13 plus one guest is 14 — one under the line — so the whole chart sits in
# ONE room (Medium) and the Room field is genuinely a constant. That is also
# the CONSTRAINT ON THIS LIST: a fourteenth permanent member would put every
# guest in a Large room and every band member in a Medium one, and the Room
# field would go from a constant to a coin toss. The three bed instruments —
# synth pad, string section, choir pad — still ask for Large on their own,
# because in this program a bed IS what makes a room big (vstage_room's
# big_bed rule, which does not count channels the same way).
# ONE BAND PER ROOM SIZE. The room is a song-level setting, so a single set of
# defaults could only ever be right in one size of room — in the other two,
# every channel would light up its Room field and half of them their Distance,
# which is noise, not information. So there are three bands and three sets of
# defaults, and the sheet compares against the set for the room THIS song is
# in. The Room field is then grey whenever the song is a normal one for its
# size, and lights up only when the song is genuinely between two rooms.
#
# Each band is built to sit comfortably inside its own range WITH ONE GUEST
# standing in it, because that is how a default for an instrument outside the
# band is worked out: Small is 4 places (a guest makes 5, still Small), Medium
# is 9 (a guest makes 10), Large is far enough over 11 that nothing can pull
# it back down.
#
# The kit is in all three. It costs one place, and without it a lone snare
# would have to be placed as if it were the entire drum kit — which is a
# line-up nobody has ever recorded.
DEFAULT_BANDS = {
    # 1-5 places. A singer, a guitar, a piano, and the kit if there is one:
    # the intimate end — no horns, no strings, no woodwind, which is what he
    # said belongs here and what the room agrees with.
    "Small": [
        "vocals_lead",
        "guitar_acoustic",
        "piano_bg",
        "kick", "snare", "hihat", "toms", "cymbals",
    ],
    # 6-10 places. His own band, the one he described instrument by instrument.
    "Medium": [
        "vocals_lead", "vocals_backing",
        "guitar_chords", "guitar_rhythm",
        "bass_root", "bass_loop",
        "kick", "snare", "hihat", "toms", "cymbals",
        "piano_bg", "organ",
    ],
    # 11+ places. The same band, produced: a solo guitar, a second keyboard,
    # brass, and a string section — the two section entries count double, so
    # this is 14 places and nothing a guest does can drag it under the line.
    "Large": [
        "vocals_lead", "vocals_backing",
        "guitar_chords", "guitar_rhythm", "guitar_lead",
        "bass_root", "bass_loop",
        "kick", "snare", "hihat", "toms", "cymbals",
        "piano_bg", "organ", "piano_riff",
        "brass", "string_section",
    ],
}

# The band, unqualified, is the medium one — the one he actually plays in.
DEFAULT_BAND = DEFAULT_BANDS["Medium"]

DEFAULT_BAND_LINEUPS = {
    room: [{"name": "The default band (%s room)" % room, "ids": list(ids)}]
    for room, ids in DEFAULT_BANDS.items()
}

DEFAULT_BAND_LINEUP = DEFAULT_BAND_LINEUPS["Medium"]


def band_lineup(room):
    """The reference band for one room size."""
    return DEFAULT_BAND_LINEUPS.get(room) or DEFAULT_BAND_LINEUP


def band_ids(room):
    return DEFAULT_BANDS.get(room) or DEFAULT_BAND


def is_band_lineup(lus):
    """Is this one of the three bands, rather than a vote?"""
    return any(lus is x for x in DEFAULT_BAND_LINEUPS.values())


# The reference songs the VOTE runs over, when he asks for that instead. This
# was the first way defaults were built, and it is still the better answer for
# an instrument his band never contains. First in the list wins a tie, so his
# own default line-up (DEFAULT_VARIANT, DEL 04b) is first: when his band and a
# textbook pop song disagree, his band is right. Between them these cover every
# instrument in the chart; anything that somehow is not covered is added to the
# first line-up at x1 rather than silently getting no default at all.
DEFAULT_LINEUPS = [
    {"name": "His own default mix",
     "ids": ["bass_root", "bass_loop", "guitar_chords", "guitar_rhythm",
             "kick", "snare", "hihat", "cymbals", "toms", "percussion",
             "organ"]},
    {"name": "Full band with vocals",
     "ids": ["vocals_lead", "vocals_backing", "vocals_choir_pad",
             "kick", "snare", "hihat", "ride", "cymbals", "toms",
             "bass_root", "guitar_rhythm", "guitar_chords", "guitar_lead",
             "piano_bg"]},
    {"name": "Rock trio and a singer",
     "ids": ["vocals_lead", "kick", "snare", "hihat", "cymbals",
             "bass_root", "guitar_rhythm", "guitar_single_low"]},
    {"name": "Pop and synths",
     "ids": ["vocals_lead", "vocals_backing", "vocals_choir_pad",
             "kick", "snare", "hihat", "percussion", "bass_loop",
             "synth_pad", "synth_pluck", "synth_mallet", "piano_bg"]},
    {"name": "Acoustic singer-songwriter",
     "ids": ["vocals_lead", "guitar_acoustic", "guitar_lead", "bass_root",
             "percussion", "piano_bg", "cello", "flute", "accordion"]},
    {"name": "Folk band",
     "ids": ["vocals_lead", "accordion", "accordion_lead", "guitar_acoustic",
             "double_bass", "percussion", "violin", "viola", "harmonica",
             "flute", "woodwind"]},
    {"name": "Soul and horns",
     "ids": ["vocals_lead", "vocals_backing", "kick", "snare", "hihat", "ride",
             "bass_root", "guitar_chords", "guitar_single_low", "organ",
             "organ_lead", "piano_riff", "trumpet", "trombone", "saxophone",
             "horn_section", "brass", "brass_lead"]},
    {"name": "Jazz combo",
     "ids": ["vocals_lead", "kick", "snare", "hihat", "ride", "cymbals",
             "double_bass", "piano_riff", "organ_lead", "guitar_chords",
             "trumpet", "saxophone", "trombone"]},
    {"name": "Ambient and electronic",
     "ids": ["vocals_lead", "vocals_choir_pad", "kick", "hihat", "percussion",
             "bass_loop", "synth_pad", "synth_pluck", "synth_mallet",
             "piano_bg", "string_section", "guitar_single_low"]},
    {"name": "Strings and winds",
     "ids": ["piano_bg", "piano_riff", "violin", "viola", "cello",
             "double_bass", "string_section", "strings_lead", "flute",
             "flute_bg", "violin_bg", "woodwind", "brass", "brass_lead",
             "horn_section", "harmonica", "synth_mallet"]},
]

# The engines a default is voted on, in chain order — the same order the
# footnotes are printed in, so the Defaults window reads like a channel strip.
DEFAULT_ENGINES = [
    ("lowcut",   "Low cut"),
    ("omega",    "Omega 458a"),
    ("smarteq",  "smart:EQ group"),
    ("comp",     "Compressor"),
    ("submass",  "SubMass"),
    ("duck",     "Ducking"),
    ("depth",    "smart:reverb"),
    ("corridor", "Corridor"),
    ("vstage",   "Virtual Stage"),
]

# Every head line in this program is a list of fields joined by one of these
# two separators. Splitting on them is what makes a field greyable on its own
# instead of the whole line going one colour.
HEAD_SEPS = ("  ·  ", "  —  ")

# ACCENTS: the few words in a head line that are read every time get their own
# colour while the rest of the line stays quiet. The same words keep the same
# colour wherever they appear (smart:EQ tier, smart:reverb tier, Virtual Stage
# fields, the source a Trackspacer ducks under).
TIER_COLOURS = {"FRONT": "#3ddc97", "NEAR": "#7fe0d0", "MID": "#ffd166",
                "FAR": "#8fb4ff", "BACK": "#8fb4ff"}
LOWEND_FREQ_COLOUR = "#a7f070"   # the '@ 60 Hz' of the SubMass part of the low-end row
STAGE_POS_COLOUR  = "#ffcf66"    # L50 / C / R25
STAGE_DIST_COLOUR = "#7be0b0"    # the Distance number
STAGE_ROOM_COLOUR = "#8fb4ff"    # Small / Medium / Large
DUCK_SRC_COLOURS  = {"Lead Vocal": "#ffd166", "Kick": "#ff7b7b"}
DUCK_SRC_DEFAULT  = "#9ee6c9"


def tier_colour(text):
    """Colour for a tier word found in a matched string (FRONT / NEAR / MID / FAR / BACK)."""
    for word, col in TIER_COLOURS.items():
        if word in text:
            return col
    return None


def accent_spans(text, accents):
    """[(start, end, colour)] for the accent patterns that match `text`, in order and
    without overlaps. `accents` is a list of (regex, colour-or-function)."""
    spans = []
    for pat, col in accents or ():
        for mt in _re.finditer(pat, text):
            c = col(mt.group(0)) if callable(col) else col
            if c:
                spans.append((mt.start(), mt.end(), c))
    spans.sort()
    out, pos = [], 0
    for s, e, c in spans:
        if s >= pos:
            out.append((s, e, c))
            pos = e
    return out


def head_parts(head):
    """Split a head line into [(separator_before, field), ...].

    The separator is carried along so the line can be drawn back exactly as it
    was written — the fields are the only thing that gets its own colour."""
    text = head or ""
    out, buf, sep, i = [], "", "", 0
    while i < len(text):
        hit = None
        for s in HEAD_SEPS:
            if text.startswith(s, i):
                hit = s
                break
        if hit:
            out.append((sep, buf))
            sep, buf, i = hit, "", i + len(hit)
        else:
            buf += text[i]
            i += 1
    out.append((sep, buf))
    return [(s, t) for s, t in out if t.strip()]


def head_bits(head):
    """Just the fields of a head line."""
    return [t for _s, t in head_parts(head)]


def _field_key(bit):
    """What makes two fields 'the same knob'. The first word: 'Distance 47' and
    'Distance 62' are one knob, 'Room Large' and 'Room Medium' are one knob.
    A one-word field is its own key, which is the honest answer for a field
    that is only ever a bare word."""
    parts = (bit or "").split()
    return parts[0].lower() if len(parts) > 1 else (bit or "").strip().lower()


def mark_same(bits, default_bits):
    """[bool] — True where a field is exactly what the default holds.

    Same length is the normal case and then the fields line up one for one,
    which is the accurate comparison. Different lengths means a field appeared
    or vanished (an HPF that is only sometimes on, a duck whose source left the
    song), and then the first word is what pairs them up. Anything that cannot
    be paired counts as CHANGED, never as default: the failure that leaves a
    knob in colour costs a glance, the one that greys it out costs a mix."""
    bits = list(bits or [])
    dflt = list(default_bits or [])
    if not dflt:
        return [False] * len(bits)
    if len(bits) == len(dflt):
        return [b == d for b, d in zip(bits, dflt)]
    pool = {}
    for d in dflt:
        pool.setdefault(_field_key(d), []).append(d)
    return [bool(b in pool.get(_field_key(b), [])) for b in bits]


def engine_bits(engine, iid, sel=None, counts=None, persp="audience",
                stage_rows=None):
    """The fields of ONE engine's head line for ONE instrument, or [].

    sel/counts describe the song it is being asked about; stage_rows lets a
    caller that already has a stage plan hand it in instead of paying for
    another one (see EQApp._stage)."""
    sel = set(sel or ())
    counts = counts or {}

    if engine == "lowcut":
        lc = lowcut_for(iid)
        if not lc:
            return []
        return head_bits("\U0001f53b Low cut (Lowtility):  %d Hz  ·  %d dB/oct"
                         % (lc[0], lc[1]))

    if engine == "omega":
        pre, _alts = omega_for(iid)
        return head_bits(omega_head(pre)) if pre else []

    if engine == "bandwidth":
        pre, _alts = bandwidth_for(iid)
        return head_bits(bandwidth_head(pre)) if pre else []

    if engine == "cascadia":
        pre, _alts = cascadia_for(iid, sel)
        return head_bits(cascadia_head(pre)) if pre else []

    if engine == "smarteq":
        info = smarteq_group_for(iid, sel or None)
        if not info:
            return []
        glyph, _colour, label, _note = info
        return head_bits("\U0001f3af smart:EQ group:  %s %s" % (glyph, label))

    if engine == "comp":
        info = compression_for(iid, sel or None)
        if not info:
            return []
        tier, spec, _note = info
        if tier == "none":
            return ["\U0001f5dc Compressor: NONE — keep the natural dynamics"]
        return head_bits(
            "\U0001f5dc Compressor: %s  ·  Ratio %s  ·  Attack %s  ·  "
            "Release %s  ·  GR %s  ·  %s knee"
            % (spec["label"], spec["ratio"], spec["attack"], spec["release"],
               spec["gr"], spec["knee"]))

    if engine == "submass":
        info = submass_for(iid)
        if not info:
            return []
        amp, freq_hz, center_pct, _note = info
        return head_bits(
            "\U0001f311 SubMass: %s  ·  Amp %s/12  ·  Freq %s Hz  ·  "
            "Center %s%%" % (submass_tier(amp), amp, freq_hz, center_pct))

    if engine == "duck":
        raw = DUCKING.get(iid)
        if not raw:
            return []
        if sel and iid in sel and not duck_source_present(raw["src"], sel):
            return ["\U0001f986 No ducking needed — there is no %s in this "
                    "song. (With a %s: %s.)"
                    % (raw["src"], raw["src"], raw["set"])]
        return ["\U0001f986 Duck under the %s  (Trackspacer)" % raw["src"],
                "Side-chain = " + raw["src"],
                raw["set"]]

    if engine == "depth":
        info = depth_for_sel(iid, sel)
        if not info:
            return []
        tier, spec, _note, _alone = info
        if tier == "dry":
            return []
        return head_bits(
            "\U0001f32b smart:reverb: %s  ·  Dist %s  ·  Size %s  ·  "
            "Width %s  ·  %s" % (spec["label"], spec["distance"],
                                      spec["size"], spec["width"], spec["char"]))

    if engine == "corridor":
        pre, _alts = corridor_for(iid, sel)
        return head_bits(corridor_head(pre)) if pre else []

    if engine == "vstage":
        rows = stage_rows
        if rows is None:
            rows, _info = stage_plan(sel, counts, persp)
        row = rows.get(iid)
        return head_bits(vstage_head(row)) if row else []

    return []


# The extra SETTING lines that hang under a head line and are also just a list
# of fields. They earn the same treatment for the same reason: two thirds of
# the Omega panel is identical in every song.
def engine_detail_bits(engine, iid, sel=None):
    if engine == "omega":
        pre, _alts = omega_for(iid)
        return head_bits(omega_detail(pre)) if pre else []
    if engine == "corridor":
        pre, _alts = corridor_for(iid, sel)
        return head_bits(corridor_detail(pre)) if pre else []
    if engine == "bandwidth":
        pre, _alts = bandwidth_for(iid)
        return head_bits(bandwidth_detail(pre)) if pre else []
    if engine == "cascadia":
        pre, _alts = cascadia_for(iid, sel)
        return head_bits(cascadia_detail(pre)) if pre else []
    return []


_DEFAULTS_CACHE = {}


def clear_defaults_cache():
    _DEFAULTS_CACHE.clear()


def instrument_defaults(iid, persp="audience", lineups=None):
    """What this instrument's plug-in presets should hold.

    {engine: {"bits": [...], "detail": [...], "votes": [n per field],
              "of": m, "where": [line-up names]}}

    THE VOTE IS PER FIELD, not per line. That was the first thing the test
    found: voting on the whole head line meant that if the Position moved, the
    Distance and the Room moved with it, and Virtual Stage came back with
    defaults that had won one line-up out of five. Room and Distance are steady
    across almost every song even when Position is not, so each field is
    counted on its own and keeps its own vote — which is also how he described
    it: Large, C and 47 are three answers, not one.

    Fields are paired up by their first word (see _field_key), so 'Distance 47'
    in one song and 'Distance 62' in another are the same knob voting twice.

    Cached: this runs a full stage_plan per reference line-up, which is cheap
    once and silly per card."""
    lus = [lu for lu in (lineups if lineups is not None else DEFAULT_LINEUPS)
           if lu.get("ids")]
    if not lus:
        return {}
    key = (iid, persp,
           tuple((lu.get("name", ""), tuple(sorted(lu["ids"]))) for lu in lus))
    hit = _DEFAULTS_CACHE.get(key)
    if hit is not None:
        return hit

    used = [lu for lu in lus if iid in lu["ids"]]
    if not used:
        # Not in any reference song. Rather than leave it without a default,
        # stand it in the first line-up on its own — which is what he would do
        # if he ever put a viola in his band.
        base = lus[0]
        used = [{"name": base.get("name", "reference") + " + this one",
                 "ids": list(base["ids"]) + [iid]}]

    seen = {}      # engine -> [ (lineup_name, [bits]) , … ]
    for lu in used:
        sel = set(lu["ids"])
        sel.add(iid)
        counts = {i: 1 for i in sel}
        try:
            rows, _info = stage_plan(sel, counts, persp)
        except Exception:
            rows = {}
        for eng, _label in DEFAULT_ENGINES:
            try:
                if eng == "duck":
                    # A DEFAULT is what goes in the preset, and "no ducking
                    # needed" cannot be saved in one. The duck's default is
                    # always the configured duck (reference mode, sel=None);
                    # a song without the side-chain source is then a deviation
                    # every time, which is exactly the right answer — that IS
                    # the song where he has to switch Trackspacer off.
                    bits = engine_bits(eng, iid)
                else:
                    bits = engine_bits(eng, iid, sel, counts, persp,
                                       stage_rows=rows)
            except Exception:
                bits = []
            if bits:
                seen.setdefault(eng, []).append((lu.get("name", ""), bits))

    out = {}
    for eng, runs in seen.items():
        # 1. the SHAPE: which fields the line has at all. The commonest wins,
        #    so an HPF that is only on in half the songs does not invent a
        #    field the preset has no knob for.
        shapes = {}
        for order, (_name, bits) in enumerate(runs):
            k = tuple(_field_key(b) for b in bits)
            rec = shapes.get(k)
            if rec is None:
                shapes[k] = [1, order]
            else:
                rec[0] += 1
        shape = sorted(shapes.items(), key=lambda kv: (-kv[1][0], kv[1][1]))[0][0]
        # 2. each field votes on its own, over EVERY song that has that field.
        polls = {}
        for order, (_name, bits) in enumerate(runs):
            for b in bits:
                slot = polls.setdefault(_field_key(b), {})
                rec = slot.get(b)
                if rec is None:
                    slot[b] = [1, order]
                else:
                    rec[0] += 1
        bits, votes = [], []
        for k in shape:
            slot = polls.get(k) or {}
            if not slot:
                continue
            val, rec = sorted(slot.items(),
                              key=lambda kv: (-kv[1][0], kv[1][1]))[0]
            bits.append(val)
            votes.append(rec[0])
        out[eng] = {"bits": bits, "detail": engine_detail_bits(eng, iid),
                    "votes": votes, "of": len(runs),
                    "where": [n for n, _b in runs]}
    _DEFAULTS_CACHE[key] = out
    return out


def default_vote_note(d):
    """'Distance 47 won 4 of 6  ·  Room Medium won 5 of 6' — only the fields
    the reference songs did NOT agree on. Empty when every field was
    unanimous, which is the common case and needs no comment.

    It prints the VALUE and not the knob name on purpose: a 2-of-4 default is
    a coin toss dressed as an answer, and seeing which value it was is what
    tells him whether to trust it or to dial that one by ear."""
    if not d:
        return ""
    of = d.get("of", 0)
    out = []
    for bit, v in zip(d.get("bits", []), d.get("votes", [])):
        if v < of:
            label = bit.split(": ", 1)[1] if ": " in bit else bit
            out.append("%s won %d of %d" % (label, v, of))
    return "  ·  ".join(out)


def default_lineups_from_variants(variants):
    """His own saved song variants, as reference line-ups. The alternative to
    the built-in set: if the songs he actually mixes are in the Variants tab,
    they are a better description of 'usually' than any list I can write."""
    out = []
    for v in variants or []:
        ids = [i for i in v.get("fixed", []) if i in VALID_IDS]
        if ids:
            out.append({"name": v.get("name", "Variant"), "ids": ids})
    return out


# *************** DEL 02f - SONIBLE smart:reverb / smart:EQ PRESET WRITER *****
# A sonible ".vstpreset" is a VST3 container whose plugin state is PROTOBUF.
# We do NOT synthesise these black-box "smart" states from scratch — that was the
# SweetEQ lesson (a chart can't reproduce an AI-learned/proprietary state). Instead
# we take ONE reference preset the user made by ear as a SEED and patch only the
# few deterministic knobs the cheat sheet legitimately knows.
#
#   • smart:reverb  → Distance / Size / Width (the visible knobs). These live in
#     the param block (top-level protobuf field 3) as wire-type-5 floats. A float
#     is a FIXED 4 bytes, so the edit is byte-for-byte IN PLACE: every other byte
#     (the learned reverb profile, the container offsets, the JUCE trailer) stays
#     identical, so the patched file always re-loads. Field map, verified against a
#     hand-made "Lead vocal" preset (its f11=15, f16=25 matched the chart exactly):
#         f11 = Distance (0..100)   f16 = Size (0..100)   f18 = Width (0..100)
#     The character puck (Room/Hall/Spring/Plate, f13/f14) is LEFT at the seed's
#     value — its corner coordinates aren't verified, so the recipe text tells the
#     user which corner to lean toward instead.
#
#   • smart:EQ  → the curve is AI-learned (a ~5 MB profile) and there is no clean
#     "front/mid/back" field to set, so we don't patch it. We clone the seed to a
#     correctly-named slot (so the named preset survives) and print the smart:EQ
#     group tier (Front/Mid/Back) as a recipe — the user analyses the EQ manually.

SREV_FIELD_DISTANCE = 11    # top-level field 3 → sub-field 11
SREV_FIELD_SIZE     = 16    # top-level field 3 → sub-field 16
SREV_FIELD_WIDTH    = 18    # top-level field 3 → sub-field 18


def _pb_read_varint(b, p):
    """Read a protobuf varint at offset p; return (value, new_p)."""
    shift = 0
    val = 0
    while True:
        x = b[p]
        p += 1
        val |= (x & 0x7f) << shift
        if not x & 0x80:
            break
        shift += 7
    return val, p


def _pb_top_fields(b, base):
    """Parse a flat protobuf message; return [(field, wiretype, value_abs_off, length)].
    Stops cleanly at the first byte that isn't a valid field (e.g. the JUCE trailer
    that follows the plugin's protobuf state inside the chunk)."""
    p = 0
    n = len(b)
    out = []
    while p < n:
        try:
            key, p = _pb_read_varint(b, p)
        except IndexError:
            break
        field = key >> 3
        wt = key & 7
        if wt == 0:
            st = p
            try:
                _, p = _pb_read_varint(b, p)
            except IndexError:
                break
            out.append((field, 0, base + st, p - st))
        elif wt == 2:
            ln, p = _pb_read_varint(b, p)
            if p + ln > n:
                break
            out.append((field, 2, base + p, ln))
            p += ln
        elif wt == 5:
            out.append((field, 5, base + p, 4))
            p += 4
        elif wt == 1:
            out.append((field, 1, base + p, 8))
            p += 8
        else:
            break
    return out


def _vst3_comp_chunk(data):
    """Return (offset, size) of the 'Comp' chunk in a .vstpreset, or (None, None)."""
    try:
        listoff = struct.unpack("<q", data[40:48])[0]
        n = struct.unpack("<i", data[listoff + 4:listoff + 8])[0]
        p = listoff + 8
        for _ in range(n):
            cid = data[p:p + 4]
            off = struct.unpack("<q", data[p + 4:p + 12])[0]
            size = struct.unpack("<q", data[p + 12:p + 20])[0]
            if cid == b"Comp":
                return off, size
            p += 20
    except Exception:
        pass
    return None, None


def _smartreverb_param_offsets(data):
    """Locate Distance/Size/Width float offsets inside a smart:reverb .vstpreset.
    Returns {'distance':off, 'size':off, 'width':off} (absolute) or None."""
    comp_off, _ = _vst3_comp_chunk(data)
    if comp_off is None:
        return None
    comp = data[comp_off:]
    fb = comp.find(b"FBCh")
    if fb < 0:
        return None
    # FXB chunk header after 'FBCh': version, fxID, fxVersion, numPrograms (4 ints)
    # + 128 reserved bytes, then the chunkSize (big-endian int), then the chunk.
    cs_off = fb + 4 * 5 + 128
    try:
        clen = struct.unpack(">i", comp[cs_off:cs_off + 4])[0]
    except Exception:
        return None
    cstart = comp_off + cs_off + 4
    top = _pb_top_fields(data[cstart:cstart + clen], cstart)
    f3 = next((t for t in top if t[0] == 3 and t[1] == 2), None)
    if not f3:
        return None
    sub = _pb_top_fields(data[f3[2]:f3[2] + f3[3]], f3[2])
    m = {f: off for (f, wt, off, ln) in sub if wt == 5}
    try:
        return {"distance": m[SREV_FIELD_DISTANCE],
                "size":     m[SREV_FIELD_SIZE],
                "width":    m[SREV_FIELD_WIDTH]}
    except KeyError:
        return None


def patch_smartreverb(seed_bytes, distance, size, width):
    """Return a copy of a smart:reverb .vstpreset with Distance/Size/Width set
    (each 0..100). Only three fixed-size floats change; every other byte — the
    learned profile, container offsets, trailer — is identical, so the file stays
    valid. Raises ValueError if the seed can't be parsed."""
    data = bytearray(seed_bytes)
    off = _smartreverb_param_offsets(data)
    if not off:
        raise ValueError("not a recognisable smart:reverb preset")
    struct.pack_into("<f", data, off["distance"], float(distance))
    struct.pack_into("<f", data, off["size"], float(size))
    struct.pack_into("<f", data, off["width"], float(width))
    return bytes(data)


def read_smartreverb_values(seed_bytes):
    """Return (distance, size, width) read back from a smart:reverb preset, or None.
    Used to show the user the seed's current values / verify a patch."""
    off = _smartreverb_param_offsets(bytearray(seed_bytes))
    if not off:
        return None
    return tuple(round(struct.unpack_from("<f", seed_bytes, off[k])[0], 2)
                 for k in ("distance", "size", "width"))


# *************** DEL 02h - BLUE CAT'S PATCHWORK CHAIN ASSEMBLER **************
# Blue Cat's PatchWork is a plug-in CHAINER: one PatchWork instance hosts several
# plug-ins in series. Its ".vstpreset" is a VST3 container (same 48-byte header as
# the others) whose Comp chunk is a big XML <Preset>…</Preset>. Inside, each hosted
# plug-in lives in an <objN> slot whose <pluginXXXX … chunk="BASE64"/> attribute
# holds that plug-in's OWN state — and (VERIFIED, byte-for-byte) that decoded chunk
# is EXACTLY the same data the plug-in puts in the Comp chunk of its standalone
# .vstpreset. So we can build one PatchWork preset that carries the whole channel
# strip at once by taking ONE seed PatchWork preset (the user builds it in Cubase
# with the chain they want) and patching each hosted plug-in's chunk the same safe
# way we patch the standalone presets:
#   • Lowtility  → set the low-cut Hz + slope in its <lowtility2> XML
#   • Kirchhoff  → swap in the instrument's .keq JSON
#   • smart:reverb → patch Distance/Size/Width floats in place (or bypass if DRY)
#   • smart:EQ   → LEFT byte-identical (AI-learned 5 MB curve — re-Learn per track)
# Unrecognised plug-ins (e.g. Diablo) are left exactly as the seed has them. We only
# touch slots the seed already contains — PatchWork's chain order/routing is the
# seed's. Verified: re-packing a seed with no edits is byte-identical, and every
# edit changes only the intended bytes + the length fields. NO checksum anywhere.

PW_CLS_LOWTILITY   = "ABCDEF019182FAEB56654E6F44654574"   # Venomode Lowtility 2
PW_CLS_KIRCHHOFF   = "565354356D6267746274656368206B69"   # TBTECH Kirchhoff-EQ
PW_CLS_SMARTEQ     = "565354736D4534736D61727465713400"   # sonible smart:EQ 4
PW_CLS_SMARTREVERB = "565354736D5632736D61727472657665"   # sonible smart:reverb 2

# Friendly names for the report (classID → label).
PW_PLUGIN_NAMES = {
    PW_CLS_LOWTILITY:   "Lowtility 2",
    PW_CLS_KIRCHHOFF:   "Kirchhoff-EQ",
    PW_CLS_SMARTEQ:     "smart:EQ 4",
    PW_CLS_SMARTREVERB: "smart:reverb 2",
}


def _pw_split(data):
    """Split a PatchWork .vstpreset into (classid, comp, info) or None.
    `comp` is the raw Comp chunk (XML, sometimes with 1 trailing byte)."""
    try:
        listoff = struct.unpack("<q", data[40:48])[0]
        n = struct.unpack("<i", data[listoff + 4:listoff + 8])[0]
        p = listoff + 8
        ent = {}
        for _ in range(n):
            cid = data[p:p + 4]
            off = struct.unpack("<q", data[p + 4:p + 12])[0]
            sz = struct.unpack("<q", data[p + 12:p + 20])[0]
            ent[cid] = (off, sz)
            p += 20
        comp = data[ent[b"Comp"][0]:ent[b"Comp"][0] + ent[b"Comp"][1]]
        info = data[ent[b"Info"][0]:ent[b"Info"][0] + ent[b"Info"][1]]
        return data[8:40], comp, info
    except Exception:
        return None


def _pw_build(classid, comp, info):
    """Re-assemble a PatchWork .vstpreset (3-entry List: Comp/Cont/Info)."""
    comp_sz, info_sz = len(comp), len(info)
    listoff = 48 + comp_sz + info_sz
    hdr = b"VST3" + struct.pack("<i", 1) + classid + struct.pack("<q", listoff)
    lst = b"List" + struct.pack("<i", 3)
    lst += b"Comp" + struct.pack("<q", 48) + struct.pack("<q", comp_sz)
    lst += b"Cont" + struct.pack("<q", 48 + comp_sz) + struct.pack("<q", 0)
    lst += b"Info" + struct.pack("<q", 48 + comp_sz) + struct.pack("<q", info_sz)
    return hdr + comp + info + lst


def _pw_comp_text_tail(comp):
    """Return (xml_text, tail_bytes): the Comp XML text up to </Preset> and any
    bytes after it (PatchWork sometimes appends one trailing NUL)."""
    text = comp.decode("utf-8", "replace")
    end = text.rfind("</Preset>")
    if end < 0:
        return text, b""
    cut = end + len("</Preset>")
    tail = comp[len(text[:cut].encode("utf-8")):]
    return text[:cut], tail


def _pw_slot_present(text, cls):
    """True if the Comp XML has a hosted-plugin slot for this classID."""
    return _re.search(r'<plugin' + cls + r' version="\d+" bypassed="\d+" chunk="', text) is not None


def _pw_get_chunk(text, cls):
    """Return (bypass:int, raw_chunk_bytes) for a hosted plugin, or None."""
    m = _re.search(r'<plugin' + cls + r' version="\d+" bypassed="(\d+)" chunk="([A-Za-z0-9+/=]+)"', text)
    if not m:
        return None
    return int(m.group(1)), base64.b64decode(m.group(2))


def _pw_set_chunk(text, cls, new_chunk_bytes, bypass=None):
    """Replace a hosted plugin's chunk (and optionally its bypass flag). Returns
    the new XML text. Only the first matching slot is touched."""
    new_b64 = base64.b64encode(new_chunk_bytes).decode("ascii")

    def repl(m):
        byp = m.group(1) if bypass is None else str(int(bypass))
        return f'<plugin{cls} version="{m.group("v")}" bypassed="{byp}" chunk="{new_b64}"'
    pat = r'<plugin' + cls + r' version="(?P<v>\d+)" bypassed="(\d+)" chunk="[A-Za-z0-9+/=]+"'
    return _re.sub(pat, repl, text, count=1)


# ---- per-plugin chunk patchers (operate on the RAW embedded chunk) ----------
def _pw_patch_lowtility_chunk(chunk, hz, slope_db):
    """Patch the embedded Lowtility chunk (VC2! + len + XML + trailer)."""
    if chunk[:4] != b"VC2!":
        raise ValueError("not a Lowtility chunk")
    xlen = struct.unpack("<i", chunk[4:8])[0]
    xml = chunk[8:8 + xlen]
    trailer = chunk[8 + xlen:]
    idx = LOWTILITY_SLOPE_INDEX.get(int(slope_db), max(0, min(3, round(slope_db / 12) - 1)))

    def setp(pid, val, x):
        pat = b'(id="' + pid + b'" value=")[^"]*(")'
        new, _n = _re.subn(pat, lambda m: m.group(1) + val + m.group(2), x)
        return new
    xml = setp(b"frequencycut", f"{float(hz):.1f}".encode(), xml)
    xml = setp(b"slope", f"{float(idx):.1f}".encode(), xml)
    xml = setp(b"enablecut", b"1.0", xml)
    return b"VC2!" + struct.pack("<i", len(xml)) + xml + trailer


def _pw_patch_kirchhoff_chunk(chunk, json_bytes):
    """Patch the embedded Kirchhoff chunk (JUCE VstW/CcnK/FBCh wrapper + .keq JSON)."""
    cs_off = chunk.find(b"FBCh") + 4 * 5 + 128
    if cs_off < 4 * 5 + 128:
        raise ValueError("not a Kirchhoff chunk")
    old_len = struct.unpack(">i", chunk[cs_off:cs_off + 4])[0]
    json_start = cs_off + 4
    payload = chunk[json_start:json_start + old_len]
    s = payload.decode("utf-8")
    jend = json.JSONDecoder().raw_decode(s)[1]
    trailer = payload[len(s[:jend].encode("utf-8")):]
    new_payload = json_bytes + trailer
    comp = bytearray(chunk[:json_start] + new_payload)
    struct.pack_into(">i", comp, cs_off, len(new_payload))    # FBCh chunkSize (BE)
    struct.pack_into(">i", comp, 20, len(comp) - 24)          # CcnK byteSize (BE)
    return bytes(comp)


def _pw_smartreverb_offsets(chunk):
    """Distance/Size/Width float offsets inside an embedded smart:reverb chunk."""
    fb = chunk.find(b"FBCh")
    if fb < 0:
        return None
    cs_off = fb + 4 * 5 + 128
    try:
        clen = struct.unpack(">i", chunk[cs_off:cs_off + 4])[0]
    except Exception:
        return None
    cstart = cs_off + 4
    top = _pb_top_fields(chunk[cstart:cstart + clen], cstart)
    f3 = next((t for t in top if t[0] == 3 and t[1] == 2), None)
    if not f3:
        return None
    sub = _pb_top_fields(chunk[f3[2]:f3[2] + f3[3]], f3[2])
    m = {f: off for (f, wt, off, ln) in sub if wt == 5}
    try:
        return {"distance": m[SREV_FIELD_DISTANCE],
                "size":     m[SREV_FIELD_SIZE],
                "width":    m[SREV_FIELD_WIDTH]}
    except KeyError:
        return None


def _pw_patch_smartreverb_chunk(chunk, distance, size, width):
    """Patch Distance/Size/Width floats in place in an embedded smart:reverb chunk."""
    off = _pw_smartreverb_offsets(chunk)
    if not off:
        raise ValueError("not a recognisable smart:reverb chunk")
    b = bytearray(chunk)
    struct.pack_into("<f", b, off["distance"], float(distance))
    struct.pack_into("<f", b, off["size"], float(size))
    struct.pack_into("<f", b, off["width"], float(width))
    return bytes(b)


def _pw_read_smartreverb_chunk(chunk):
    off = _pw_smartreverb_offsets(chunk)
    if not off:
        return None
    return tuple(round(struct.unpack_from("<f", chunk, off[k])[0], 2)
                 for k in ("distance", "size", "width"))


def pw_recognised_slots(seed_bytes):
    """Return the set of classIDs (from PW_PLUGIN_NAMES) the seed actually hosts."""
    parts = _pw_split(seed_bytes)
    if not parts:
        return set()
    text, _tail = _pw_comp_text_tail(parts[1])
    return {cls for cls in PW_PLUGIN_NAMES if _pw_slot_present(text, cls)}


def assemble_patchwork(seed_bytes, *, lowtility=None, kirchhoff_json=None,
                       smartreverb=None, bypass_reverb=False, progname=None):
    """Build a PatchWork .vstpreset from a seed, patching only the hosted plug-ins
    that the seed contains AND that are requested:
        lowtility      = (hz, slope_db)         or None to leave alone
        kirchhoff_json = .keq JSON bytes        or None
        smartreverb    = (distance, size, width) or None
        bypass_reverb  = True → set the reverb slot bypassed (DRY instruments)
        progname       = PatchWork program name to stamp into the <Preset>
    Returns (bytes, touched) where `touched` is a list of plugin labels changed.
    Raises ValueError if the seed can't be parsed."""
    parts = _pw_split(seed_bytes)
    if not parts:
        raise ValueError("not a recognisable PatchWork preset")
    classid, comp, info = parts
    text, tail = _pw_comp_text_tail(comp)
    touched = []

    if lowtility is not None and _pw_slot_present(text, PW_CLS_LOWTILITY):
        cur = _pw_get_chunk(text, PW_CLS_LOWTILITY)
        if cur:
            new = _pw_patch_lowtility_chunk(cur[1], lowtility[0], lowtility[1])
            text = _pw_set_chunk(text, PW_CLS_LOWTILITY, new, bypass=0)
            touched.append(PW_PLUGIN_NAMES[PW_CLS_LOWTILITY])

    if kirchhoff_json is not None and _pw_slot_present(text, PW_CLS_KIRCHHOFF):
        cur = _pw_get_chunk(text, PW_CLS_KIRCHHOFF)
        if cur:
            new = _pw_patch_kirchhoff_chunk(cur[1], kirchhoff_json)
            text = _pw_set_chunk(text, PW_CLS_KIRCHHOFF, new, bypass=0)
            touched.append(PW_PLUGIN_NAMES[PW_CLS_KIRCHHOFF])

    if _pw_slot_present(text, PW_CLS_SMARTREVERB):
        if bypass_reverb:
            cur = _pw_get_chunk(text, PW_CLS_SMARTREVERB)
            if cur:                                  # keep chunk, just bypass it
                text = _pw_set_chunk(text, PW_CLS_SMARTREVERB, cur[1], bypass=1)
                touched.append(PW_PLUGIN_NAMES[PW_CLS_SMARTREVERB] + " (bypassed/DRY)")
        elif smartreverb is not None:
            cur = _pw_get_chunk(text, PW_CLS_SMARTREVERB)
            if cur:
                new = _pw_patch_smartreverb_chunk(cur[1], *smartreverb)
                text = _pw_set_chunk(text, PW_CLS_SMARTREVERB, new, bypass=0)
                touched.append(PW_PLUGIN_NAMES[PW_CLS_SMARTREVERB])

    if progname:
        safe = _re.sub(r'[<>&"]', "", str(progname))[:64]
        text = _re.sub(r'(<Preset\b[^>]*?\bprogName=")[^"]*(")',
                       lambda m: m.group(1) + safe + m.group(2), text, count=1)

    new_comp = text.encode("utf-8") + tail
    return _pw_build(classid, new_comp, info), touched


# *************** DEL 02i - BUS ROADMAP (routing tree) ***********************
# The ROADMAP is the picture the Channel Plan never drew: what feeds what, all
# the way from a single channel up to the master. Two things shape it:
#
#   1) YOUR drum convention:
#        Kick + Snare                     -> Drums: Front
#        Toms                             -> Drums: Toms
#        Drums: Toms + Hi-Hat + Ride      -> Drums: Mid
#        Cymbals                          -> Drums: Cymbals
#        Drums: Cymbals + Percussion      -> Drums: Back
#        Front + Mid + Back               -> Drums: All
#      The payoff: one fader per section, and identical VSTs (e.g. all the tom
#      plug-ins) can live ONCE on the section bus instead of once per channel.
#
#   2) The smart:EQ 10-slot budget. A bus is exactly what carries ONE smart:EQ
#      instance, so the routing tree and the group plan are the same problem.
#
# A sub-bus is only created when it EARNS its place: it needs at least two
# sources under it. One lonely tom does not get a "Drums: Toms" bus - the
# builder dissolves it into its parent automatically.

ROADMAP_MASTER = "Master"

# instrument id -> the LOWEST bus it feeds. Ids not listed go straight to Master.
BUS_LEAF = {
    # --- Drums (your convention, above) ---
    "kick":            "Drums: Front",
    "snare":           "Drums: Front",
    "toms":            "Drums: Toms",
    "hihat":           "Drums: Mid",
    "ride":            "Drums: Mid",
    "cymbals":         "Drums: Cymbals",
    "percussion":      "Drums: Back",
    "hand_drums":      "Drums: Back",
    # --- Bass (one bus as soon as you have more than one bass part) ---
    "bass_root":       "Bass",
    "bass_loop":       "Bass",
    "double_bass":     "Bass",      # plays the bass role, not a string-bed role
    # --- Guitars ---
    "guitar_rhythm":   "Guitars",
    "guitar_chords":   "Guitars",
    "guitar_single_low": "Guitars",
    "guitar_acoustic": "Guitars",
    # --- Vocals: the lead keeps its own path, everything else is a bed ---
    "vocals_lead":     "Vocals: Lead",
    "vocals_backing":  "Vocals: Back",
    "vocals_choir_pad": "Vocals: Back",
    "vocals_extra":    "Vocals: Back",
    # --- A LEAD keeps its own path: organ_lead, brass_lead and strings_lead
    #     are deliberately NOT listed, so they go straight to Master instead of
    #     riding a background fader. Pull Background: All (or Horns) down and
    #     the part carrying the tune must NOT go down with it.
    # --- Backgrounds, split the way you split them ---
    "organ":           "Background: Keys",
    "accordion":       "Background: Keys",
    "piano_bg":        "Background: Keys",
    "piano_riff":      "Background: Keys",
    "synth_pad":       "Background: Keys",
    "synth_pluck":     "Background: Keys",
    "synth_mallet":    "Background: Keys",
    # The two BEDS added in v3.1 ride the background buses, exactly like the
    # cards they sit behind. Their LEAD halves (plain Flute, plain Violin) are
    # left on those buses too - moving them would silently re-route sessions
    # that already exist - while the brand-new lead ids go straight to Master.
    "flute_bg":        "Background: Winds",
    "violin_bg":       "Background: Strings",
    "flute":           "Background: Winds",
    "brass":           "Background: Winds",
    "trumpet":         "Horns",
    "trombone":        "Horns",
    "tenor_trombone":        "Horns",
    "tenor_bass_trombone":        "Horns",
    "saxophone":       "Horns",
    "horn_section":    "Horns",
    "harmonica":       "Background: Winds",
    "woodwind":        "Background: Winds",
    "clarinet":        "Background: Winds",
    "oboe":            "Background: Winds",
    "bassoon":         "Background: Winds",
    "contrabassoon":   "Background: Winds",
    "flugelhorn":      "Horns",
    "french_horn":     "Horns",
    "tuba":            "Horns",
    "english_horn":    "Background: Winds",
    "euphonium":       "Horns",
    "bass_clarinet":   "Background: Winds",
    "contrabass_clarinet": "Background: Winds",
    "double_bass_section": "Bass",
    "piccolo": "Background: Winds",
    "alto_flute": "Background: Winds",
    "bass_flute": "Background: Winds",
    "soprano_sax": "Horns",
    "alto_sax": "Horns",
    "tenor_sax": "Horns",
    "baritone_sax": "Horns",
    "piccolo_trumpet": "Horns",
    "alto_trombone": "Horns",
    "bass_trombone": "Horns",
    "double_bass_trombone": "Horns",
    "violin":          "Background: Strings",
    "viola":           "Background: Strings",
    "cello":           "Background: Strings",
    "string_section":  "Background: Strings",
}

# bus -> parent bus. Anything not listed feeds the master directly.
BUS_PARENT = {
    "Drums: Toms":         "Drums: Mid",
    "Drums: Cymbals":      "Drums: Back",
    "Drums: Front":        "Drums: All",
    "Drums: Mid":          "Drums: All",
    "Drums: Back":         "Drums: All",
    "Drums: All":          ROADMAP_MASTER,
    "Bass":                ROADMAP_MASTER,
    "Guitars":             ROADMAP_MASTER,
    "Vocals: Lead":        ROADMAP_MASTER,
    "Vocals: Back":        ROADMAP_MASTER,
    "Horns":               "Background: All",
    "Background: Keys":    "Background: All",
    "Background: Winds":   "Background: All",
    "Background: Strings": "Background: All",
    "Background: All":     ROADMAP_MASTER,
}

# Draw order, top -> bottom, so the roadmap always reads the same way.
BUS_ORDER = [
    "Vocals: Lead", "Vocals: Back",
    "Drums: Front", "Drums: Toms", "Drums: Mid", "Drums: Cymbals",
    "Drums: Back", "Drums: All",
    "Bass", "Guitars", "Horns",
    "Background: Keys", "Background: Winds", "Background: Strings",
    "Background: All",
    ROADMAP_MASTER,
]

# Why each bus is worth making - printed under its name so the roadmap teaches
# rather than just lists.
BUS_WHY = {
    "Drums: Front":  "Kick + snare = the backbeat. One fader for the punch of the song.",
    "Drums: Toms":   "All toms together - and the tom plug-ins can live HERE once "
                     "instead of on every single tom channel.",
    "Drums: Mid":    "Toms + hats + ride: the timekeeping/mid layer of the kit.",
    "Drums: Cymbals": "Crashes and washes together - one place to tame the top end.",
    "Drums: Back":   "Cymbals + percussion: the airy back of the kit.",
    "Drums: All":    "The whole kit on one fader. Pull this down and the drums step "
                     "back without touching a single channel.",
    "Bass":          "More than one bass part (root + loop, or bass + bass x) needs "
                     "one shared low end — and, IF the song has a kick, one shared "
                     "duck against it: ONE Trackspacer here instead of one per "
                     "bass. (No kick? Then there is nothing to duck against.) "
                     "Note that smart:EQ "
                     "still ranks each bass separately by default: routing them "
                     "together (this bus) and unmasking them together (one group "
                     "slot) are two different decisions. Take the 'Bass' merge in "
                     "the 🎯 smart:EQ window if you want both.",
    "Guitars":       "All guitars share one glue comp, one level move, one smart:EQ slot.",
    "Horns":         "Trumpet + sax + trombone are ONE instrument in the arrangement, so "
                     "give them one fader, one glue comp, one reverb send and ONE "
                     "Trackspacer ducking the whole section under the vocal. Three "
                     "separate duckers on three horns just means three different "
                     "amounts of wrong.",
    "Vocals: Lead":  "The lead keeps its own path - its reverb, its duck source, its "
                     "level automation.",
    "Vocals: Back":  "Backing vocals and choir/vocal pads move together, always.",
    "Background: Keys":    "Piano, organ, pads, plucks, mallets - the harmonic bed.",
    "Background: Winds":   "Brass and woodwinds - the same job, the same treatment.",
    "Background: Strings": "Violin/viola/cello/section - the string bed.",
    "Background: All":     "Every background on one fader: instant 'push the arrangement "
                           "back behind the vocal'.",
    ROADMAP_MASTER: "Auto-mastering tools ONLY (limiter / loudness), never on channels.",
}

# What actually belongs ON a bus (as opposed to on a channel).
BUS_DO = (
    "On a bus:  glue compressor (2:1, 1-3 dB) - smart:EQ (this is the slot) - "
    "the section fader.\n"
    "NOT on a bus:  the low cut (that is per channel, Lowtility) and a second "
    "high-pass. Do the HP once, on the channel."
)

BUS_MIN_SOURCES = 2      # a bus needs at least this many channels under it


def build_roadmap(ids, counts=None):
    """Build the routing tree for the given instrument ids.

    counts = {id: how many copies of this instrument} (a channel with count 3
    counts as 3 sources, so e.g. three toms DO earn a 'Drums: Toms' bus).

    Returns (nodes, roots) where nodes[bus] = {
        'name', 'parent', 'children' [bus names], 'members' [(id, name, n)],
        'sources' (total channels in the whole subtree), 'depth'
    }. Buses with fewer than BUS_MIN_SOURCES sources under them are dissolved
    into their parent, so you never end up making a bus for one channel.
    """
    counts = counts or {}
    id2inst = {x["id"]: x for x in EQ_DATA}

    # 1. Seed every bus that any selected instrument touches, plus its ancestors.
    nodes = {ROADMAP_MASTER: {"name": ROADMAP_MASTER, "parent": None,
                              "children": [], "members": [], "sources": 0}}

    def ensure(bus):
        if bus in nodes:
            return
        parent = BUS_PARENT.get(bus, ROADMAP_MASTER)
        ensure(parent)
        nodes[bus] = {"name": bus, "parent": parent, "children": [],
                      "members": [], "sources": 0}
        nodes[parent]["children"].append(bus)

    for iid in ids:
        inst = id2inst.get(iid)
        if not inst:
            continue
        bus = BUS_LEAF.get(iid, ROADMAP_MASTER)
        ensure(bus)
        nodes[bus]["members"].append((iid, inst["name"], max(1, int(counts.get(iid, 1)))))

    # 2. Count sources bottom-up.
    def count(bus):
        n = sum(c for _i, _n, c in nodes[bus]["members"])
        for ch in nodes[bus]["children"]:
            n += count(ch)
        nodes[bus]["sources"] = n
        return n
    count(ROADMAP_MASTER)

    # 3. Dissolve buses that did not earn their place: too few sources under
    #    them, or a pure pass-through (one child, no members of its own).
    changed = True
    while changed:
        changed = False
        for bus in [b for b in nodes if b != ROADMAP_MASTER]:
            n = nodes[bus]
            too_small = n["sources"] < BUS_MIN_SOURCES
            passthru = (not n["members"]) and len(n["children"]) == 1
            if not (too_small or passthru):
                continue
            parent = nodes[n["parent"]]
            parent["members"].extend(n["members"])
            parent["children"].remove(bus)
            for ch in n["children"]:
                nodes[ch]["parent"] = parent["name"]
                parent["children"].append(ch)
            del nodes[bus]
            changed = True
            break

    # 4. Sort children/members into the fixed draw order + assign depth.
    order = {b: i for i, b in enumerate(BUS_ORDER)}
    for n in nodes.values():
        n["children"].sort(key=lambda b: order.get(b, 99))

    def setdepth(bus, d):
        nodes[bus]["depth"] = d
        for ch in nodes[bus]["children"]:
            setdepth(ch, d + 1)
    setdepth(ROADMAP_MASTER, 0)

    return nodes, nodes[ROADMAP_MASTER]["children"]


# ---- smart:EQ merge candidates ----------------------------------------------
# smart:EQ 4 gives you 10 group slots. The family-per-tier plan can easily need
# 11-14. These are the merges that cost you the least, BEST FIRST. The program
# shows them all (each in its own colour) and applies them from the top until the
# plan fits - so it never just says "11 > 10" and leaves you to figure it out.
#
# A spec matches a bus when the bus's FAMILY is in 'fams' and (if 'tier' is set)
# the bus sits in that tier. A merge is only offered when it would swallow at
# least two buses. Merged buses take the family in 'newfam', so a later spec can
# swallow them again (Keys+Strings -> Beds, then Beds+Vocals -> Beds).
SMARTEQ_MERGE_COLOURS = ["#ffb454", "#5ad1e6", "#9fe07f", "#e68fd1",
                         "#c79fe6", "#e6a07f", "#9fb6e6", "#bfe67f"]

SMARTEQ_MERGES = [
    # (id, tier, fams, new bus name, new family, why)
    ("beds_back", "back", {"Keys/Winds", "Strings"}, "Beds", "Beds",
     "Pads, keys, brass beds and string beds all do the same job back there: "
     "hold the harmony and stay out of the way. One bus, one smart:EQ, one "
     "fader. This is the cheapest merge there is."),
    ("beds_back_vox", "back", {"Beds", "Vocals"}, "Beds + Choir", "Beds",
     "Backing vocals and a sampled choir are just another bed - they yield to "
     "the lead exactly like the pads do."),
    ("beds_mid", "mid", {"Keys/Winds", "Strings"}, "Beds", "Beds",
     "The mid-tier keys and strings support in the same way and rarely need to "
     "be unmasked against each other."),
    ("gtr_all", None, {"Guitars"}, "Guitars", "Guitars",
     "All guitars onto one bus regardless of tier. You lose per-tier unmasking "
     "between rhythm and chord guitar - usually no loss at all, they are "
     "supposed to blend."),
    ("drums_all", None, {"Drums"}, "Drums: All", "Drums",
     "The whole kit onto Drums: All - one smart:EQ for every drum tier. You "
     "lose kick/snare-vs-cymbals unmasking, so keep this one for later."),
    ("bass_all", None, {"Bass"}, "Bass", "Bass",
     "Every bass part onto the Bass bus, with ONE smart:EQ for all of them. This "
     "is the one merge that touches the solo basses, so it is deliberately far "
     "down the list: their low-end placement genuinely differs, and you lose the "
     "per-bass ranking against the kick. Worth it when the alternative is not "
     "fitting at all — and it matches how you route them anyway."),
    ("beds_all", None, {"Beds", "Keys/Winds", "Strings"}, "Beds (all tiers)", "Beds",
     "Every bed, both tiers, one bus. The bluntest merge in the list - only "
     "when nothing else gets you under 10."),
]

TIER_RANK = {"front": 0, "mid": 1, "back": 2}


def merge_bus_name(spec):
    """The bus name a merge produces — tier-specific merges keep the tier in the
    name so a BACK 'Beds' and a MID 'Beds' never look like the same bus."""
    _mid, tier, _fams, name, _newfam, _why = spec
    return f"{name} · {tier.upper()}" if tier else name


# *************** DEL 03 - HELPERS ********************************************

def no_blink(w):
    """Disable cursor blink on any tk.Entry or tk.Text widget."""
    try:
        w.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass


def get_base_dir():
    """Return directory of this script/exe, always correct even as .exe."""
    if getattr(sys, "frozen", False):
        return _program_home()
    return _program_home()


def get_helpfiles_dir(sub=""):
    base = os.path.join(get_base_dir(), "Helpfiles")
    if sub:
        base = os.path.join(base, sub)
    os.makedirs(base, exist_ok=True)
    return base


# All generated-preset backups live UNDER one tidy 'Presets' folder in Helpfiles
# (one sub-folder per plugin), instead of three separate top-level folders.
PRESETS_KIRCHHOFF   = os.path.join("Presets", "Kirchhoff")
PRESETS_SMARTREVERB = os.path.join("Presets", "SmartReverb")
PRESETS_LOWTILITY   = os.path.join("Presets", "Lowtility")
PRESETS_SUBMASS     = os.path.join("Presets", "SubMass")
PRESETS_PATCHWORK   = os.path.join("Presets", "PatchWork")
PRESETS_CORRIDOR    = os.path.join("Presets", "Corridor")
PRESETS_OMEGA       = os.path.join("Presets", "Omega")
PRESETS_BANDWIDTH   = os.path.join("Presets", "Bandwidth")
PRESETS_CASCADIA    = os.path.join("Presets", "Cascadia")
PRESETS_VSTAGE      = os.path.join("Presets", "VirtualStage")
PRESETS_KNOCK       = os.path.join("Presets", "Knock")


def migrate_helpfiles_presets():
    """One-time tidy-up: move the OLD top-level preset folders into
    Helpfiles/Presets/<plugin>/. Runs only when the old folder exists and the new
    one does not yet — so it migrates once and never loses anything (incl. the
    Kirchhoff registry.json that the dedup/naming relies on)."""
    import shutil
    hp = os.path.join(get_base_dir(), "Helpfiles")
    pairs = [("KirchhoffPresets", PRESETS_KIRCHHOFF),
             ("SoniblePresets",   PRESETS_SMARTREVERB),
             ("LowtilityPresets", PRESETS_LOWTILITY),
             ("SweetEQPresets",   os.path.join("Presets", "SweetEQ"))]  # leftover, tidy too
    for old, new in pairs:
        old_p, new_p = os.path.join(hp, old), os.path.join(hp, new)
        if os.path.isdir(old_p) and not os.path.exists(new_p):
            try:
                os.makedirs(os.path.dirname(new_p), exist_ok=True)
                shutil.move(old_p, new_p)
            except Exception:
                pass


def get_log_path():
    log_dir = get_helpfiles_dir("0---Empty")
    return os.path.join(log_dir, "crash_log.txt")


def _documents_dir():
    """Best-effort path to the user's Documents folder (where sonible keeps its
    'VST3 Presets' tree). Used only as a default; the user can override the folder."""
    up = os.environ.get("USERPROFILE", "")
    if up and os.path.isdir(os.path.join(up, "Documents")):
        return os.path.join(up, "Documents")
    return os.path.expanduser(os.path.join("~", "Documents"))


def write_crash_log(exc_text):
    try:
        path = get_log_path()
        with open(path, "a", encoding="utf-8") as f:
            f.write(f"\n{'='*60}\n")
            f.write(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(exc_text)
    except Exception:
        pass


def _set_window_icon(root):
    """Set window icon via both tkinter API and Win32 SendMessage."""
    if platform.system() != "Windows":
        return
    base = get_base_dir()
    prog = os.path.splitext(os.path.basename(__file__))[0]
    ico  = os.path.join(base, "Icons", f"{prog}.ico")
    if not os.path.isfile(ico):
        return
    try:
        root.iconbitmap(ico)
    except Exception:
        pass
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080
        hwnd = user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico, IMAGE_ICON, 0,  0,  LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico, IMAGE_ICON, 16, 16, LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


def auto_close_popup(top, ms=1000):
    """Close a Toplevel after ms milliseconds."""
    top.after(ms, top.destroy)


# *************** DEL 04 - SETTINGS *******************************************

DEFAULT_SETTINGS = {
    "geometry": "1300x820",
    "sash_pos": 340,
    "tab_index": 0,
    "checked": [],            # list of instrument IDs that are checked
    # Right panel: which view opens, and which sections the 📋 Instruments view
    # shows. Defaults are what you actually work in — Instruments, filtered to
    # EQ-group + Duck + Reverb — instead of Channel Plan with everything on.
    # Both are remembered between runs, so changing them in the UI sticks.
    "right_mode": "instruments",
    "instr_filters": ["eqgroup", "duck", "reverb"],
    # ---- ORDER of the channels in the right panel (2026-09-14) -------------
    # "pick"     = the order the instruments stand in the picker on the left,
    #              i.e. the order you tick them: all the guitars after each
    #              other, all the drums after each other. THE DEFAULT — it is
    #              the way you think about a song.
    # "position" = the old behaviour: split by where the channel sits in the
    #              room. 📐 Channel Plan splits FRONT / MID / BACK (the
    #              smart:EQ priority); 📋 Instruments splits Front / Near /
    #              Mid / Far / DRY (the reverb bus). Right when you are
    #              ROUTING, wrong when you are looking for "the other guitar".
    # One ⇅ button on the right panel's View row swaps the two.
    "list_order": "pick",
    "eq_mode": "kirchhoff",   # "kirchhoff" (Parametric Q, default) | "range" (start–end)
    "keq_dir": "",            # Kirchhoff presets folder ("" = auto: %APPDATA%\ThreeBodyTech\KirchhoffEQ\presets)
    "keq_bake_ms": True,      # bake Mid/Side Stereo Placement into generated presets (default ON — codes verified)
    "keq_no_hp": False,       # omit the High-Pass band from generated presets (Lowtility does the HP)
    "keq_make_vst3": True,    # also write a Cubase .vstpreset (so presets show in Cubase's own preset browser)
    "keq_vst3_dir": "",       # Kirchhoff .vstpreset folder ("" = auto: Documents\VST3 Presets\Plugin Alliance\TBTECH Kirchhoff-EQ)
    "smartreverb_dir": "",    # sonible smart:reverb 2 preset folder ("" = auto: Documents\VST3 Presets\sonible\smartReverb2)
    "sonible_per_tier": False,  # write ONE smart:reverb preset per depth tier (bus workflow) instead of one per instrument
    "lowtility_dir": "",      # Venomode Lowtility 2 preset folder ("" = auto: Documents\VST3 Presets\Venomode\Lowtility 2)
    "submass_dir": "",        # DSPTone SubMass preset folder ("" = auto: Documents\VST3 Presets\DSPTone\SubMass)
    "corridor_dir": "",       # Quantastical Sound Corridor preset folder ("" = auto: Documents\VST3 Presets\Quantastical Sound\Corridor)
    "omega_dir": "",          # Kush Audio Omega 2 458a preset folder ("" = auto: Documents\VST3 Presets\Kush Audio\Omega 2 458a)
    "cascadia_native_dir": "",  # Cascadia's OWN browser folder ("" = auto: Documents\iZotope\Cascadia\Presets)
    "cascadia_dir": "",       # iZotope Cascadia .vstpreset folder ("" = auto: Documents\VST3 Presets\iZotope\Cascadia)
    "vstage_dir": "",         # EVA Instruments Virtual Stage .vstpreset folder ("" = auto: Documents\VST3 Presets\EVA Instruments\Virtual Stage)
    "bandwidth_dir": "",      # In The Mix Bandwidth user preset folder ("" = auto: C:\ProgramData\In The Mix\Bandwidth\Presets\User)
    "knock_version": "1",     # which KNOCK Generate > Knock presets writes: "1" (Plugins That Knock) or "2" (Knock Audio) - DEL 02e3
    "knock1_dir": "",         # KNOCK 1 .vstpreset folder ("" = auto: Documents\VST3 Presets\Plugins That Knock\KNOCK)
    "knock2_dir": "",         # KNOCK 2 .vstpreset folder ("" = auto: Documents\VST3 Presets\Knock Audio\KNOCK 2)
    "knock2_user_dir": "",    # KNOCK 2 native .k2p folder, the plug-in's own browser ("" = auto: C:\ProgramData\Knock Audio\KNOCK 2\Presets\User)
    "patchwork_dir": "",      # Blue Cat's PatchWork preset folder ("" = auto: Documents\VST3 Presets\Blue Cat Audio\Blue Cat's PatchWork)
    # 🦻 Hearing profile: {band_key: "ok"|"weak"|"lost"}. Empty = the program
    # behaves exactly as before (no marks, no caps). See DEL 02k.
    "hearing": {},
    # ★ The plug-ins pinned to the top of the 🧩 Plugins tab. None = use
    # FOCUS_DEFAULT the first time, then whatever the user stars.
    "focus_plugins": None,
    # 🎪 Virtual Stage map: "audience" (hi-hat on the RIGHT) or "drummer".
    "stage_perspective": "audience",
    # 📚 The per-group EQ-card tabs. False = working mode: the window is
    # just ★ Song Variants + 🧩 Plugins, and the theory is one View click
    # away. Nothing is removed either way.
    "show_theory_tabs": True,
    # 🔎 FOCUS VIEW (2026-09-14) — the two-faced window. ON = the short face:
    # "Instruments in this variant" on the left, "Selected Instruments" on the
    # right with its three View buttons and its Filter row, and nothing else.
    # OFF = the long face, every panel this program has ever had. One button
    # in the title bar swaps between them and the choice is remembered.
    # Default ON: that IS the way he works. See _apply_focus_view().
    "focus_view": True,
    # ---- HOW MUCH PROSE (DEL 05, _note_label) ------------------------------
    # Every explanatory line in this program is one of two things:
    #   ESSENTIAL — it tells you what to DIAL IN ("Side-chain = Kick",
    #               "High Cut ~150 Hz · Amount ~12–20%"). Never hidden.
    #   EXTRA     — it tells you WHY the number is the number ("The top of the
    #               sweep stops at ~R42 because the hi-hat is there"). Useful
    #               once, then it is just scrolling.
    # Extra comments are OFF by default so the working views stay compact; the
    # Stage map and the Explain windows always show everything, because that is
    # what they are for.
    "show_details": False,         # the Details box: lines of values a preset sets for you
    "show_extra_comments": False,
    # When a section ends up with a head line and no comment under it, drop the
    # blank row instead of leaving a gap. ON by default.
    "hide_empty_note_rows": True,
    # ---- Δ DEFAULTS (DEL 02p) ------------------------------------------
    # ON by default, because it is the switch that turns a nine-plug-in
    # channel strip into a short list of things this song actually needs.
    # A field that matches the instrument's default goes grey; what stays
    # in colour is what has to be dialled.
    "show_default_diff": True,
    # Where a default comes from: "band" = ONE line-up, his own default band,
    # with everything else placed as a guest inside it (the default, and what
    # he asked for); "typical" = a vote over the built-in reference songs;
    # "variants" = a vote over his own saved song variants.
    "defaults_from": "band",
    # ---- ⟳ UPDATE: the left side waits until you say so (2026-09-23) ----
    # ON by default, and that IS the point of it. Ticking one cymbal on the
    # left used to rebuild the whole right-hand panel on the spot: a flash
    # and a jump to the top of the scroll for every single click, while you
    # are still deciding what the song even is. With this on, the left side
    # is a scratch pad - tick, untick and change counts as much as you like -
    # and the panel takes the lot in at once when you click ⟳ Update.
    # The RIGHT side is not affected: change something there and it still
    # updates the moment you touch it. Two ways round, and you pick per
    # action which one you want.
    "hold_left_updates": True,
}


def load_settings():
    try:
        if os.path.isfile(SETTINGS_FILE):
            with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
            s = dict(DEFAULT_SETTINGS)
            s.update(data)
            return s
    except Exception:
        pass
    return dict(DEFAULT_SETTINGS)


def save_settings(s):
    try:
        os.makedirs(os.path.dirname(SETTINGS_FILE), exist_ok=True)
        with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
            json.dump(s, f, indent=2)
    except Exception:
        pass


# *************** DEL 04b - SONG VARIANTS (Tab 7) ****************************
# A "song variant" = a named set of instruments the user mixes together.
#   {"name": str, "fixed": [inst_id...], "counts": {inst_id: int}}
# 'fixed'  = the instruments in this mix (the program remembers them between runs).
# 'counts' = how MANY of each you have in this variant (default 1). A count > 1
#            (e.g. two chord guitars, three plopp-synths) changes the advice:
#            duplicate parts of the same instrument need panning apart / slight EQ
#            differences so they widen instead of pile up and mask each other.
# (Older files used a 'temp' list for temporary additions; on load those are merged
#  into 'fixed' and 'temp' is dropped — the count field replaces that concept.)

VALID_IDS = {inst["id"] for inst in EQ_DATA}

MAX_INSTRUMENT_COUNT = 9   # how many instances of one instrument a variant can list

DEFAULT_VARIANT = {
    "name":  "My Default",
    "fixed": ["bass_root", "bass_loop", "guitar_chords", "guitar_rhythm",
              "kick", "snare", "hihat", "cymbals", "toms", "percussion", "organ"],
    "counts": {},
    # 🎪 Hand placements on the Virtual Stage - see
    # stage_overrides_clean() in DEL 02m. Per SONG and not per program:
    # whether a piano riff is the hook or the bed underneath it is a fact
    # about the arrangement, and it changes from song to song.
    "stage_manual": {},
    # v3.25: {instrument id: [pair number 1-9, priority 1-9]} - see clean_pairs().
    "pairs": {},
    # v3.26: ids run as SWAM instruments (placed in SWAM's own room, Virtual Stage OFF).
    "swam": [],
    "swam_sec": [],      # v3.29: the SWAM parts run in a Section plug-in
}


def clean_ground(raw):
    """The ⚓ Ground line-up, sanitised - or None.

    Ground is a SNAPSHOT, not a pointer at a variant. A pointer would be
    tidier right up to the evening the variant it points at is renamed or
    deleted, and then the one button that is supposed to always work would
    be the one that does nothing."""
    if not isinstance(raw, dict):
        return None
    try:
        fixed = [i for i in (raw.get("fixed") or []) if i in VALID_IDS]
        if not fixed:
            return None
        counts = raw.get("counts") or {}
        out = {}
        for i in fixed:
            try:
                out[i] = max(1, min(MAX_INSTRUMENT_COUNT,
                                    int(counts.get(i, 1))))
            except (TypeError, ValueError):
                out[i] = 1
        return {"name": str(raw.get("name") or "Ground"),
                "fixed": fixed, "counts": out,
                "stage_manual": stage_overrides_clean(raw.get("stage_manual")),
                "pairs": clean_pairs(raw.get("pairs")),
                "swam": clean_swam(raw.get("swam")),
                "swam_sec": clean_swam_sec(raw.get("swam_sec"), clean_swam(raw.get("swam")))}
    except Exception:
        return None


# *************** DEL 04c - PAIRS + PRIORITY (v3.25) **************************
# Two numbers at the far right of every row in "Instruments in this variant":
#   PAIR  0-9  parts with the SAME number (1-9) are ONE level - a pad that plays a
#              fairly straight line together: chord guitar + background organ, or a
#              viola and a violin that the program would otherwise rank apart.
#              0 = not in a pair.
#   PRIO  1-9  who OWNS that level (9 = most). Only means something inside a pair.
# What a pair does, for the parts that are ticked and paired (pair_effects):
#   * smart:EQ priority AND reverb depth: every member takes the tier of the OWNER
#     (highest Prio; on a tie the front-most member). A 'dry' member keeps its own
#     reverb tier - reverb on a bass is mud whoever it is paired with.
#   * Virtual Stage: equal Prio and exactly two members = Siblings (a matched pair,
#     one each side). Unequal Prio = the owner(s) become Feature, the rest Support.
#     Anything set by hand in the Stage window wins over what a pair derives.
# Saved per variant under "pairs": {instrument id: [pair, prio]}.
PAIR_MAX = 9
PRIO_MAX = 9
PAIR_CELL_W = 46      # pixels per Pair / Prio box in the Song Variants rows
_SMARTEQ_RANK = {"front": 0, "mid": 1, "back": 2}
_DEPTH_RANK   = {"front": 0, "near": 1, "mid": 2, "far": 3}   # 'dry' is left out on purpose


def clean_pairs(raw):
    """{id: [pair 1-9, prio 1-9]}, sanitised. An entry with pair 0 is no entry."""
    out = {}
    if not isinstance(raw, dict):
        return out
    for iid, v in raw.items():
        if iid not in VALID_IDS:
            continue
        try:
            pair, prio = int(v[0]), int(v[1])
        except (TypeError, ValueError, IndexError, KeyError):
            continue
        if 1 <= pair <= PAIR_MAX:
            out[iid] = [pair, max(1, min(PRIO_MAX, prio))]
    return out


def pair_groups(pairs, ticked):
    """{pair number: [ids]} for the pairs that have at least two TICKED members."""
    groups = {}
    for iid, (n, _p) in clean_pairs(pairs).items():
        if iid in ticked:
            groups.setdefault(n, []).append(iid)
    return {n: sorted(ids, key=lambda i: _WRITTEN_POS.get(i, 0))
            for n, ids in groups.items() if len(ids) >= 2}


def pair_effects(pairs, ticked, counts=None):
    """What the pairs change right now.

    Returns {"smarteq": {id: (tier, note)}, "depth": {id: (tier, note)},
             "stage": {id: stage override}}. Only parts whose answer actually
    CHANGES are listed, so an empty dict means the pairs change nothing."""
    pairs = clean_pairs(pairs)
    counts = counts or {}
    out = {"smarteq": {}, "depth": {}, "stage": {}}
    for n, ids in pair_groups(pairs, ticked).items():
        prio = {i: pairs[i][1] for i in ids}
        top = max(prio.values())
        for key, table, rank in (("smarteq", SMARTEQ_GROUP, _SMARTEQ_RANK),
                                 ("depth", DEPTH, _DEPTH_RANK)):
            base = {i: table.base(i) for i in ids}
            mem = [i for i in ids if base[i] and base[i][0] in rank]
            if len(mem) < 2:
                continue
            owner = sorted(mem, key=lambda i: (-prio[i], rank[base[i][0]],
                                               _WRITTEN_POS.get(i, 0)))[0]
            tier = base[owner][0]
            for i in mem:
                if base[i][0] == tier:
                    continue
                others = ", ".join(_stage_name(j) for j in mem if j != i)
                out[key][i] = (tier, "%s  ⛓ PAIR %d with %s: one level, so it takes "
                               "the tier of its owner, the %s (%s)."
                               % (base[i][1], n, others, _stage_name(owner),
                                  tier.upper()))
        usable = [i for i in ids if stage_manual_ok(i)]
        if len(set(prio.values())) > 1:
            for i in usable:
                out["stage"][i] = {"role": "feature" if prio[i] == top else "support",
                                   "side": "auto", "opposite": "", "sibling": ""}
        elif len(usable) == 2 and all(int(counts.get(i, 1) or 1) == 1 for i in usable):
            out["stage"][usable[0]] = {"role": "auto", "side": "auto",
                                       "opposite": "", "sibling": usable[1]}
    return out


def stage_merge_pairs(manual, derived):
    """Hand placements on top of what the pairs derive: a hand-set field wins."""
    manual = manual or {}
    out = {}
    for a, d in (derived or {}).items():
        d = dict(d)
        b = d.get("sibling")
        if b:
            for x in (a, b):
                mo = manual.get(x)
                if isinstance(mo, dict) and (mo.get("opposite") or mo.get("sibling")):
                    d["sibling"] = ""
        out[a] = d
    for key, o in manual.items():
        d = out.get(key)
        if d is None or not isinstance(o, dict):
            out[key] = o
            continue
        m = dict(d)
        if o.get("role", "auto") != "auto":
            m["role"] = o["role"]
        if o.get("side", "auto") != "auto":
            m["side"] = o["side"]
        if o.get("opposite") or o.get("sibling"):
            m["opposite"], m["sibling"] = o.get("opposite", ""), o.get("sibling", "")
        out[key] = m
    return stage_overrides_clean(out)


# *************** DEL 04d - SWAM ROOM (v3.26) *********************************
# SWAM (Audio Modeling) instruments carry their own room simulator, Ambiente. It is
# SHARED by every SWAM instance (one room, up to three user rooms + a close-mic room),
# and each instrument has just two numbers in it: roomSourceDistance (metres) and
# roomSourceAngle (degrees) - read out of his own Viola preset file. So a SWAM channel
# is placed THERE, and Virtual Stage stays OFF on it. The numbers come from the same
# stage plan as everything else, so pairs, siblings and hand placements still count.
SWAM_COLOUR = "#e6b86a"
SWAM_DIVIDER = "*" * 14 + "  SWAM  " + "*" * 14
SWAM_ANGLE_FRONT = 90        # straight ahead; above = left, below = right (his Room0 screenshot)
SWAM_ANGLE_SPAN = 55         # Position +-100 % reaches +-55 degrees from straight ahead
SWAM_DIST_MIN_M = 1.5        # Virtual Stage Distance 0   -> 1.5 m
SWAM_DIST_MAX_M = 7.5        # Virtual Stage Distance 100 -> 7.5 m (inside LARGE 2: 22.3 x 20.5 m);
                             # Distance 18 (front) -> 2.6 m, about the 2.7 m his Viola has now
SWAM_SMALL_SCALE = 0.6       # a small room: every distance scaled down
SWAM_WHY = ("This channel is placed in SWAM's own room (Ambiente), so Virtual Stage stays OFF "
            "on it: two rooms on one channel is how a mix ends up with two pans and two echoes. "
            "Do not pan it again in Cubase. The Angle and Distance come from the same stage plan "
            "as everything else, so the pairs, siblings and hand placements still count.")


SWAM_TABS = ("Brass", "Winds", "Strings")     # SWAM makes strings, woodwinds and brass

# v3.29: the SWAM SECTION plug-ins (Violin / Viola / Cello Section ...). Each is its own plug-in with its own
# preset folder, e.g. ...\Audio Modeling\SWAM Cello Section, and its presets are another format than the solo
# ones - so a part ticked "Sect" is built from a seed saved IN the section plug-in.
SWAM_SECTION_PRODUCT = {
    "violin": ["violin section"], "violin_bg": ["violin section"], "strings_lead": ["violin section"],
    "viola": ["viola section"], "viola_front": ["viola section"],
    "cello": ["cello section"],
}   # no double_bass: the 'Double Bass Section' card is its own row (SWAM box only)


def swam_ok(iid):
    """Can this part be a SWAM instrument? Only strings, brass and winds - SWAM has no
    vocals, guitars, keys or synths - and not the channels the stage keeps OFF anyway."""
    return (_stage_known(iid) and INST_GROUP.get(iid) in SWAM_TABS
            and iid not in KIT_IDS and iid not in KIT_OFF_RISER and iid not in VSTAGE_SKIP)


def swam_section_ok(iid):
    """Can this part also be run in a SWAM Section plug-in?"""
    return iid in SWAM_SECTION_PRODUCT and swam_ok(iid)


def clean_swam_sec(raw, swam_ids=None):
    """The ids run in a SWAM Section plug-in: sanitised, and only parts that are SWAM too."""
    try:
        ids = {i for i in (raw or ()) if isinstance(i, str) and swam_section_ok(i)}
    except TypeError:
        return []
    if swam_ids is not None:
        ids &= set(swam_ids)
    return sorted(ids, key=lambda i: _WRITTEN_POS.get(i, 0))


def clean_swam(raw):
    """The ids ticked as SWAM, sanitised, in the order of the list."""
    try:
        ids = {i for i in (raw or ()) if isinstance(i, str) and swam_ok(i)}
    except TypeError:
        return []
    return sorted(ids, key=lambda i: _WRITTEN_POS.get(i, 0))


def swam_angle(pct):
    """Stage Position (-100 left .. +100 right) -> SWAM angle in degrees."""
    pct = max(-100.0, min(100.0, float(pct)))
    return int(round(SWAM_ANGLE_FRONT - pct / 100.0 * SWAM_ANGLE_SPAN))


def swam_metres(dist, scale=1.0):
    """Virtual Stage Distance (0-100) -> metres from the microphone."""
    d = max(0.0, min(100.0, float(dist)))
    return round((SWAM_DIST_MIN_M + d / 100.0 * (SWAM_DIST_MAX_M - SWAM_DIST_MIN_M)) * scale, 1)


def swam_room_choice(ids, stage_room=None, sec=()):
    """ONE room for every SWAM instrument (they all share it)."""
    sec = set(sec or ()) | {i for i in ids if "section" in i}
    big = (len(ids) >= 3 or stage_room == "Large" or bool(sec))
    if big:
        return {"big": True, "scale": 1.0, "size": "LARGE 2", "material": "Set 2: MEDIUM",
                "mic": "middle of the Close-Far fader",
                "why": ("%d SWAM parts%s: a big room gives the broad, reverberant sound a section "
                        "wants. LARGE 2 with Set 2: MEDIUM is the Studio A room you already use."
                        % (len(ids), " (one of them a section)" if sec else ""))}
    return {"big": False, "scale": SWAM_SMALL_SCALE, "size": "one of the SMALL sizes",
            "material": "Set 2: MEDIUM", "mic": "middle of the Close-Far fader",
            "why": ("Only %d SWAM part%s: the manual says smaller rooms suit solo instruments "
                    "(more intimate). Pick a SMALL size under Room Sizes." %
                    (len(ids), "" if len(ids) == 1 else "s"))}


def swam_text(sw):
    """'Angle 131 deg  .  Distance 2.7 m', or one pair per copy for a row of them."""
    a, m = sw["angles"], sw["metres"]
    pre = "Section plug-in  \u00b7  " if sw.get("section") else ""
    if len(a) == 1:
        return pre + "Angle %d\u00b0  \u00b7  Distance %.1f m" % (a[0], m[0])
    return pre + "  \u00b7  ".join("#%d %d\u00b0 / %.1f m" % (k + 1, a[k], m[k]) for k in range(len(a)))


def swam_short(sw):
    """The compact form for a list row: 'SWAM 93\u00b0 / 2.7 m' ('SWAM sect.' for a section plug-in)."""
    a, m = sw["angles"], sw["metres"]
    return ("SWAM sect. " if sw.get("section") else "SWAM ") + " \u00b7 ".join(
        "%d\u00b0 / %.1f m" % (a[k], m[k]) for k in range(len(a)))


SWAM_MIN_SEP_M = 1.3         # two sources closer than this stand ON each other
# v3.34: SWAM parts with several copies whose copies PLAY ONE AT A TIME (one takes over from the
# other, a little overlap at the joins). They are one player in the room, so every copy gets the
# first copy's Angle/Distance; copies that play together keep their own spots, spaced apart.
# Filled by EQApp._stage() from the per-song setting 'swam_turns'.
SWAM_TURNS = set()


def _swam_xy(angle, metres):
    import math
    r = math.radians(angle)
    return metres * math.cos(r), metres * math.sin(r)


def _swam_space(rows, order, room, groups=()):
    """Every SWAM source in the room gets its OWN spot: when one stands closer than
    SWAM_MIN_SEP_M to a source that is already placed it is moved BACK in 0.7 m steps
    (depth is the natural way to make room), and only if that is not enough it is turned a
    few degrees. The part placed first keeps its spot; each move is written down in
    row['swam']['moved'] so the sheet can say why a number differs from the stage plan.

    v3.36: PAIRS COME FIRST. `groups` = the parts he tied together (Pair boxes, siblings),
    each a list of ids. They are placed BEFORE every other part, so a part with no pair is the
    one that gives way (before, the stage order decided, and a cello or a flugelhorn could push
    a pair away). The members of one pair are placed AS ONE UNIT: if the unit has to move, all
    members go back the same number of steps (siblings stay on one line) - and a pair whose
    own members stand too close to each other is opened up the same way."""
    import math
    cap = SWAM_DIST_MAX_M * room["scale"]
    placed = []                                    # (x, y, name, iid)
    in_group = {i for g in groups for i in g}

    def clash(a, m):
        x, y = _swam_xy(a, m)
        for px, py, nm, pid in placed:
            if math.hypot(x - px, y - py) < SWAM_MIN_SEP_M:
                return nm, pid
        return None

    def nm_of(iid, k):
        return _stage_name(iid) + ((" #%d" % (k + 1)) if len(rows[iid]["swam"]["angles"]) > 1 else "")

    def put(iid, k):
        sw = rows[iid]["swam"]
        x, y = _swam_xy(sw["angles"][k], sw["metres"][k])
        placed.append((x, y, nm_of(iid, k), iid))

    def place_single(iid):
        sw = rows[iid]["swam"]
        for k in range(len(sw["angles"])):
            if k > 0 and iid in SWAM_TURNS:            # v3.34: copies that take turns share ONE spot
                sw["angles"][k], sw["metres"][k] = sw["angles"][0], sw["metres"][0]
                continue
            a, m = sw["angles"][k], sw["metres"][k]
            hit = clash(a, m)
            if hit:
                who, wid = hit
                cands = [(a, m + 0.7 * st) for st in range(1, 10)]
                for st in range(1, 8):
                    for sign in (1, -1):
                        cands += [(a + sign * 5 * st, m), (a + sign * 5 * st, m + 0.7)]
                for a2, m2 in cands:
                    if m2 <= cap and 25 <= a2 <= 155 and not clash(a2, m2):
                        sw["moved"].append(
                            "Moved from %d\u00b0 / %.1f m to %d\u00b0 / %.1f m: it stood on top of the %s%s."
                            % (a, m, a2, m2, who,
                               " (a pair member - pairs keep their spot, parts without a pair give way)"
                               if wid in in_group and iid not in in_group else ""))
                        a, m = a2, round(m2, 1)
                        sw["angles"][k], sw["metres"][k] = a, m
                        break
            put(iid, k)

    def place_unit(mem):
        ents = [(i, k) for i in mem for k in range(len(rows[i]["swam"]["angles"]))
                if not (k > 0 and i in SWAM_TURNS)]
        base = {e: (rows[e[0]]["swam"]["angles"][e[1]], rows[e[0]]["swam"]["metres"][e[1]]) for e in ents}

        def spots(st, f):
            out = {}
            for e, (a, m) in base.items():
                out[e] = (max(25.0, min(155.0, 90 + (a - 90) * f)), m + 0.7 * st)
            return out

        def bad(sp):
            for _e, (a, m) in sp.items():
                if m > cap:
                    return "cap"
            keys = list(sp)
            for x in range(len(keys)):
                for y in range(x + 1, len(keys)):
                    if keys[x][0] == keys[y][0]:
                        continue                               # copies of one part: their own business
                    ax, ay = _swam_xy(*sp[keys[x]])
                    bx, by = _swam_xy(*sp[keys[y]])
                    if math.hypot(ax - bx, ay - by) < SWAM_MIN_SEP_M:
                        return "pair"
            for e, (a, m) in sp.items():
                hit = clash(a, m)
                if hit:
                    return hit[0]
            return None

        why = bad(spots(0, 1.0))
        if why:
            cands = [(st, 1.0) for st in range(1, 10)]
            for f in (1.15, 1.3, 1.45, 1.6, 1.8):
                cands += [(st, f) for st in range(0, 4)]
            for st, f in cands:
                sp = spots(st, f)
                if bad(sp) is None:
                    names = ", ".join(_stage_name(i) for i in mem)
                    for i in mem:
                        sw = rows[i]["swam"]
                        k0 = next(k for (j, k) in ents if j == i)
                        a0, m0 = base[(i, k0)]
                        a1, m1 = sp[(i, k0)]
                        sw["moved"].append(
                            "Moved from %d\u00b0 / %.1f m to %d\u00b0 / %.1f m together with its pair (%s): %s."
                            % (a0, m0, a1, m1, names,
                               "the pair stood too close to each other" if why == "pair" else
                               "it stood on top of the %s" % why))
                    for (i, k), (a1, m1) in sp.items():
                        rows[i]["swam"]["angles"][k] = int(round(a1))
                        rows[i]["swam"]["metres"][k] = round(m1, 1)
                    break
        for i in mem:                                           # copies that take turns: copy 1's spot
            sw = rows[i]["swam"]
            if i in SWAM_TURNS:
                for k in range(1, len(sw["angles"])):
                    sw["angles"][k], sw["metres"][k] = sw["angles"][0], sw["metres"][0]
        for (i, k) in ents:
            put(i, k)

    for iid in order:
        rows[iid]["swam"]["moved"] = []
    seq, seen = [], set()
    for g in groups:
        mem = [i for i in g if i in order and i not in seen]
        if mem:
            seq.append(mem)
            seen.update(mem)
    seq += [[i] for i in order if i not in seen]
    for mem in seq:
        if len(mem) >= 2:
            place_unit(mem)
        else:
            place_single(mem[0])


def swam_apply(rows, info, swam_ids, sec_ids=(), hold=()):
    """Turn the SWAM channels of a finished stage plan into SWAM rows, in place.

    Virtual Stage goes OFF on them (row['skip']), they get an Angle and a Distance in
    metres, and info['swam'] carries the shared room. Returns that dict or None."""
    ids = [i for i in clean_swam(swam_ids) if i in rows and not rows[i].get("kit")]
    if not ids:
        return None
    sec = set(clean_swam_sec(sec_ids, ids))
    room = swam_room_choice(ids, info.get("room"), sec)
    for i in ids:
        r = rows[i]
        pcts = list(r.get("pos_pcts") or [r.get("pos_pct", 0.0)])
        dists = list(r.get("dists") or [])
        if not dists:
            dists = [r["dist"] if r.get("dist") is not None else VSTAGE_TIER_DIST["near"]]
        n = max(len(pcts), len(dists))
        pcts += [pcts[-1]] * (n - len(pcts))
        dists += [dists[-1]] * (n - len(dists))
        r["swam"] = {"angles": [swam_angle(p) for p in pcts],
                     "metres": [swam_metres(d, room["scale"]) for d in dists],
                     "section": (i in sec) or ("section" in i)}
        r["skip"] = True
        r["option"] = None
        r["why"] = SWAM_WHY
    order = [i for i in (info.get("order") or []) if i in ids] or ids
    _swam_space(rows, order, room, [[i for i in g if i in rows] for g in (hold or ())])
    info["swam"] = {"room": room, "ids": order}
    return info["swam"]


def swam_room_lines(rows, info):
    """The 'SWAM ROOM' part of the Stage map, as [(style, text)]."""
    sw = (info or {}).get("swam")
    if not sw:
        return []
    room = sw["room"]
    out = [("h2", SWAM_DIVIDER + "\n"),
           ("h2", "SWAM room (Ambiente) - set it ONCE, it is shared by every SWAM instrument\n"),
           ("code", "  Room Type                (leave as it is - it never changes)\n"),
           ("code", "  Room Sizes               %s\n" % room["size"]),
           ("code", "  Absorption Materials     %s\n" % room["material"]),
           ("code", "  Mic Position             %s\n" % room["mic"]),
           ("body", "  " + room["why"] + "\n\n"),
           ("h2", "Where each SWAM instrument goes (left to right)\n")]
    placed = sorted(sw["ids"], key=lambda i: -rows[i]["swam"]["angles"][0])
    for i in placed:
        out.append(("code", "  %-24s %s\n" % (_stage_name(i), swam_text(rows[i]["swam"]))))
    out.append(("body",
                "\nHow: open ANY SWAM instrument, press ROOM, then LIST (the numbers can be typed) "
                "or TECH (scaled, stay inside the dashed area). Angle 90 is straight ahead, above "
                "90 is to the left, below 90 to the right - read off your own screenshot (the "
                "Viola left of centre shows 131). Try one instrument first; if it lands on the "
                "wrong side, tell me and the sign is flipped. If a Distance is refused, lower "
                "all of them by the same factor.\n"
                "Bandwidth, Cascadia and smart:EQ work as before; only the placement moved to SWAM.\n\n"))
    return out


# ---- THE SWAM PRESET FILE (v3.26) ----------------------------------------------------
# A SWAM .vstpreset is the VST3 container (header 'VST3', 32-char class id, list offset at 40,
# chunks 'Comp' / 'Cont' / 'Info', 'List' at the end) around a JUCE VST2 wrapper:
#   'VstW' ... 'CcnK' <size BE> 'FBCh' ... <chunk size BE> 'VC2!' <xml length LE> <XML> <61-byte
#   JUCE trailer>. The XML ('<swam ...>') holds everything: sound engine, MIDI mapping, and the
#   Ambiente room with, per instrument, roomSourceAngle (degrees) and roomSourceDistance
#   (metres, stored as a 32-bit float). make_swam_preset() changes ONLY those two numbers in a
#   preset he saved himself (the seed) and moves every length field with them; asking for the
#   values the seed already has gives the seed back byte for byte.
SWAM_ANGLE_RE = _re.compile(rb'(<PARAM id="roomSourceAngle" value=")([^"]*)(")')
SWAM_DIST_RE = _re.compile(rb'(<PARAM id="roomSourceDistance" value=")([^"]*)(")')


def _swam_f32(x):
    """The text SWAM writes for a number: a 32-bit float printed like a double."""
    return repr(struct.unpack("<f", struct.pack("<f", float(x)))[0])


def swam_preset_values(data):
    """(angle, distance_m) from a SWAM .vstpreset, or None if it is not one."""
    try:
        d = bytes(data)
        if d[:4] != b"VST3":
            return None
        a, m = SWAM_ANGLE_RE.search(d), SWAM_DIST_RE.search(d)
        if not a or not m or b"<swam " not in d:
            return None
        return float(a.group(2)), float(m.group(2))
    except Exception:
        return None


SWAM_EXPR_RE = _re.compile(rb'(<PARAM id="expression" value=")([^"]*)(")')
SWAM_VIB_RE = _re.compile(rb'(<PARAM id="vibratoDepth" value=")([^"]*)(")')


def swam_preset_tune(data):
    """(expression, vibratoDepth) stored in a SWAM preset; None for one it does not hold."""
    out = []
    for rx in (SWAM_EXPR_RE, SWAM_VIB_RE):
        m = rx.search(bytes(data))
        try:
            out.append(float(m.group(2)) if m else None)
        except ValueError:
            out.append(None)
    return tuple(out)


def make_swam_preset(seed, angle, dist_m, expression=None, vibrato=None):
    """A copy of a SWAM preset (`seed`, bytes) with Angle (degrees) and Distance (metres)
    changed - and, from v3.34, optionally the Expression and the Vibrato depth stored in it
    (None = leave the seed's own). Raises ValueError if the seed is not a SWAM preset this
    code understands."""
    d = bytes(seed)
    if d[:4] != b"VST3" or swam_preset_values(d) is None:
        raise ValueError("not a SWAM preset")
    x0 = d.index(b"<?xml")
    x1 = d.index(b"</swam>") + len(b"</swam>")
    xml = d[x0:x1]
    if struct.unpack_from("<I", d, x0 - 4)[0] != len(xml):
        raise ValueError("unexpected length field in front of the XML")
    new = SWAM_ANGLE_RE.sub(lambda m: m.group(1) + _swam_f32(angle).encode() + m.group(3), xml, 1)
    new = SWAM_DIST_RE.sub(lambda m: m.group(1) + _swam_f32(dist_m).encode() + m.group(3), new, 1)
    if expression is not None:
        new = SWAM_EXPR_RE.sub(lambda m: m.group(1) + _swam_f32(expression).encode() + m.group(3), new, 1)
    if vibrato is not None:
        new = SWAM_VIB_RE.sub(lambda m: m.group(1) + _swam_f32(vibrato).encode() + m.group(3), new, 1)
    delta = len(new) - len(xml)
    out = bytearray(d[:x0] + new + d[x1:])
    # every length that contains the XML moves by delta
    struct.pack_into("<I", out, x0 - 4, len(new))
    ck = d.index(b"CcnK")
    fb = ck + 8                                   # 'FBCh'
    if d[fb:fb + 4] != b"FBCh":
        raise ValueError("no FBCh header")
    struct.pack_into(">I", out, ck + 4, struct.unpack_from(">I", d, ck + 4)[0] + delta)
    struct.pack_into(">I", out, fb + 148, struct.unpack_from(">I", d, fb + 148)[0] + delta)
    lo = struct.unpack_from("<q", d, 40)[0]
    n = struct.unpack_from("<I", d, lo + 4)[0]
    struct.pack_into("<q", out, 40, lo + delta)
    # the List itself moved by delta: rewrite its entries in the new buffer
    for i in range(n):
        e_old = lo + 8 + i * 20
        e_new = e_old + delta
        off, size = struct.unpack_from("<qq", d, e_old + 4)
        if d[e_old:e_old + 4] == b"Comp":
            size += delta
        elif off > x0:
            off += delta
        struct.pack_into("<qq", out, e_new + 4, off, size)
    return bytes(out)


# ---- GENERATE: SWAM ROOM PRESETS (v3.27) --------------------------------------------------
# One .vstpreset per SWAM instrument of the song, named  <song>---<instrument>---SWAM  and
# written into that instrument's own folder (…\VST3 Presets\Audio Modeling\SWAM Viola 3).
# The sound is the seed's (a preset he saved himself in that folder); only the room position
# is changed, from the Stage plan, with every source given its own spot. Run it again when the
# line-up changes: the same names are rewritten (the old files are kept as .bak).
PRESETS_SWAM = os.path.join("Presets", "SWAMRoom")
SWAM_SUFFIX = "---SWAM"
SWAM_PRODUCT = {
    "violin": ["violin"], "violin_bg": ["violin"], "strings_lead": ["violin"],
    "viola": ["viola"], "viola_front": ["viola"], "cello": ["cello"],
    "double_bass": ["double bass"], "double_bass_section": ["double bass section", "double basses"],
    "clarinet": ["clarinet"], "oboe": ["oboe"], "bassoon": ["bassoon"],
    "contrabassoon": ["contrabassoon"], "flugelhorn": ["flugelhorn"],
    "french_horn": ["french horn", "horn"], "tuba": ["tuba eb", "eb tuba", "tuba"], "english_horn": ["english horn"],
    "euphonium": ["euphonium"], "bass_clarinet": ["bass clarinet"],
    "contrabass_clarinet": ["contrabass clarinet"], "piccolo": ["piccolo"],
    "alto_flute": ["alto flute"], "bass_flute": ["bass flute"], "flute": ["flute"],
    "flute_bg": ["flute"], "soprano_sax": ["soprano sax", "soprano saxophone"],
    "alto_sax": ["alto sax", "alto saxophone"], "tenor_sax": ["tenor sax", "tenor saxophone"],
    "baritone_sax": ["baritone sax", "baritone saxophone"],
    "piccolo_trumpet": ["piccolo trumpet"], "trumpet": ["trumpet"], "trombone": ["trombone"],
    "alto_trombone": ["alto trombone"], "bass_trombone": ["bass trombone"],
    "tenor_trombone": ["tenor trombone"], "tenor_bass_trombone": ["tenor bass trombone"],
    "double_bass_trombone": ["double bass trombone"],
}


def swam_folder_key(name):
    """'SWAM Viola 3' -> 'viola', 'SWAM Soprano Sax 3' -> 'soprano sax'."""
    n = _re.sub(r"^swam\s+", "", str(name).strip().lower())
    n = _re.sub(r"\s+v?\d+(\.\d+)*$", "", n)
    return _re.sub(r"\s+", " ", n).strip()


def swam_find_folders(root):
    """{folder key: path} for every SWAM instrument folder under Audio Modeling."""
    out = {}
    try:
        for d in sorted(os.listdir(root)):
            p = os.path.join(root, d)
            if os.path.isdir(p) and d.lower().startswith("swam"):
                out.setdefault(swam_folder_key(d), p)
    except OSError:
        pass
    return out


def swam_folder_names(iid, section=False):
    """The folder keys a part may live under: the section plug-in's when it is run as a section."""
    if section and "section" not in iid and iid in SWAM_SECTION_PRODUCT:
        return SWAM_SECTION_PRODUCT[iid]
    return SWAM_PRODUCT.get(iid, ())


def swam_folder_for(iid, folders, section=False):
    for name in swam_folder_names(iid, section):
        if name in folders:
            return folders[name]
    return None


def swam_seed_files(folder):
    """The presets in a SWAM folder that can be a seed: his own, never one this program wrote."""
    try:
        return sorted(f for f in os.listdir(folder)
                      if f.lower().endswith(".vstpreset")
                      and not f.startswith("~deleted~")
                      and not os.path.splitext(f)[0].endswith(SWAM_SUFFIX))
    except OSError:
        return []


def swam_generated_files(folder):
    """The presets this program wrote into a folder, newest first."""
    try:
        files = [os.path.join(folder, f) for f in os.listdir(folder)
                 if f.lower().endswith(".vstpreset") and not f.startswith("~deleted~")
                 and os.path.splitext(f)[0].endswith(SWAM_SUFFIX)]
    except OSError:
        return []
    return sorted(files, key=lambda f: -os.path.getmtime(f))


def swam_pick_seed(folder, chosen=""):
    """(path, bytes) of the preset to build from. The one he CHOSE (File > SWAM: choose the
    sound...), else automatically: a name with 'Claude' in it, then one with 'Default', then
    the shortest name (a plain 'Cello-test' beats 'Cello-test-BACH')."""
    names = swam_seed_files(folder)
    if chosen and chosen in names:
        names = [chosen]
    files = [os.path.join(folder, f) for f in names]
    files.sort(key=lambda f: (not os.path.basename(f).startswith("1000---"),   # v3.29: his own seeds
                              ("claude" not in os.path.basename(f).lower()),
                              ("default" not in os.path.basename(f).lower()),
                              len(os.path.basename(f)), -os.path.getmtime(f)))
    # None of his own left (moved or deleted)? A preset this program wrote carries the very
    # same sound - only the room position differs - so the newest of those will do.
    files += swam_generated_files(folder)
    for f in files:
        try:
            with open(f, "rb") as fh:
                data = fh.read()
        except OSError:
            continue
        if swam_preset_values(data) is not None:
            return f, data
    return None


SWAM_SIZE_NAMES = {7: "LARGE 2"}


def swam_seed_room(data):
    """(room name, size number, material number) of the ACTIVE room in a SWAM preset."""
    try:
        t = bytes(data).decode("utf-8", "ignore")
        for m in _re.finditer(r'<Room id="[^"]*" name="([^"]*)"[^>]*active="1">(.*?)</Room>', t, _re.S):
            size = _re.search(r'parameterId="roomSizes" value="([^"]*)"', m.group(2))
            mat = _re.search(r'parameterId="roomAbsorptionMaterials" value="([^"]*)"', m.group(2))
            return (m.group(1).replace("_", " "), int(float(size.group(1))) if size else None,
                    int(float(mat.group(1))) if mat else None)
    except Exception:
        pass
    return None


# ---- v3.33: THE SAME PRESET FOR SWAM'S OWN BROWSER (2026-11-09) ----------------------------
# Cubase lists a .vstpreset only from the list it built when it STARTED (its MediaBay database
# mediabay3.db; checked 2026-11-09: Fyrvaktarens son was on disk, not in the database). SWAM has
# a second preset list of its own: plain XML '.swam' files in
#   %APPDATA%\Audio Modeling\AMData\<family>\<group>\<Instrument>\Resources\Presets\User
# The XML inside a .vstpreset and a .swam is the same document (the .vstpreset only has a few
# live-state extras and syncLock="1"), so the .swam is made from the .vstpreset's XML with a new
# program name and date. NOT verified in the real plug-in's browser (ToDo: Lars loads one).
def swam_amdata_root():
    return os.path.join(os.environ.get("APPDATA", ""), "Audio Modeling", "AMData")


def swam_native_dirs(root=None):
    """{normalised instrument folder name: ...\\Presets\\User} for every SWAM instrument that has one."""
    root = root or swam_amdata_root()
    out = {}
    try:
        for dp, dns, _fns in os.walk(root):
            if os.path.basename(dp) == "User" and os.path.basename(os.path.dirname(dp)) == "Presets":
                inst = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(dp))))
                out.setdefault(_re.sub(r"[^a-z0-9]", "", inst.lower()), dp)
    except OSError:
        pass
    return out


SWAM_NATIVE_ALIAS = {"piccolo": "piccoloflute", "tuba": "tubaeb", "french horn": "frenchhornf",
                     "horn": "frenchhornf"}


def swam_native_dir_for(iid, section, dirs):
    """The .swam User folder of a part, or None (unknown instrument / not installed)."""
    for key in swam_folder_names(iid, section):
        n = _re.sub(r"[^a-z0-9]", "", SWAM_NATIVE_ALIAS.get(key, key).lower())
        if section and "section" not in n:
            n += "section"
        if n in dirs:
            return dirs[n]
    return None


def swam_native_text(data, name):
    """The .swam file (bytes) for a .vstpreset's XML: same document, own program name and date."""
    import time
    d = bytes(data)
    x0 = d.index(b"<?xml")
    x1 = d.index(b"</swam>") + len(b"</swam>")
    xml = d[x0:x1].decode("utf-8")
    xml = xml.split("?>", 1)[1].lstrip("\r\n ")
    xml = xml.replace(' syncLock="1"', "", 1)
    nm = (name.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;"))
    xml = _re.sub(r'(<program name=")[^"]*(")', lambda m: m.group(1) + nm + m.group(2), xml, 1)
    t = time.localtime()
    stamp = "%s %s %2d %s %d&#10;" % (time.strftime("%a", t), time.strftime("%b", t), t.tm_mday,
                                      time.strftime("%H:%M:%S", t), t.tm_year)
    xml = _re.sub(r'(<datetime value=")[^"]*(")', lambda m: m.group(1) + stamp + m.group(2), xml, 1)
    return ('<?xml version="1.0" encoding="UTF-8"?>\r\n\r\n' + xml).encode("utf-8")


def cubase_running():
    """True/False if a Cubase process is running (None if it cannot be told)."""
    try:
        tl = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "tasklist.exe")
        r = subprocess.run([tl, "/FO", "CSV", "/NH"], capture_output=True, text=True, timeout=10,
                           creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
        return "cubase" in r.stdout.lower()
    except Exception:
        return None


# ---- v3.35: KILL STEINBERG MEDIABAY (2026-11-10) -------------------------------------------
# Cubase's preset list comes from the MediaBay database; the background process
# 'SteinbergMediaBayServer.exe' keeps it. While it lives, new .vstpreset files (SWAM, Virtual
# Stage ...) may not be picked up. Ending it (with Cubase closed) makes the next Cubase start
# rebuild the list. System tools are started by FULL path (rule 8: never a bare name).
def _sys32(name):
    return os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", name)


def mediabay_pids():
    """[(pid, image name)] of every running Steinberg MediaBay process ([] = none, None = could
    not be told)."""
    try:
        import csv as _csv
        r = subprocess.run([_sys32("tasklist.exe"), "/FO", "CSV", "/NH"], capture_output=True,
                           text=True, timeout=15,
                           creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
        out = []
        for row in _csv.reader(r.stdout.splitlines()):
            if len(row) >= 2 and "mediabay" in row[0].lower():
                try:
                    out.append((int(row[1]), row[0]))
                except ValueError:
                    pass
        return out
    except Exception:
        return None


def kill_mediabay():
    """End every Steinberg MediaBay process by PID. Returns (killed, still_alive, problem)."""
    found = mediabay_pids()
    if found is None:
        return 0, 0, "Could not list the running programs."
    for pid, _name in found:
        try:
            subprocess.run([_sys32("taskkill.exe"), "/F", "/PID", str(pid)], capture_output=True,
                           text=True, timeout=15,
                           creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
        except Exception:
            pass
    left = mediabay_pids() or []
    gone = len(found) - len(left)
    return gone, len(left), ""


def swam_safe_song(song):
    """The song name as it can stand in a file name."""
    return _re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", str(song or "Song")).strip(" .") or "Song"


def swam_preset_filename(song, label, copy=0):
    """'MySong---Viola---SWAM.vstpreset' (a second copy of a part: 'Viola_2')."""
    return "%s---%s%s%s.vstpreset" % (swam_safe_song(song), label,
                                      ("_%d" % copy) if copy > 1 else "", SWAM_SUFFIX)


def swam_jobs(rows, info):
    """What a Generate run writes: [{iid, copy, label, angle, metres}], in stage order."""
    jobs = []
    for iid in ((info or {}).get("swam") or {}).get("ids", []):
        sw = rows[iid]["swam"]
        n = len(sw["angles"])
        for k in range(n):
            sect = bool(sw.get("section"))
            jobs.append({"iid": iid, "copy": (k + 1) if n > 1 else 0,
                         "label": vstage_label(iid) + ("_Section" if sect and "section" not in iid else ""),
                         "section": sect, "angle": sw["angles"][k], "metres": sw["metres"][k]})
    return jobs


def song_sort_key(name):
    """A-Z, case-blind, numbers in number order ('Song 2' before 'Song 10')."""
    return [(0, int(p), "") if p.isdigit() else (1, 0, p.casefold())
            for p in re.split(r"(\d+)", str(name)) if p != ""]


def _variants_path():
    return os.path.join(get_helpfiles_dir("eq_cheatsheet"), "song_variants.json")


def load_variants():
    """Return (variants, current_name, ground). Seeds a default on first run.

    `ground` is the ⚓ line-up - the one you keep coming back to - or None
    when none has been saved yet. See clean_ground()."""
    try:
        with open(_variants_path(), "r", encoding="utf-8") as f:
            data = json.load(f)
        variants = data.get("variants") or []
        # keep only known ids; migrate any legacy 'temp' additions into 'fixed'
        for v in variants:
            fixed = [i for i in v.get("fixed", []) if i in VALID_IDS]
            for i in v.get("temp", []):              # legacy: fold temp -> fixed
                if i in VALID_IDS and i not in fixed:
                    fixed.append(i)
            v["fixed"] = fixed
            raw_counts = v.get("counts", {}) or {}
            v["counts"] = {i: max(1, min(MAX_INSTRUMENT_COUNT, int(raw_counts.get(i, 1))))
                           for i in fixed}
            v.pop("temp", None)
            v.setdefault("name", "Untitled")
            # 🎪 Hand placements travel with the song they were made for.
            v["stage_manual"] = stage_overrides_clean(v.get("stage_manual"))
            v["pairs"] = clean_pairs(v.get("pairs"))
            v["swam"] = clean_swam(v.get("swam"))
            v["swam_sec"] = clean_swam_sec(v.get("swam_sec"), v["swam"])
        if variants:
            current = data.get("current", variants[0]["name"])
            if current not in {v["name"] for v in variants}:
                current = variants[0]["name"]
            return variants, current, clean_ground(data.get("ground"))
    except Exception:
        pass
    # A dict in the template has to be COPIED, or every seeded variant would
    # share one hand-placement table with every other one.
    seed = {k: (list(val) if isinstance(val, list) else
                (dict(val) if isinstance(val, dict) else val))
            for k, val in DEFAULT_VARIANT.items()}
    return [seed], seed["name"], None


def save_variants(variants, current, ground=None):
    try:
        os.makedirs(os.path.dirname(_variants_path()), exist_ok=True)
        with open(_variants_path(), "w", encoding="utf-8") as f:
            json.dump({"variants": variants, "current": current,
                       "ground": ground}, f, indent=2)
    except Exception:
        pass


def _region_of(hz):
    """Bucket a frequency into a named EQ region (for conflict detection)."""
    if hz < 60:    return "Sub (<60 Hz)"
    if hz < 250:   return "Bass (60–250 Hz)"
    if hz < 500:   return "Lo-mid (250–500 Hz)"
    if hz < 2000:  return "Mid (500 Hz–2 kHz)"
    if hz < 6000:  return "Hi-mid (2–6 kHz)"
    return "Highs (>6 kHz)"


# *************** DEL 04z - OVERWRITE QUESTION (v3.37) ************************
# The old 'overwrite existing presets' tick boxes in Options are gone: you could not see their state. Every generator
# now gets an _OverwriteAsk instead of a bool. Its truth value is only asked for when a file with the name to be
# written ALREADY EXISTS, and then a popup asks ONCE per run: overwrite with the new ones (old file kept as .bak) or
# keep the existing ones. The answer counts for the rest of that run. Nothing is asked when nothing exists.
class _OverwriteAsk:
    def __init__(self, app, what):
        self.app, self.what, self.answer = app, what, None

    def __bool__(self):
        if self.answer is None:
            dst = None
            try:
                dst = sys._getframe(1).f_locals.get("dst")      # the file the generator is looking at
            except Exception:
                dst = None
            self.answer = bool(self.app._ask_overwrite_popup(self.what, dst))
        return self.answer


# *************** DEL 05 - MAIN APP CLASS *************************************

class EQApp:
    """Main application window for EQ Cheat Sheet."""

    def __init__(self, root):
        self.root = root
        self.root.title(APP_NAME)
        self.root.configure(bg=C_BG)

        self.settings = load_settings()

        # Checkbox state per instrument id
        self.check_vars = {}

        # EQ engine: "kirchhoff" = exact Parametric Q (Kirchhoff-EQ V1.7.1, default),
        # "range" = generic start–end ranges (the original SmartEQ-style view).
        self.eq_mode = tk.StringVar(
            value=self.settings.get("eq_mode", "kirchhoff"))

        # Bake Mid/Side into generated Kirchhoff presets (default ON — codes verified).
        self.keq_ms_var = tk.BooleanVar(
            value=bool(self.settings.get("keq_bake_ms", True)))
        # Omit the High-Pass band from generated presets (Lowtility does the HP).
        self.keq_nohp_var = tk.BooleanVar(
            value=bool(self.settings.get("keq_no_hp", False)))
        # Also write a Cubase .vstpreset per preset (so they show in Cubase's own
        # preset browser, not only Kirchhoff's internal one).
        self.keq_vst3_var = tk.BooleanVar(
            value=bool(self.settings.get("keq_make_vst3", True)))
        # Overwrite existing presets instead of reusing them (safety: always OFF
        # on launch, not persisted).

        # smart:reverb preset generation: write ONE preset per depth tier
        # (Front/Near/Mid/Far) for the bus workflow, instead of one per instrument.
        self.sonible_pertier_var = tk.BooleanVar(
            value=bool(self.settings.get("sonible_per_tier", False)))
        # Overwrite existing Sonible presets (safety: always OFF on launch).
        # Overwrite existing Lowtility presets (safety: always OFF on launch).
        # Overwrite existing SubMass presets (safety: always OFF on launch).
        # KNOCK: which version to write (remembered) and the overwrite switch (always OFF on launch).
        self.knock_version_var = tk.StringVar(value=knock_version_of(self.settings))
        # Overwrite existing PatchWork chain presets (safety: always OFF on launch).
        # Overwrite existing Omega presets (safety: always OFF on launch).
        # Overwrite existing Bandwidth presets (safety: always OFF on launch).
        # Overwrite existing Cascadia presets (safety: always OFF on launch).
        # Overwrite existing Virtual Stage presets (safety: always OFF on launch).

        # Band-type filter: "all", "boost", "cut", "char"
        self._band_filter = tk.StringVar(value="all")
        # Refs to inner frames per group for filter rebuilds
        self._group_inner  = {}   # group -> inner tk.Frame
        self._group_canvas = {}   # group -> tk.Canvas (for scrollregion reset)
        self._group_all_vars = {} # group -> StringVar for the tab's All/none box
        # Live footnotes (duck / smart:EQ / compressor): re-filled whenever the
        # selection changes, because their advice depends on what else is in the
        # song (see _live_note / _refresh_live_notes).
        self._duck_holders = []

        # Song-variant presets (Tab 7)
        self.variants, self.current_variant, self.ground = load_variants()
        self._var_group_all_vars = {}  # group -> StringVar (all/none in the variant tab)
        self._vfixed_vars = {}    # inst_id -> BooleanVar  (in this variant)
        # inst_id -> StringVar "how many of this instrument" (default "1").
        # Created HERE, before the UI is built, because the SAME variable is now
        # shared by two widgets: the spin box on the instrument card and the one
        # in the Song Variants tab. Tk keeps them in step for free.
        self._vcount_vars = {iid: tk.StringVar(value="1") for iid in VALID_IDS}
        self._multi_holders = []   # card/summary frames that redraw on a count change

        # 🎪 Hand placements on the stage for the CURRENT variant
        # (DEL 02m). Read out of the variant, written straight back into it.
        self._stage_manual = {}
        self._manual_win = None    # the ✋ dialog, while it is open

        # ⛓ Pairs + priority (DEL 04c, v3.25) for the CURRENT variant. They wait for
        # Save / ⟳ Update like a tick or a count (_applied_pairs is their snapshot).
        self._pairs = {}           # {id: [pair, prio]}
        self._pair_stage = {}      # what the pairs derive for the Virtual Stage
        self._vpair_vars = {}      # the two spin boxes per row in Song Variants
        self._vprio_vars = {}
        self._vpair_spins = {}
        self._applied_pairs = None  # the pairs the right panel was last built with
        self._focus_iid = None      # the instrument you touched last (panel scrolls to it)
        self._swam = []            # v3.26: ids run as SWAM (DEL 04d)
        self._applied_swam = None  # v3.28: the SWAM ticks the right panel was last built with
        self._vswam_vars = {}      # the SWAM tick per row in Song Variants
        self._swam_sec = []        # v3.29: SWAM parts run in a Section plug-in
        self._applied_swam_sec = None
        self._vsec_vars = {}       # the Sect tick per row in Song Variants

        # ---- ⟳ UPDATE / ↩ RESET / ⚓ GROUND (2026-09-23) ------------------
        # The left side is a scratch pad; the right panel is a SNAPSHOT of
        # the last line-up that was committed to it. _applied_sel and
        # _applied_counts ARE that snapshot, and every engine in this program
        # reaches the line-up through _checked_ids() / _count_of() - so those
        # two accessors handing back the snapshot while something is waiting
        # is the whole mechanism. No second copy of the panel, no frozen
        # widgets, nothing to keep in step.
        #
        # "Waiting" is never a flag somebody has to remember to clear: it is
        # computed by comparing the two, so it cannot go stale (see
        # _compute_pending_bits).
        self.hold_left_var = tk.BooleanVar(
            value=bool(self.settings.get("hold_left_updates", True)))
        self._applied_sel = None       # None = nothing has been rendered yet
        self._applied_counts = {}
        self._pending_cache = None

        # 🦻 Hearing profile (DEL 02k) — {band_key: state}. Empty until filled in.
        self.hearing = hearing_profile(self.settings)

        # ★ Focus plug-ins (pinned to the top of the 🧩 Plugins tab).
        fp = self.settings.get("focus_plugins")
        self.focus_plugins = list(fp) if isinstance(fp, list) else list(FOCUS_DEFAULT)

        # 🎪 Virtual Stage (DEL 02m): whose left is left. "audience" = you are
        # looking AT the drummer, so the hi-hat is on the RIGHT. Only the kit
        # is mirrored by this — a guitarist does not swap sides because you
        # walked round the back of the stage.
        self.stage_persp_var = tk.StringVar(
            value=("drummer" if self.settings.get("stage_perspective") == "drummer"
                   else "audience"))
        self._stage_cache_key = None
        self._stage_cache = ({}, {})

        # ---- How much prose to print (see _note_label) ----------------------
        # Extra comments = the "why this number" lines. Off by default: they do
        # not change a single setting, and hiding them is what makes the views
        # compact enough to read without scrolling.
        self.details_var = tk.BooleanVar(
            value=bool(self.settings.get("show_details", False)))
        self.extra_comments_var = tk.BooleanVar(
            value=bool(self.settings.get("show_extra_comments", False)))
        self.hide_empty_var = tk.BooleanVar(
            value=bool(self.settings.get("hide_empty_note_rows", True)))
        self.theory_tabs_var = tk.BooleanVar(
            value=bool(self.settings.get("show_theory_tabs", True)))
        # 🔎 Focus view — see DEFAULT_SETTINGS["focus_view"] and
        # _apply_focus_view(). Nothing is deleted when it is on; the widgets
        # are unpacked and packed straight back, with their scroll positions
        # and their ticks exactly where they were.
        self.focus_view_var = tk.BooleanVar(
            value=bool(self.settings.get("focus_view", True)))

        # ---- Δ vs default (DEL 02p) ----------------------------------
        # On by default. Every field that is already what his preset holds
        # is greyed out, so what is left in colour is the short list this
        # song changes — the reason he no longer has to open nine plug-ins
        # to check they are still on their normal setting.
        self.default_diff_var = tk.BooleanVar(
            value=bool(self.settings.get("show_default_diff", True)))
        src = self.settings.get("defaults_from") or "band"
        self.defaults_src_var = tk.StringVar(
            value=(src if src in ("band", "typical", "variants") else "band"))

        # Plugin library (grow-over-time list of what you own / want to try).
        self.plugins = load_plugins()
        self._plugin_kind_filter = "All"   # current kind filter in the Plugins tab

        # Right panel: "instruments" (per-instrument summary, the DEFAULT — it is
        # the view you actually work in) | "channelplan" (compact combined plan) |
        # "effects" (sorted by one effect). Restored from settings on start.
        self._right_mode  = self.settings.get("right_mode", "instruments")
        if self._right_mode not in ("channelplan", "instruments", "effects"):
            self._right_mode = "instruments"
        self._effect_sort = "smarteq"
        # ⇅ ORDER of the channels in the two list views — see
        # DEFAULT_SETTINGS["list_order"]. "pick" (default) = the order they
        # stand in the picker on the left, so all the guitars come after each
        # other; "position" = the old split by room position (FRONT/MID/BACK
        # in the Channel Plan, reverb bus in the Instruments view). The
        # StringVar is the single source of truth, so the View menu and the
        # panel button stay in step by themselves.
        _order = self.settings.get("list_order", "pick")
        if _order not in ("pick", "position"):
            _order = "pick"
        self.list_order_var = tk.StringVar(value=_order)
        # Per-instrument "expanded" summary blocks (set of instrument ids).
        self._expanded_blocks = set()

        # 📋 Instruments-view filter: tick one or more effect categories to show
        # ONLY those sections in every instrument block (default = none ticked =
        # show everything, as before). BooleanVars are created in _build_summary.
        #
        # 2026-09-14: Low cut · EQ · Comp. · SubMass · Pan are now ONE box.
        # 2026-09-19: SubMass taken back OUT of it - see the note on the row.
        # His reason, and it is the right one: those are the settings he
        # never goes back and changes — they are dialled once and then they are
        # simply true. Boxes he never ticks were boxes of noise on the
        # row; one box ("⚙ Set & forget") brings them all back on the rare day
        # he wants to look at them. The section keys underneath are UNCHANGED,
        # so _build_summary_block and every saved settings file still work —
        # including one saved while "submass" was still inside the bundle: the
        # saved value is the BOX key "setforget", and that box still exists.
        self.INSTR_FILTERS = [
            ("setforget", "⚙ Set & forget"),   # = lowcut + eq + comp + pan + corridor + omega
            # SubMass came OUT of that bundle on 2026-09-19. The bundle's
            # reason was "settings that are dialled once and then simply
            # stay true", and that stopped being true for SubMass: it is a
            # FOCUS plug-in being actively dialled, and while it was inside
            # the bundle, ticking ANY other box hid it with no way back
            # except ticking four unrelated sections as well.
            ("submass", "🌑 SubMass"),
            ("eqgroup", "EQ-group"),
            ("stage",   "Stage"),
            ("duck",    "Duck"),
            ("reverb",  "Reverb"),
            ("bandwidth", "↔ Width"),
            ("cascadia", "≈ Cascadia"),
            ("knock",   "\U0001f94a Knock"),
            ("multi",   "✖N"),
        ]
        # A filter KEY on the row -> the section keys it actually turns on.
        # Anything not listed stands for itself.
        self.INSTR_FILTER_EXPAND = {
            "setforget": ("lowcut", "eq", "comp", "pan", "corridor", "omega"),
        }
        self._instr_filter_vars = {}

        self._build_ui()
        self._apply_settings()

        self.root.protocol("WM_DELETE_WINDOW", self._on_close)
        self.root.bind("<Configure>", self._on_configure)

    # ---- BUILD UI -----------------------------------------------------------

    def _build_ui(self):
        self._build_menu()

        # Top title bar
        title_bar = tk.Frame(self.root, bg=C_BG3, pady=6)
        title_bar.pack(fill="x")
        tk.Label(title_bar, text="🎛  EQ Cheat Sheet — Rock Music Production",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left", padx=14)
        # ♪ The song being worked on, on every tab. Fixed width: a long name is
        # cut with "…" instead of pushing the buttons around (_sync_current_song_mark).
        self.now_song_lbl = tk.Label(title_bar, text="", width=SONG_NOW_CHARS,
                                     anchor="w", bg=C_ACCENT, fg=C_SONG_NOW_FG,
                                     font=FONT_HEADER, padx=8, pady=2)
        self.now_song_lbl.pack(side="left", padx=(0, 8))
        tk.Label(title_bar, text=f"v{APP_VERSION}",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL).pack(side="right", padx=14)
        # 🔎 The one button that swaps the window between its two faces. It sits
        # next to the version, LEFT of everything that can be hidden, so it never
        # moves under the pointer when the rest of the bar comes and goes.
        # Its own label says what the NEXT click gives you, not what you have.
        self.focus_btn = tk.Button(title_bar, text="",
                  bg="#3a5a3a", fg=C_BTN_FG,   # change colour here (green-ish)
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2",
                  command=self._toggle_focus_view)
        self.focus_btn.pack(side="right", padx=(0, 8))
        tk.Button(title_bar, text="🎪 Stage map",
                  bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2",
                  command=self._show_stage_map).pack(side="right", padx=(0, 8))
        # Hidden by the focus view (pure theory — the Explain menu has it too).
        self.freqbands_btn = tk.Button(title_bar, text="📐 Frequency Bands",
                  bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2",
                  command=self._show_freq_bands)
        self.freqbands_btn.pack(side="right", padx=(0, 8))

        # ── EQ engine selector ───────────────────────────────────────────────
        # Switches every card / summary between exact Kirchhoff parameters and
        # the original start–end range view. Hidden by the focus view: he has
        # never moved it off Kirchhoff, and it costs a whole row of the window.
        engine_bar = tk.Frame(self.root, bg=C_BG2, pady=4)
        self.engine_bar = engine_bar
        engine_bar.pack(fill="x")
        tk.Label(engine_bar, text="EQ engine:",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left", padx=(14, 8))

        for text, value in [
            (f"🎯 Kirchhoff EQ V{KIRCHHOFF_VERSION} — Parametric Q (exact)", "kirchhoff"),
            ("📏 Generic — Range (start–end)",                               "range"),
        ]:
            tk.Radiobutton(
                engine_bar, text=text,
                variable=self.eq_mode, value=value,
                bg=C_BG2, fg=C_FG,
                selectcolor=C_BG3,
                activebackground=C_BG2, activeforeground=C_FG,
                font=FONT_SMALL, indicatoron=1,
                cursor="hand2",
                command=self._on_eq_mode_change,
            ).pack(side="left", padx=(0, 12))

        tk.Label(engine_bar,
                 text="(Kirchhoff = exact Type · Freq · Gain · Q · Slope)",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left", padx=(4, 0))

        # PanedWindow: left=tabs, right=summary
        self.pane = tk.PanedWindow(self.root, orient="horizontal",
                                   bg=C_BG, sashwidth=5, sashrelief="flat",
                                   bd=0)
        self.pane.pack(fill="both", expand=True, padx=0, pady=0)

        # LEFT: tabbed instrument groups
        left_frame = tk.Frame(self.pane, bg=C_BG)
        self.pane.add(left_frame, minsize=200)
        self._build_tabs(left_frame)

        # RIGHT: summary panel
        right_frame = tk.Frame(self.pane, bg=C_BG2, bd=0)
        self.pane.add(right_frame, minsize=180)
        self._build_summary(right_frame)

        # Save sash position only when user explicitly drags it
        self.pane.bind("<ButtonRelease-1>", self._on_sash_drag)

        # v3.29: fold / show the whole left side (tabs, Song Variants). Folded = Selected Instruments
        # alone, at the far left; shown again = the left side comes back and it moves to the right.
        self._left_frame, self._right_frame = left_frame, right_frame
        self._apply_left_fold()

        # Both faces of the window exist now — put on the one he left it in.
        self._apply_focus_view()

    # ---- 🔎 FOCUS VIEW -------------------------------------------------------
    # Two faces, one button, nothing thrown away.
    #
    # What he actually works in is a short list: "Instruments in this variant"
    # on the left, "Selected Instruments" on the right, and the 📐 Channel Plan
    # one click away on the same View row. Everything else in this program is
    # good — it is just not something he reads every session, and a panel he
    # does not read is a panel he has to scroll past.
    #
    # So the focus view UNPACKS the rest. It does not destroy widgets and it
    # does not touch a single setting: the theory tabs keep their own View-menu
    # tick, the Plugins tab keeps its stars, the conflict text keeps its text.
    # Click the button again and they are packed back exactly where they were.
    #
    # WHAT THE FOCUS VIEW HIDES (his answers, 2026-09-14):
    #   · the EQ engine row              — "vet jag inte ens vad det är"
    #   · ⚠ Conflicts & recommendations  — "kollar jag aldrig heller"; four
    #     cymbals are four cymbals, and Virtual Stage is what spreads them
    #   · the 📚 theory tabs + the 🧩 Plugins tab
    #   · 📐 Frequency Bands, 🌫 Reverb Groups, 🎯 smart:EQ Groups, 🗺 Roadmap,
    #     🦻 My rules  — all four popups are on the View menu as well, so
    #     nothing here is reachable ONLY through a hidden button
    # WHAT IT KEEPS: the variant list and its toolbar, the Selected Instruments
    # panel with all three View buttons, the Filter row, the BOOST/CUT/TRY
    # legend, and 🎪 Stage map.

    def _apply_focus_view(self):
        """Show the short face or the long one. Safe to call at any time."""
        focus = bool(self.focus_view_var.get())

        # Button label = what the next click does.
        btn = getattr(self, "focus_btn", None)
        if btn is not None:
            btn.config(text="⚙ Show everything" if focus else "🔎 Focus")

        # Row of radio buttons under the title bar.
        bar = getattr(self, "engine_bar", None)
        if bar is not None:
            if focus:
                bar.pack_forget()
            elif not bar.winfo_manager():
                # Must go back ABOVE the paned window, not at the bottom.
                bar.pack(fill="x", before=self.pane)

        # Title-bar theory button.
        fb = getattr(self, "freqbands_btn", None)
        if fb is not None:
            if focus:
                fb.pack_forget()
            elif not fb.winfo_manager():
                fb.pack(side="right", padx=(0, 8))

        # The four popup buttons on the right panel's View row, and then the
        # ⚠ Conflicts & recommendations block at the foot of Song Variants.
        # Each entry is (widget, the pack() kwargs it was built with) — kept
        # in a plain list rather than stamped onto the widget, because an
        # attribute set on a Tk widget can shadow one of Tkinter's own.
        for group in ("_panel_extra_btns", "_var_conflict_widgets"):
            for w, pack_kw in getattr(self, group, ()):
                if focus:
                    w.pack_forget()
                elif not w.winfo_manager():
                    w.pack(**pack_kw)

        # Tabs: the theory tabs follow their own View-menu tick when the long
        # face is on, and are simply out of the way on the short one.
        self._apply_theory_tabs()
        nb = getattr(self, "notebook", None)
        pf = getattr(self, "plugins_frame", None)
        if nb is not None and pf is not None:
            try:
                if focus:
                    nb.hide(pf)
                else:
                    nb.add(pf, text="  🧩 Plugins  ")
            except tk.TclError:
                pass            # already in that state

    def _toggle_focus_view(self):
        """The title-bar button (and the View-menu tick) — swap the two faces."""
        self.focus_view_var.set(not self.focus_view_var.get())
        self._on_focus_view_change()

    def _on_focus_view_change(self):
        """Apply and remember. Used by the button and by the View menu."""
        self._apply_focus_view()
        self.settings["focus_view"] = bool(self.focus_view_var.get())
        self._save_current_settings()

    # ---- MENU ---------------------------------------------------------------

    def _build_menu(self):
        mb = tk.Menu(self.root, bg=C_BG, fg=C_FG, tearoff=0,
                     activebackground=C_BG3, activeforeground=C_FG)
        self.root.config(menu=mb)

        file_menu = tk.Menu(mb, bg=C_BG, fg=C_FG, tearoff=0,
                            activebackground=C_BG3, activeforeground=C_FG)
        mb.add_cascade(label="File", menu=file_menu)
        file_menu.add_command(label="Clear all selections (same as ↩ Reset)",
                              command=self._clear_all)
        file_menu.add_command(
            label="⚓ Set the line-up on the left as my Ground",
            command=self._set_ground)
        file_menu.add_separator()
        file_menu.add_command(label="Set Kirchhoff preset folder…", command=self._set_keq_folder)
        file_menu.add_command(label="Set Kirchhoff .vstpreset (Cubase) folder…", command=self._set_keq_vst3_folder)
        file_menu.add_command(label="Set smart:reverb preset folder…", command=self._set_smartreverb_folder)
        file_menu.add_command(label="Set Lowtility preset folder…", command=self._set_lowtility_folder)
        file_menu.add_command(label="Set SubMass preset folder…", command=self._set_submass_folder)
        file_menu.add_command(label="Set KNOCK 1 / KNOCK 2 preset folders…", command=self._set_knock_folders)
        file_menu.add_command(label="Set Corridor preset folder…", command=self._set_corridor_folder)
        file_menu.add_command(label="Set Omega 458a preset folder…", command=self._set_omega_folder)
        file_menu.add_command(label="Set Bandwidth preset folder…", command=self._set_bandwidth_folder)
        file_menu.add_command(label="Set Cascadia (Cubase .vstpreset) folder…", command=self._set_cascadia_folder)
        file_menu.add_command(label="Set Cascadia (own browser .preset) folder…", command=self._set_cascadia_native_folder)
        file_menu.add_command(label="Set Virtual Stage preset folder…", command=self._set_vstage_folder)
        file_menu.add_command(label="Set SWAM preset folder…", command=self._set_swam_folder)
        file_menu.add_command(label="SWAM: choose the sound to build from…", command=self._swam_seed_dialog)
        file_menu.add_command(label="SWAM: Expression and Vibrato in the presets…", command=self._swam_tune_dialog)
        file_menu.add_command(label="SWAM: copies that take turns (this song)…", command=self._swam_turns_dialog)
        file_menu.add_command(label="Set PatchWork preset folder…", command=self._set_patchwork_folder)
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=self._on_close)

        # ---- Generate menu (was the 'Selected / All' buttons in the right panel) --
        gen_menu = tk.Menu(mb, bg=C_BG, fg=C_FG, tearoff=0,
                           activebackground=C_BG3, activeforeground=C_FG)
        mb.add_cascade(label="Generate", menu=gen_menu)
        gen_menu.add_command(label="📊 Overview: Selected", command=self._show_overview_selected)
        gen_menu.add_command(label="📊 Overview: All",      command=self._show_overview_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🗺 Roadmap (what feeds what)", command=self._show_roadmap)
        gen_menu.add_separator()
        gen_menu.add_command(label="🎪 Stage map (Virtual Stage placement)",
                             command=self._show_stage_map)
        gen_menu.add_separator()
        gen_menu.add_command(label="🧭 Planner (buses & dynamics): Selected", command=self._show_planner_selected)
        gen_menu.add_command(label="🧭 Planner (buses & dynamics): All",      command=self._show_planner_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🎛 Kirchhoff presets: Selected", command=self._generate_presets_selected)
        gen_menu.add_command(label="🎛 Kirchhoff presets: All",      command=self._generate_presets_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🌫 smart:reverb presets: Selected", command=self._generate_sonible_selected)
        gen_menu.add_command(label="🌫 smart:reverb presets: All",      command=self._generate_sonible_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🔻 Lowtility presets: Selected", command=self._generate_lowtility_selected)
        gen_menu.add_command(label="🔻 Lowtility presets: All",      command=self._generate_lowtility_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🌑 SubMass presets: Selected", command=self._generate_submass_selected)
        gen_menu.add_command(label="🌑 SubMass presets: All",      command=self._generate_submass_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="\U0001f94a Knock presets: Selected", command=self._generate_knock_selected)
        gen_menu.add_command(label="\U0001f94a Knock presets: All (+ Drum_Bus, Mix_Bus)", command=self._generate_knock_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🌀 Corridor presets: Selected", command=self._generate_corridor_selected)
        gen_menu.add_command(label="🌀 Corridor presets: All",      command=self._generate_corridor_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🔥 Omega 458a presets: Selected", command=self._generate_omega_selected)
        gen_menu.add_command(label="🔥 Omega 458a presets: All",      command=self._generate_omega_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="↔ Bandwidth presets: Selected", command=self._generate_bandwidth_selected)
        gen_menu.add_command(label="↔ Bandwidth presets: All",      command=self._generate_bandwidth_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="≈ Cascadia presets: Selected", command=self._generate_cascadia_selected)
        gen_menu.add_command(label="≈ Cascadia presets: All",      command=self._generate_cascadia_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="🎪 Virtual Stage presets: Selected", command=self._generate_vstage_selected)
        gen_menu.add_command(label="🎪 Virtual Stage presets: All (instruments, guitar pair, toms, cymbals)",
                             command=self._generate_vstage_all)
        gen_menu.add_separator()
        gen_menu.add_command(label="\U0001f3bb SWAM room presets: this song (the SWAM-ticked instruments)",
                             command=self._generate_swam_button)
        gen_menu.add_separator()
        gen_menu.add_command(label="🧩 PatchWork full chain: Selected", command=self._generate_patchwork_selected)
        gen_menu.add_command(label="🧩 PatchWork full chain: All",      command=self._generate_patchwork_all)
        gen_menu.add_separator()

        # Generation options — the checkboxes that used to live on the button rows.
        opt_menu = tk.Menu(gen_menu, bg=C_BG, fg=C_FG, tearoff=0,
                           activebackground=C_BG3, activeforeground=C_FG)
        gen_menu.add_cascade(label="Options…", menu=opt_menu)
        opt_menu.add_checkbutton(label="Kirchhoff: bake Mid/Side", variable=self.keq_ms_var,
                                 command=self._on_keq_ms_toggle)
        opt_menu.add_checkbutton(label="Kirchhoff: no high-pass (Lowtility does it)",
                                 variable=self.keq_nohp_var, command=self._on_keq_nohp_toggle)
        opt_menu.add_checkbutton(label="Kirchhoff: also write Cubase .vstpreset",
                                 variable=self.keq_vst3_var, command=self._on_keq_vst3_toggle)
        opt_menu.add_separator()
        opt_menu.add_checkbutton(label="smart:reverb: one preset per tier (buses)",
                                 variable=self.sonible_pertier_var,
                                 command=self._on_sonible_pertier_toggle)
        opt_menu.add_separator()
        opt_menu.add_radiobutton(label="Knock version: KNOCK 1 (Plugins That Knock)", variable=self.knock_version_var,
                                 value="1", command=self._on_knock_version)
        opt_menu.add_radiobutton(label="Knock version: KNOCK 2 (Knock Audio)", variable=self.knock_version_var,
                                 value="2", command=self._on_knock_version)
        opt_menu.add_separator()
        opt_menu.add_radiobutton(label="🎪 Stage: audience view (hi-hat on the RIGHT)",
                                 variable=self.stage_persp_var, value="audience",
                                 command=self._on_stage_persp_change)
        opt_menu.add_radiobutton(label="🎪 Stage: drummer's view (hi-hat on the LEFT)",
                                 variable=self.stage_persp_var, value="drummer",
                                 command=self._on_stage_persp_change)

        # ---- View menu — how much of the prose to print ----------------------
        # These are DISPLAY settings, not generation settings, so they get their
        # own menu instead of hiding under Generate ▸ Options.
        view_menu = tk.Menu(mb, bg=C_BG, fg=C_FG, tearoff=0,
                            activebackground=C_BG3, activeforeground=C_FG)
        mb.add_cascade(label="View", menu=view_menu)
        # 🔎 The two faces of the window — the same switch as the title-bar
        # button, first in the menu because it is the one that changes most.
        view_menu.add_checkbutton(
            label="🔎 Focus view — just the variant list, the panel and the plan",
            variable=self.focus_view_var,
            command=self._on_focus_view_change)
        view_menu.add_command(
            label="   (off = every panel: theory tabs, plugins, EQ engine, conflicts)",
            state="disabled")
        view_menu.add_separator()
        view_menu.add_checkbutton(
            label="⟳ Update button — the left side waits until you click it",
            variable=self.hold_left_var,
            command=self._on_hold_change)
        view_menu.add_command(
            label="   (off = the right panel redraws on every tick, as it used to)",
            state="disabled")
        view_menu.add_separator()
        view_menu.add_checkbutton(
            label="💬 Why-lines — the 'why this number' comments",
            variable=self.extra_comments_var,
            command=self._on_comment_setting_change)
        view_menu.add_checkbutton(
            label="↕ Compact — no empty comment rows, tighter sections",
            variable=self.hide_empty_var,
            command=self._on_comment_setting_change)
        view_menu.add_separator()
        # ⇅ The same switch as the button on the right panel's View row — one
        # StringVar, so the menu and the button can never disagree.
        view_menu.add_radiobutton(
            label="⇅ Pick order — the order the instruments stand in the picker "
                  "(all the guitars after each other)",
            variable=self.list_order_var, value="pick",
            command=self._on_list_order_change)
        view_menu.add_radiobutton(
            label="⇅ Per position — split by where it sits: FRONT/MID/BACK in the "
                  "plan, reverb bus in the instrument list",
            variable=self.list_order_var, value="position",
            command=self._on_list_order_change)
        view_menu.add_separator()
        view_menu.add_checkbutton(
            label="📚 Theory tabs — the per-group EQ cards (focus view off)",
            variable=self.theory_tabs_var,
            command=self._on_theory_tabs_change)
        view_menu.add_separator()
        # The two group popups also sit on the right panel's View row, which
        # the focus view unpacks — so they need a home on the menu bar too,
        # or they would be reachable only by leaving the short face.
        view_menu.add_command(label="🌫 Reverb Groups…",
                              command=self._show_smartreverb_groups)
        view_menu.add_command(label="🎯 smart:EQ Groups…",
                              command=self._show_smarteq_groups)
        view_menu.add_command(label="🎪 Stage map…", command=self._show_stage_map)
        view_menu.add_command(label="✋ Virtual Stage by hand — role, side, "
                                    "counterpoles…",
                              command=self._show_stage_manual)
        view_menu.add_separator()
        view_menu.add_checkbutton(
            label="Δ Only what differs — grey out what your preset already does",
            variable=self.default_diff_var,
            command=self._on_default_diff_change)
        view_menu.add_command(
            label="📐 Defaults — what to save in each preset…",
            command=self._show_defaults)
        view_menu.add_radiobutton(
            label="   …from MY default band (everything else is a guest in it)",
            variable=self.defaults_src_var, value="band",
            command=self._on_defaults_source_change)
        view_menu.add_radiobutton(
            label="   …voted over ten typical songs (built in)",
            variable=self.defaults_src_var, value="typical",
            command=self._on_defaults_source_change)
        view_menu.add_radiobutton(
            label="   …voted over MY song variants",
            variable=self.defaults_src_var, value="variants",
            command=self._on_defaults_source_change)
        view_menu.add_separator()
        view_menu.add_command(
            label="(All three are also on the Filter row of the Instruments panel.)",
            state="disabled")
        view_menu.add_command(
            label="(Δ grey = already in your preset. Δ in colour = dial it.)",
            state="disabled")
        view_menu.add_separator()
        view_menu.add_command(
            label="(Settings you dial in are never hidden — only the reasons.)",
            state="disabled")
        view_menu.add_command(
            label="(The 🎪 Stage map and Explain ▸ windows always show everything.)",
            state="disabled")

        # ---- Explain menu — short "so this is how it works" reads ----
        explain_menu = tk.Menu(mb, bg=C_BG, fg=C_FG, tearoff=0,
                               activebackground=C_BG3, activeforeground=C_FG)
        mb.add_cascade(label="Explain", menu=explain_menu)
        explain_items = [
            ("defaults",    "Δ Defaults — why most of the sheet is grey…"),
            ("multiples",   "One or several of the same instrument…"),
            ("hearing",     "Mixing when you cannot trust your ears…"),
            ("roadmap",     "Buses & the Roadmap — what feeds what…"),
            ("insert_send", "Insert vs. Send (reverb & delay)…"),
            ("reverb_buses", "Reverb depth buses — Near / Mid / Far / Front…"),
            ("vstage",      "Virtual Stage — placing the band, and its presets…"),
            ("corridor",    "Corridor reverb — the preset bundle…"),
            ("omega",       "Omega 458a — saturation, and what Intensity really does…"),
            ("bandwidth",   "Bandwidth — stereo width, and what Strength does…"),
            ("cascadia",    "Cascadia — the delay send, and how its presets work…"),
            ("presets",     "Generating & loading presets…"),
            ("smarteq",     "smart:EQ groups (Front / Mid / Back)…"),
            ("duck",        "Ducking — start gentle…"),
            ("midside",     "Mid/Side EQ (Kirchhoff)…"),
            ("channelplan", "Channel Plan, stems & inserts map…"),
            ("scope",       "Notation: ( ) and (( ))…"),
        ]
        for key, label in explain_items:
            explain_menu.add_command(label=label,
                                     command=lambda k=key: self._show_explain(k))

        help_menu = tk.Menu(mb, bg=C_BG, fg=C_FG, tearoff=0,
                            activebackground=C_BG3, activeforeground=C_FG)
        mb.add_cascade(label="Help", menu=help_menu)
        help_menu.add_command(label="How to use this program...", command=self._show_help)
        help_menu.add_command(label="Frequency Bands Explained...", command=self._show_freq_bands)
        help_menu.add_separator()
        help_menu.add_command(label="🦻 Hearing profile — what can you judge by ear?...",
                              command=self._show_hearing_dialog)
        help_menu.add_command(label="🦻 My rules (mixing with hearing loss)...",
                              command=self._show_hearing_rules)
        help_menu.add_separator()
        help_menu.add_command(label="About...", command=self._show_about)

    # ---- TABS ---------------------------------------------------------------

    def _build_tabs(self, parent):
        style = ttk.Style()
        style.theme_use("default")
        style.configure("Dark.TNotebook",
                        background=C_BG, borderwidth=0, tabmargins=[2,2,2,0])
        style.configure("Dark.TNotebook.Tab",
                        background=C_BG2, foreground=C_FG_DIM,
                        padding=[12, 5], font=FONT_NORMAL)
        style.map("Dark.TNotebook.Tab",
                  background=[("selected", C_BG3)],
                  foreground=[("selected", C_FG)])

        self.notebook = ttk.Notebook(parent, style="Dark.TNotebook")
        self.notebook.pack(fill="both", expand=True, padx=0, pady=0)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_change)

        self.tab_frames = {}
        for group in GROUPS:
            frame = tk.Frame(self.notebook, bg=C_BG)
            self.notebook.add(frame, text=f"  {group}  ")
            self.tab_frames[group] = frame
            self._build_group_tab(frame, group)

        # Tab 7: Song Variants — built after the group tabs (so check_vars exist),
        # then inserted at position 0 so it is the default tab.
        self._build_variants_tab()
        # Plugins tab — inserted at position 1 (right after Song Variants).
        self._build_plugins_tab()

        # All/none boxes start in step with the restored selection.
        self._sync_group_all_boxes()

        # Working mode vs theory mode — hide the group tabs if that is how
        # he left it. Done last, so every tab exists before one is hidden.
        self._apply_theory_tabs()

    def _apply_theory_tabs(self):
        """Show or hide the per-group EQ-card tabs to match the toggle.

        hide() keeps the tab and everything in it — the checkboxes, the
        scroll position, the live notes — so switching back costs nothing
        and loses nothing. ★ Song Variants and 🧩 Plugins always stay.

        Those two live in the same tab_frames dict under the keys
        "__variants__" and "__plugins__", so they have to be stepped over
        explicitly — walking the whole dict hid the Song Variants tab along
        with the theory ones and relabelled it "__variants__" on the way
        back. Their own visibility is decided elsewhere (Song Variants is
        always on; the Plugins tab follows the 🔎 focus view).

        The focus view wins over the tick: on the short face the theory tabs
        are out of the way whatever the View menu says, and the tick is left
        untouched so the long face comes back exactly as he left it."""
        nb = getattr(self, "notebook", None)
        if nb is None:
            return
        show = (bool(self.theory_tabs_var.get())
                and not bool(self.focus_view_var.get()))
        for group, frame in self.tab_frames.items():
            if group in ("__variants__", "__plugins__"):
                continue
            try:
                if show:
                    nb.add(frame, text=f"  {group}  ")
                else:
                    nb.hide(frame)
            except tk.TclError:
                pass            # tab already in that state

    def _on_theory_tabs_change(self):
        """View ▸ Theory tabs was ticked or unticked."""
        self._apply_theory_tabs()
        self.settings["show_theory_tabs"] = bool(self.theory_tabs_var.get())
        self._save_current_settings()

    def _build_group_tab(self, parent, group):
        """Build a group tab: filter toolbar + scrollable instrument cards."""

        # ── Filter toolbar ──────────────────────────────────────────────────
        toolbar = tk.Frame(parent, bg=C_BG2, pady=5, padx=10)
        toolbar.pack(fill="x")

        tk.Label(toolbar, text="Show bands:",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left", padx=(0, 8))

        filter_opts = [
            ("All",          "all",   C_FG),
            ("Boost",        "boost", C_BOOST),
            ("Cut",          "cut",   C_CUT),
            ("Try",          "char",  C_CHAR),
        ]
        for label, value, color in filter_opts:
            rb = tk.Radiobutton(
                toolbar, text=label,
                variable=self._band_filter, value=value,
                bg=C_BG2, fg=color,
                selectcolor=C_BG3,
                activebackground=C_BG2, activeforeground=C_FG,
                font=FONT_SMALL,
                indicatoron=1,
                command=self._on_filter_change,
            )
            rb.pack(side="left", padx=(0, 10))

        # ── All / none for THIS group (right-hand side of the same toolbar) ──
        # One click ticks (or unticks) every instrument in the tab. Tri-state
        # when only some of them are ticked.
        allvar = tk.StringVar(value="0")
        self._group_all_vars[group] = allvar
        all_cb = tk.Checkbutton(
            toolbar, text=f"All / none  ({len(GROUP_MAP[group])})",
            variable=allvar, onvalue="1", offvalue="0", tristatevalue="mix",
            bg=C_BG2, fg=C_ACCENT,                # normal colour: C_ACCENT = "#7eb8f7"
            selectcolor=C_BG3,                    # normal colour: C_BG3 = "#0f3460"
            activebackground=C_BG2, activeforeground=C_FG,
            font=("Segoe UI", 8, "bold"), highlightthickness=0, bd=0,
            cursor="hand2",
            command=lambda g=group: self._on_group_all(g))
        all_cb.pack(side="right")
        tk.Label(toolbar, text="Whole tab:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="right", padx=(0, 6))

        tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x")
        # Outer scrollable area
        canvas = tk.Canvas(parent, bg=C_BG, bd=0, highlightthickness=0)
        vsb = tk.Scrollbar(parent, orient="vertical", command=canvas.yview,
                           bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canvas.configure(yscrollcommand=vsb.set)

        vsb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)

        inner = tk.Frame(canvas, bg=C_BG)
        window_id = canvas.create_window((0, 0), window=inner, anchor="nw")

        # Save refs for filter rebuilds
        self._group_inner[group]  = inner
        self._group_canvas[group] = canvas

        def _on_frame_configure(e):
            canvas.configure(scrollregion=canvas.bbox("all"))

        def _on_canvas_configure(e):
            canvas.itemconfig(window_id, width=e.width)

        inner.bind("<Configure>", _on_frame_configure)
        canvas.bind("<Configure>", _on_canvas_configure)

        # Smooth wheel scrolling: bind the handler to the canvas AND every
        # descendant widget (recursively, see _bind_wheel below) so the wheel
        # works no matter which card, row or label the pointer is over.
        # Missing child bindings were the cause of the previous "jank".
        def _wheel(e, _c=canvas):
            _c.yview_scroll(-2 if e.delta > 0 else 2, "units")
            return "break"

        canvas.bind("<MouseWheel>", _wheel)
        inner.bind("<MouseWheel>", _wheel)

        instruments = GROUP_MAP[group]
        for inst in instruments:
            self._build_instrument_card(inner, inst, _wheel)

        self._bind_wheel(inner, _wheel)   # cover every child widget

    def _on_mousewheel(self, event, canvas):
        """Scroll the currently visible canvas with mouse wheel."""
        try:
            canvas.yview_scroll(-2 if event.delta > 0 else 2, "units")
        except Exception:
            pass

    def _bind_wheel(self, widget, fn):
        """Recursively bind the mouse-wheel handler to a widget and ALL its
        children, so scrolling is smooth over every part of the left panel
        (cards, band rows, labels) — not just the canvas itself."""
        try:
            widget.bind("<MouseWheel>", fn)
        except Exception:
            pass
        for ch in widget.winfo_children():
            self._bind_wheel(ch, fn)

    def _on_filter_change(self):
        """Rebuild instrument cards in all groups to reflect the new band filter."""
        fval = self._band_filter.get()
        for group, inner in self._group_inner.items():
            # Destroy existing cards
            for w in inner.winfo_children():
                w.destroy()
            self._prune_live_notes()   # their live footnotes went with them
            instruments = GROUP_MAP[group]
            # Recreate wheel fn closure (we can't easily recover the original,
            # so we rebind to the group's canvas)
            _cv = self._group_canvas[group]
            def _wheel(e, _c=_cv):
                _c.yview_scroll(-2 if e.delta > 0 else 2, "units")
                return "break"
            for inst in instruments:
                self._build_instrument_card(inner, inst, _wheel, band_filter=fval)
            self._bind_wheel(inner, _wheel)   # cover every child widget
            # Reset scroll to top
            _cv.yview_moveto(0)
        # The cards (and their check vars) were just rebuilt — re-sync the
        # per-tab All/none boxes against the fresh variables.
        self._sync_group_all_boxes()

    def _on_eq_mode_change(self):
        """Switch between the Kirchhoff (exact) and Range (start–end) engines,
        rebuilding both the left cards and the right summary panel."""
        self.settings["eq_mode"] = self.eq_mode.get()
        save_settings(self.settings)
        self._on_filter_change()   # rebuild left-hand cards in the new engine
        self._refresh_summary()    # rebuild right-hand summary in the new engine

    # ---- INSTRUMENT CARD ----------------------------------------------------

    def _build_instrument_card(self, parent, inst, wheel_fn=None, band_filter="all"):
        """Build a single instrument card with checkbox, bands, tip, and EQ curve."""
        iid = inst["id"]

        # Determine which bands to show
        if band_filter == "all":
            visible_bands = inst["bands"]
        else:
            visible_bands = [b for b in inst["bands"] if b["type"] == band_filter]

        # If filtering and no bands match, show a minimal placeholder card
        if band_filter != "all" and not visible_bands:
            stub = tk.Frame(parent, bg=C_CARD, relief="flat", bd=0)
            stub.pack(fill="x", padx=10, pady=(8, 0))
            inner_s = tk.Frame(stub, bg=C_CARD, padx=12, pady=6)
            inner_s.pack(fill="x")
            hdr_s = tk.Frame(inner_s, bg=C_CARD)
            hdr_s.pack(fill="x")
            dot_color = inst.get("color", C_FG)
            tk.Label(hdr_s, text="●", fg=dot_color, bg=C_CARD,
                     font=("Segoe UI", 14)).pack(side="left", padx=(0, 6))
            tk.Label(hdr_s, text=inst["name"],
                     bg=C_CARD, fg=C_FG_DIM, font=FONT_TITLE).pack(side="left", padx=(4, 0))
            tk.Label(hdr_s, text="  — no bands match this filter",
                     bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left")
            tk.Frame(stub, bg=C_SEP, height=1).pack(fill="x")
            if wheel_fn:
                for w in (stub, inner_s, hdr_s):
                    w.bind("<MouseWheel>", wheel_fn)
            return

        # Card outer frame
        card = tk.Frame(parent, bg=C_CARD, relief="flat", bd=0)
        card.pack(fill="x", padx=10, pady=(8, 0))

        # Inner padding frame
        inner = tk.Frame(card, bg=C_CARD, padx=12, pady=10)
        inner.pack(fill="x")

        # --- Header row: checkbox + instrument name ---
        hdr = tk.Frame(inner, bg=C_CARD)
        hdr.pack(fill="x")

        var = tk.BooleanVar(value=(iid in self.settings.get("checked", [])))
        self.check_vars[iid] = var

        dot_color = inst.get("color", C_FG)
        dot = tk.Label(hdr, text="●", fg=dot_color, bg=C_CARD,
                       font=("Segoe UI", 14))
        dot.pack(side="left", padx=(0, 6))

        cb = tk.Checkbutton(hdr, variable=var, bg=C_CARD,
                            fg=C_FG, selectcolor=C_BG2,
                            activebackground=C_CARD, activeforeground=C_FG,
                            highlightthickness=0, bd=0,
                            command=lambda i=iid: self._on_check(i))
        cb.pack(side="left")

        name_lbl = tk.Label(hdr, text=inst["name"],
                            bg=C_CARD, fg=C_FG, font=FONT_TITLE)
        name_lbl.pack(side="left", padx=(4, 0))

        sub_lbl = tk.Label(hdr, text=f"  —  {inst['sub']}",
                           bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL)
        sub_lbl.pack(side="left")

        # Make the whole header clickable to toggle checkbox
        for w in (dot, name_lbl, sub_lbl):
            w.bind("<Button-1>", lambda e, v=var, i=iid: self._toggle_check(v, i))

        # --- HOW MANY of this instrument (shares its variable with the Song
        # Variants tab). One is the normal case; 2+ changes real advice, so the
        # ✖N footnote below appears as soon as you raise it. ---
        cnt_box = tk.Frame(hdr, bg=C_CARD)
        cnt_box.pack(side="right")
        tk.Label(cnt_box, text="how many:", bg=C_CARD, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(0, 3))
        cspin = tk.Spinbox(cnt_box, from_=1, to=MAX_INSTRUMENT_COUNT, width=2,
                           textvariable=self._vcount_vars[iid], justify="center",
                           bg=C_BG2, fg=C_CHAR,            # normal colour: C_CHAR = "#7eb8f7"
                           buttonbackground=C_BG2,
                           insertofftime=0, insertontime=9999999,
                           relief="flat", highlightthickness=0,
                           font=FONT_SMALL, wrap=False,
                           command=lambda i=iid: self._on_count_change(i))
        cspin.pack(side="left")
        cspin.bind("<Return>",   lambda e, i=iid: self._on_count_change(i))
        cspin.bind("<FocusOut>", lambda e, i=iid: self._on_count_change(i))

        # --- Chain order: Low cut (Lowtility) FIRST, above the Kirchhoff table ---
        sep = tk.Frame(inner, bg=C_SEP, height=1)
        sep.pack(fill="x", pady=(8, 4))

        self._build_lowcut_footnote(inner, iid, bg=C_BG2, wrap=700)

        # --- Omega 458a: the input stage, so it sits between the low cut and
        # the EQ — the low cut has already taken the rumble out before the
        # saturator ever sees it, which is the order that matters ---
        self._build_omega_footnote(inner, iid, bg=C_BG2, wrap=700)

        # --- Band table header + rows (engine-dependent) ---
        if self.eq_mode.get() == "kirchhoff":
            self._build_card_bands_kirchhoff(inner, visible_bands)
        else:
            self._build_card_bands_range(inner, visible_bands)

        # --- Tip (LIVE: a tip that names a partner instrument is rewritten when
        # that partner is not in the song — see PARTNER_NOTES) ---
        tip_frame = self._live_note(
            inner, C_BG2,
            lambda h: self._fill_tip(h, inst, wrap=700, wheel_fn=wheel_fn))

        # --- smart:EQ group placement footnote ---
        self._build_smarteq_footnote(inner, iid, bg=C_BG2, wrap=700, wheel_fn=wheel_fn)

        # --- Compressor footnote (after EQ, before reverb — chain order) ---
        self._build_comp_footnote(inner, iid, bg=C_BG2, wrap=700, wheel_fn=wheel_fn)

        # --- SubMass footnote (after comp/duck, before width/sends — chain order) ---
        self._build_submass_footnote(inner, iid, bg=C_BG2, wrap=700)

        # --- Ducking / side-chain footnote (Trackspacer · Kickstart) ---
        self._build_ducking_footnote(inner, iid, bg=C_BG2, wrap=700,
                                     wheel_fn=wheel_fn)

        # (Bandwidth and Cascadia are NOT repeated on these left-hand cards: every
        # widget counts against Windows' 10,000-object limit per process, and both
        # are shown in the right-hand panel, where their filters live.)

        # --- Depth (reverb send, front/back) footnote ---
        self._build_depth_footnote(inner, iid, bg=C_BG2, wrap=700)

        # --- Corridor reverb: which preset, and its numbers ---
        self._build_corridor_footnote(inner, iid, bg=C_BG2, wrap=700)

        # --- ✖N Multiples (LIVE: appears the moment the count goes above 1) ---
        self._live_multi(inner, C_BG2,
                         lambda h, i=iid: self._fill_multi(h, i, bg=C_BG2, wrap=700),
                         iid=iid)

        # --- EQ Curve ---
        eq_cv = tk.Canvas(inner, bg=C_BG2, bd=0, highlightthickness=0, height=54)
        eq_cv.pack(fill="x", pady=(6, 0))
        eq_cv.bind("<Configure>",
                   lambda e, cv=eq_cv, b=inst["bands"]:
                       _draw_eq_curve_on(cv, b, e.width, e.height, C_BG2))

        # Bottom border
        tk.Frame(card, bg=C_SEP, height=1).pack(fill="x")

        # Propagate wheel binding to every child so scrolling works anywhere on the card
        if wheel_fn:
            for widget in (card, inner, tip_frame, eq_cv):
                widget.bind("<MouseWheel>", wheel_fn)
            for widget in inner.winfo_children():
                try:
                    widget.bind("<MouseWheel>", wheel_fn)
                except Exception:
                    pass

    # ---- HOW MUCH PROSE -----------------------------------------------------
    # Two settings, one helper, and every explanatory line in the program goes
    # through it. The rule that decides which is which:
    #
    #   ESSENTIAL (extra=False) — the line changes what you DIAL IN.
    #       "Side-chain = Kick", "High Cut ~150 Hz · Amount ~12–20%",
    #       "Layer 2: high-passed 100–120 Hz", "⚠ two full-range basses…".
    #       These are never hidden. A cheat sheet that hides the settings is
    #       not a cheat sheet.
    #
    #   EXTRA (extra=True) — the line explains WHY that is the number.
    #       "The top of the sweep stops at ~R42 because the hi-hat is there",
    #       "Flipped to the other side: the left of the stage was already…".
    #       True, worth reading once, and pure scrolling every time after that.
    #
    # The 🎪 Stage map window and the Explain ▸ windows deliberately ignore both
    # settings: you open those ON PURPOSE to read the reasoning, so hiding it
    # there would empty the only rooms it belongs in.

    def _show_extra(self):
        """Are the 'why this number' comments switched on?"""
        try:
            return bool(self.extra_comments_var.get())
        except Exception:
            return bool(self.settings.get("show_extra_comments", False))

    def _hide_empty(self):
        """Should a section with nothing to say under it collapse the row?"""
        try:
            return bool(self.hide_empty_var.get())
        except Exception:
            return bool(self.settings.get("hide_empty_note_rows", True))

    def _note_label(self, parent, text, bg=C_BG2, fg=C_FG_DIM, wrap=700,
                    extra=False, font=None, pady=None, wheel_fn=None):
        """Pack one explanatory line, or nothing at all.

        Returns the Label, or None when the line was suppressed — callers use
        that to decide whether a section still has any body left. Suppressed
        when the line is EXTRA and extra comments are off, or when the text is
        blank and empty rows are being hidden (which is the default: an empty
        label is a 15-pixel hole with nothing in it)."""
        if extra and not self._show_extra():
            return None
        text = (text or "").strip()
        if not text and self._hide_empty():
            return None
        lbl = tk.Label(parent, text=text, bg=bg, fg=fg,
                       font=(font or FONT_SMALL), wraplength=wrap,
                       justify="left", anchor="w")
        lbl.pack(fill="x", **({"pady": pady} if pady is not None else {}))
        if wheel_fn:
            lbl.bind("<MouseWheel>", wheel_fn)
        return lbl

    def _tighten(self, frame, had_body):
        """Close the gap a section leaves behind.

        Removing the empty LABEL was never enough: every footnote frame carries
        pady=5 of its own plus pady=(6,0) where it is packed, so a section with
        only a head line still reserved about 16 px of nothing, and six of those
        per instrument is most of a screen. With 'hide empty comment rows' on,
        a section that has a body gets a compact rhythm and a section with
        nothing under its head line gets none at all. Off, the old roomier
        spacing comes back exactly as it was."""
        if not self._hide_empty():
            return frame
        try:
            if had_body:
                frame.configure(pady=2)
                frame.pack_configure(pady=(3, 0))
            else:
                frame.configure(pady=0)
                frame.pack_configure(pady=(2, 0))
        except Exception:
            pass
        return frame

    def _on_comment_setting_change(self):
        """Both prose toggles land here: remember them, then redraw the two
        panels that print prose. This is a deliberate, one-click change, so a
        full rebuild is the honest way to do it — nothing animates."""
        self.settings["show_extra_comments"] = bool(self.extra_comments_var.get())
        self.settings["hide_empty_note_rows"] = bool(self.hide_empty_var.get())
        save_settings(self.settings)
        self._on_filter_change()   # left-hand instrument cards
        self._refresh_summary()    # right-hand panel

    # ---- Δ DEFAULTS: draw the difference, not the whole answer (DEL 02p) ----
    # The head line of every engine is a list of fields. When Δ is on, each
    # field is compared with what that instrument's DEFAULT holds — the value
    # he saved in the plug-in's own preset — and a field that matches goes grey.
    # What is left in colour is the short list of things this song needs him to
    # actually touch, and a section with nothing in colour is a section he can
    # skip entirely.
    #
    # Drawn as one Label per field instead of one Label for the line, because a
    # Label has exactly one colour. That means doing the wrapping by hand: the
    # width of each field is MEASURED with the same font it is drawn in and a
    # new row is started before the budget is passed. Measuring is deterministic,
    # so the line never reflows on its own and nothing blinks — a <Configure>
    # loop would have done both.

    def _diff_on(self):
        """Is 'Δ Only what differs' switched on?"""
        try:
            return bool(self.default_diff_var.get())
        except Exception:
            return bool(self.settings.get("show_default_diff", True))

    def _default_lineups(self):
        """Where a default comes from. One band (the default), a vote over the
        built-in reference songs, or a vote over his own saved variants."""
        src = self.settings.get("defaults_from") or "band"
        if src == "variants":
            try:
                lus = default_lineups_from_variants(self.variants)
            except Exception:
                lus = []
            if lus:
                return lus
            return DEFAULT_LINEUPS
        if src == "typical":
            return DEFAULT_LINEUPS
        return band_lineup(self._defaults_room())

    def _defaults_room(self):
        """Which room's defaults to compare against.

        Normally the room THIS song is in, so the comparison is like for like:
        a Large song is measured against the Large band, and its Room field is
        grey because Large is what a song that size should be in. The Defaults
        window can pin it to one size instead, to print that set.
        """
        pin = getattr(self, "_defaults_room_pin", None)
        if pin in DEFAULT_BANDS:
            return pin
        try:
            _rows, info = self._stage()
            room = info.get("room")
        except Exception:
            room = None
        return room if room in DEFAULT_BANDS else "Medium"

    def _defaults_for(self, iid):
        try:
            return instrument_defaults(iid, self._stage_perspective(),
                                       self._default_lineups())
        except Exception:
            return {}

    def _marks(self, engine, iid, bits, detail=False):
        """[bool] — True where a field is already what the preset holds."""
        bits = list(bits or [])
        if not bits or not self._diff_on():
            return [False] * len(bits)
        d = self._defaults_for(iid).get(engine)
        if not d:
            return [False] * len(bits)
        return mark_same(bits, d.get("detail" if detail else "bits"))

    def _measure_font(self, font):
        """One tkfont.Font per font tuple, kept — building one per label was
        measurable on a 12-channel song."""
        cache = getattr(self, "_font_cache", None)
        if cache is None:
            cache = self._font_cache = {}
        key = tuple(font)
        f = cache.get(key)
        if f is None:
            try:
                f = tkfont.Font(font=font)
            except Exception:
                f = None
            cache[key] = f
        return f

    def _details_on(self):
        """Is the 'Details' box ticked? Off by default: the lines under a head line
        that hold values a preset sets for you (Crossovers, Low cut, Unmask,
        Side-chain ...) are not drawn."""
        try:
            return bool(self.details_var.get())
        except Exception:
            return bool(self.settings.get("show_details", False))

    def _on_details_toggle(self):
        self.settings["show_details"] = bool(self.details_var.get())
        save_settings(self.settings)
        self._on_filter_change()   # left-hand cards
        self._refresh_summary()    # right-hand panel

    def _head_line(self, parent, engine, iid, bits, bg=C_BG2, fg=C_FG,
                   wrap=700, bold=True, pady=None, detail=False, font=None,
                   accents=None):
        """Draw one head line, field by field, greying what matches the default.

        With Δ off this is a single wrapping Label, byte for byte the line the
        program has always printed — the switch really does only change the
        colours."""
        bits = [b for b in (bits or []) if b]
        if not bits:
            return None
        if detail and not self._details_on():
            return None             # a detail line: only drawn when Details is ticked
        fnt = font or (("Segoe UI", 8, "bold") if bold else FONT_SMALL)
        pack_kw = {"fill": "x"}
        if pady is not None:
            pack_kw["pady"] = pady
        diff = self._diff_on()
        if not diff and not accents:
            lbl = tk.Label(parent, text=HEAD_SEPS[0].join(bits), bg=bg, fg=fg,
                           font=fnt, wraplength=wrap, justify="left", anchor="w")
            lbl.pack(**pack_kw)
            return lbl

        marks = self._marks(engine, iid, bits, detail=detail) if diff else [False] * len(bits)
        meas = self._measure_font(fnt)
        # ONE tk.Text per head line, not one Label per field. Windows allows a
        # process 10,000 USER objects and every Tk widget is one; the old
        # Label-per-field lines (a marker, a Frame per row and a Label per field)
        # were the biggest single consumer, and at the limit Tk stops creating
        # widgets - rows come out blank and the program can crash (measured: 9,122
        # objects right after start-up, 10,000 as soon as a few sections were
        # ticked). The wrapping is still done by hand with the measured widths,
        # so the line never reflows; each field is a colour tag on the one widget.
        #
        # The margin marker: a Δ when this section still has something to dial.
        # It is drawn in the BACKGROUND colour when there is nothing, rather
        # than left out - the width has to stay, or every section that needs
        # him would sit a few pixels to the right of every section that does
        # not, and the panel would look like it had lost its left edge.
        gutter = ((meas.measure("\u0394 ") if meas else 14) if diff else 0)
        budget = max(160, wrap - 24)
        rows, cur, used = [], [], 0
        for i, (bit, same) in enumerate(zip(bits, marks)):
            text = (HEAD_SEPS[0] + bit) if i else bit
            w = (meas.measure(text) if meas else len(text) * 6) + 2
            if used and used + w > budget:
                rows.append(cur)
                cur, used = [], 0
                text = bit
                w = (meas.measure(text) if meas else len(text) * 6) + 2
            cur.append((text, same))
            used += w
        rows.append(cur)

        txt = tk.Text(parent, bg=bg, fg=fg, font=fnt, relief="flat", bd=0,
                      highlightthickness=0, padx=0, pady=0, wrap="none",
                      height=len(rows), width=1, cursor="arrow", takefocus=0,
                      insertwidth=0, spacing1=0, spacing2=0, spacing3=0)
        no_blink(txt)
        txt.pack(**pack_kw)
        txt.tag_configure("mark", foreground=(C_DIFF if not all(marks) else bg))
        txt.tag_configure("same", foreground=C_DEFAULT)
        txt.tag_configure("norm", foreground=fg)
        txt.tag_configure("cont", lmargin1=gutter)
        def put(text, same, cont):
            base = "same" if same else "norm"
            pos = 0
            for s, e, col in accent_spans(text, accents):
                if s > pos:
                    txt.insert("end", text[pos:s], (base,) + cont)
                tag = "acc" + col.lstrip("#")
                txt.tag_configure(tag, foreground=col)     # created last = wins
                txt.insert("end", text[s:e], (tag,) + cont)
                pos = e
            if pos < len(text):
                txt.insert("end", text[pos:], (base,) + cont)

        for r, fields in enumerate(rows):
            if r:
                txt.insert("end", "\n", "cont")
            elif diff:
                txt.insert("end", "\u0394 ", "mark")
            for text, same in fields:
                put(text, same, ("cont",) if (r and diff) else ())
        txt.config(state="disabled")
        return txt

    def _runs_text(self, parent, runs, bg, font, wrap):
        """One wrapping tk.Text from [(text, colour)] runs - a line whose parts each
        have their own colour. Height is worked out from the measured width, so
        the row never reflows on its own."""
        meas = self._measure_font(font)
        total = sum((meas.measure(tx) if meas else len(tx) * 6) for tx, _c in runs)
        lines = max(1, int(-(-total // max(100, wrap - 16))))
        txt = tk.Text(parent, bg=bg, font=font, relief="flat", bd=0,
                      highlightthickness=0, padx=0, pady=0, wrap="word",
                      height=lines, width=1, cursor="arrow", takefocus=0,
                      insertwidth=0)
        no_blink(txt)
        for i, (tx, col) in enumerate(runs):
            tag = "run%d_%s" % (i, col.lstrip("#"))
            txt.tag_configure(tag, foreground=col)
            txt.insert("end", tx, tag)
        txt.config(state="disabled")
        txt.pack(fill="x")
        return txt

    def _accent_text(self, parent, text, fg, bg, font, accents, **pack_kw):
        """One single-line tk.Text with coloured words - used where a head line is
        laid out by hand (the Trackspacer rows)."""
        meas = self._measure_font(font)
        width = max(1, int(meas.measure(text) / max(1, meas.measure("0"))) + 2) if meas else len(text) + 2
        txt = tk.Text(parent, bg=bg, fg=fg, font=font, relief="flat", bd=0,
                      highlightthickness=0, padx=0, pady=0, wrap="none", height=1,
                      width=width, cursor="arrow", takefocus=0, insertwidth=0)
        no_blink(txt)
        txt.tag_configure("base", foreground=fg)
        pos = 0
        for s, e, col in accent_spans(text, accents):
            if s > pos:
                txt.insert("end", text[pos:s], "base")
            tag = "acc" + col.lstrip("#")
            txt.tag_configure(tag, foreground=col)
            txt.insert("end", text[s:e], tag)
            pos = e
        if pos < len(text):
            txt.insert("end", text[pos:], "base")
        txt.config(state="disabled")
        txt.pack(**pack_kw)
        return txt

    def _on_default_diff_change(self):
        """The Δ switch: remember it and redraw both panels. A deliberate
        one-click change, so a full rebuild is the honest way to do it."""
        self.settings["show_default_diff"] = bool(self.default_diff_var.get())
        save_settings(self.settings)
        self._on_filter_change()
        self._refresh_summary()

    def _on_defaults_source_change(self):
        """Which songs the vote runs over. Changing this changes what counts as
        a default, so the cache goes and everything is redrawn."""
        self.settings["defaults_from"] = (self.defaults_src_var.get()
                                          or "band")
        save_settings(self.settings)
        clear_defaults_cache()
        self._on_filter_change()
        self._refresh_summary()

    # ---- 📐 the Defaults window --------------------------------------------

    def _defaults_text(self):
        """The whole defaults list as (style, text) segments — what to put in
        each plug-in preset, and what this song is doing differently."""
        sel = self._checked_ids()
        ids = [i["id"] for i in EQ_DATA if i["id"] in sel] or \
              [i["id"] for i in EQ_DATA]
        lus = self._default_lineups()
        segs = [("h1", "📐  DEFAULTS — what to save in each preset\n\n")]
        segs.append(("body",
                     "One default per instrument: what it is set to when there "
                     "is ONE of it, in the kind of song it usually turns up in. "
                     "Save that in the plug-in's own preset, and the cheat "
                     "sheet only has to tell you what THIS song does "
                     "differently.\n\n"))
        if is_band_lineup(lus):
            room = self._defaults_room()
            band = band_ids(room)
            names = [x["name"] for x in EQ_DATA if x["id"] in band]
            segs.append(("h2", "%s room \u2014 %d places on the stage\n"
                         % (room, stage_units(set(band)))))
            segs.append(("body", "Taken from ONE line-up, the default band for "
                                 "a %s room: %s.\n\n"
                         % (room.lower(), ", ".join(names))))
            segs.append(("body",
                         "Anything not in that list gets its default by "
                         "standing IN the band, one of it: the ride next to "
                         "the band's hi-hat, the percussion next to its kit, "
                         "a cello in front of its guitars. Those are marked "
                         "GUEST below.\n\n"))
            segs.append(("tip",
                         "The room is counted in PLACES ON THE STAGE, not in "
                         "channels: the whole kit is one place however many "
                         "pieces it has, a section or a pad is two, and "
                         "everything else is one each. 1\u20135 places is a Small "
                         "room, 6\u201310 Medium, 11 and up Large.\n\n"))
            segs.append(("tip",
                         "There is one set of defaults per room size. This "
                         "song is in a %s room, so these are the numbers it is "
                         "measured against \u2014 pick another size above to print "
                         "that set instead.\n\n" % self._defaults_room()))
        else:
            segs.append(("body", "Voted over %d reference song%s: %s.\n\n"
                         % (len(lus), "" if len(lus) == 1 else "s",
                            ", ".join(lu.get("name", "?") for lu in lus))))
        if sel:
            segs.append(("tip", "Showing the %d instrument%s ticked in this "
                                "song. Untick everything to list all of them.\n\n"
                         % (len(ids), "" if len(ids) == 1 else "s")))
        try:
            rows, _info = self._stage()
        except Exception:
            rows = {}
        counts = {i: self._count_of(i) for i in sel}
        persp = self._stage_perspective()
        for iid in ids:
            inst = next((x for x in EQ_DATA if x["id"] == iid), None)
            if not inst:
                continue
            dflt = self._defaults_for(iid)
            if not dflt:
                continue
            guest = (is_band_lineup(lus) and iid not in band_ids(self._defaults_room()))
            segs.append(("h2", "\n" + inst["name"]
                         + ("   (GUEST in the band)" if guest else "") + "\n"))
            for eng, label in DEFAULT_ENGINES:
                d = dflt.get(eng)
                if not d:
                    continue
                segs.append(("code", "  " + HEAD_SEPS[0].join(d["bits"]) + "\n"))
                if d.get("detail"):
                    segs.append(("code", "      "
                                 + HEAD_SEPS[0].join(d["detail"]) + "\n"))
                vote = default_vote_note(d)
                if vote:
                    segs.append(("tip", "      (the reference songs did not all "
                                        "agree here — %s)\n" % vote))
                if iid in sel:
                    now = engine_bits(eng, iid, sel, counts, persp,
                                      stage_rows=rows)
                    marks = mark_same(now, d["bits"])
                    off = [b for b, ok in zip(now, marks) if not ok]
                    if off:
                        segs.append(("diff", "      THIS SONG:  "
                                     + HEAD_SEPS[0].join(off) + "\n"))
                    elif not now:
                        segs.append(("diff", "      THIS SONG:  nothing — the "
                                             "section is not printed at all\n"))
        segs.append(("body", "\n\nA row that is grey in the panel is a row you "
                             "have already dialled in. Only the Δ rows need "
                             "you.\n"))
        return segs

    def _show_defaults(self):
        """📐 The defaults list, in a window, with a Copy-all so it can sit on
        the second screen while the presets are made."""
        top = tk.Toplevel(self.root)
        top.title("Defaults — what to save in each preset")
        top.configure(bg=C_BG)
        top.transient(self.root)
        top.geometry("900x680")

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="📐  Defaults — what to save in each preset",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")

        bar = tk.Frame(top, bg=C_BG2, pady=4, padx=10)
        bar.pack(fill="x")
        tk.Label(bar, text="Voted over:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(0, 8))
        for label, value in (("🎸 My default band", "band"),
                             ("🎚 Ten typical songs", "typical"),
                             ("🎵 My own song variants", "variants")):
            tk.Radiobutton(bar, text=label, variable=self.defaults_src_var,
                           value=value, bg=C_BG2, fg=C_FG, selectcolor=C_BG3,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=FONT_SMALL, cursor="hand2",
                           command=lambda t=top: self._redefault(t)).pack(
                               side="left", padx=(0, 12))
        tk.Button(bar, text="📋 Copy all", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG, font=FONT_SMALL,
                  relief="flat", padx=10, pady=2, cursor="hand2",
                  command=self._defaults_copy).pack(side="right")

        bar2 = tk.Frame(top, bg=C_BG2, pady=4, padx=10)
        bar2.pack(fill="x")
        tk.Label(bar2, text="Room:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(0, 8))
        self.defaults_room_var = tk.StringVar(value="song")
        for label, value in (("🎧 This song", "song"), ("Small", "Small"),
                             ("Medium", "Medium"), ("Large", "Large")):
            tk.Radiobutton(bar2, text=label, variable=self.defaults_room_var,
                           value=value, bg=C_BG2, fg=C_FG, selectcolor=C_BG3,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=FONT_SMALL, cursor="hand2",
                           command=lambda t=top: self._repin_room(t)).pack(
                               side="left", padx=(0, 10))

        text_frame = tk.Frame(top, bg=C_BG)
        text_frame.pack(fill="both", expand=True, padx=10, pady=10)
        vsb = tk.Scrollbar(text_frame, bg=C_BG2, troughcolor=C_BG,
                           activebackground=C_ACCENT)
        vsb.pack(side="right", fill="y")
        txt = tk.Text(text_frame, bg=C_BG2, fg=C_FG, font=FONT_NORMAL,
                      relief="flat", bd=0, wrap="word", yscrollcommand=vsb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        vsb.config(command=txt.yview)
        txt.tag_configure("h1",   font=("Segoe UI", 12, "bold"), foreground=C_ACCENT)
        txt.tag_configure("h2",   font=("Segoe UI", 10, "bold"), foreground=C_FG)
        txt.tag_configure("body", font=FONT_NORMAL,              foreground=C_FG_DIM)
        txt.tag_configure("code", font=FONT_MONO,                foreground=C_DEFAULT)
        txt.tag_configure("diff", font=FONT_MONO,                foreground=C_DIFF)
        txt.tag_configure("tip",  font=FONT_SMALL,               foreground=C_CHAR)
        self._defaults_txt = txt
        self._defaults_fill(txt)

        top.focus_force()

        def _close(_e=None):
            self._defaults_room_pin = None
            top.destroy()

        top.protocol("WM_DELETE_WINDOW", _close)
        top.bind("<Escape>", _close)

    def _repin_room(self, top=None):
        """Pin the window to one room size, or follow the song again. It only
        moves what the WINDOW prints \u2014 the panel keeps measuring the song
        against its own room, which is the only comparison that means
        anything while mixing."""
        v = self.defaults_room_var.get()
        self._defaults_room_pin = v if v in DEFAULT_BANDS else None
        try:
            if self._defaults_txt.winfo_exists():
                self._defaults_fill(self._defaults_txt)
        except Exception:
            pass

    def _defaults_fill(self, txt):
        segs = self._defaults_text()
        self._defaults_last = "".join(b for _s, b in segs)
        txt.configure(state="normal")
        txt.delete("1.0", "end")
        for style, body in segs:
            txt.insert("end", body, style)
        txt.configure(state="disabled")

    def _redefault(self, top=None):
        self._on_defaults_source_change()
        try:
            if self._defaults_txt.winfo_exists():
                self._defaults_fill(self._defaults_txt)
        except Exception:
            pass

    def _defaults_copy(self):
        try:
            self.root.clipboard_clear()
            self.root.clipboard_append(getattr(self, "_defaults_last", ""))
        except Exception:
            pass

    def _build_lowcut_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True):
        """A compact '🔻 Low cut (Lowtility)' footnote: high-pass corner + slope.
        It sits first because it's first in the chain — no extra explanation."""
        bits = engine_bits("lowcut", iid)
        if not bits:
            return None
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        # The low cut never depends on the line-up, so once its preset is saved
        # this line is grey for good — which is exactly what it is for.
        self._head_line(frame, "lowcut", iid, bits, bg=bg, fg=LOWCUT_COLOUR,
                        wrap=wrap)
        return self._tighten(frame, False)   # never has anything under it

    # ---- LIVE FOOTNOTES ------------------------------------------------------
    # Some footnotes depend on the WHOLE line-up, not just their own instrument
    # (duck source, "split the lows with the kick", "pair with the kick
    # sidechain"). The left-hand cards are only rebuilt when the band filter
    # changes, so those footnotes would otherwise sit there stale after you tick
    # something. Each one is packed into a holder frame registered here, and
    # _refresh_live_notes() re-fills every holder whenever the selection moves.

    def _fill_tip(self, holder, inst, wrap=700, wheel_fn=None, bg=C_BG2):
        """The 💡 tip line, rewritten when it names an instrument that is not in
        the song (no kick → the bass tip stops talking about side-chaining)."""
        # The tip is general mix advice, never a setting → an extra comment.
        if not self._show_extra():
            return None
        frame = tk.Frame(holder, bg=bg, padx=10, pady=6)
        frame.pack(fill="x", pady=(8, 0))
        text = partner_note("tip", inst["id"], inst["tip"], self._checked_ids())
        self._note_label(frame, "💡  " + text, bg=bg, wrap=wrap, extra=True)
        if wheel_fn:
            self._bind_wheel(frame, wheel_fn)
        return frame

    def _live_note(self, parent, bg, fill):
        """Pack a holder frame and register it. 'fill' takes the holder and
        builds the current contents inside it."""
        holder = tk.Frame(parent, bg=bg)
        holder.pack(fill="x")
        self._duck_holders.append({"holder": holder, "fill": fill})
        fill(holder)
        return holder

    def _prune_live_notes(self):
        """Forget holders whose widgets have been destroyed."""
        out = []
        for rec in getattr(self, "_duck_holders", []):
            try:
                if rec["holder"].winfo_exists():
                    out.append(rec)
            except Exception:
                pass
        self._duck_holders = out

    def _refresh_live_notes(self):
        """Re-fill every live footnote. Dead holders — cards or summary blocks
        that have been destroyed — are dropped from the register as we go."""
        self._pair_sync()              # v3.25: pairs first, the notes read their tiers
        self._sync_room_btn()          # a loaded variant can bring its own room
        live = []
        for rec in getattr(self, "_duck_holders", []):
            h = rec["holder"]
            try:
                if not h.winfo_exists():
                    continue
                for w in h.winfo_children():
                    w.destroy()
                rec["fill"](h)
                live.append(rec)
            except Exception:
                pass
        self._duck_holders = live

    # ---- ✖N MULTIPLES: advice that follows the count ------------------------

    def _live_multi(self, parent, bg, fill, iid=None):
        """Same idea as _live_note, but on its own register so that changing a
        COUNT redraws only the ✖N boxes (the duck/partner notes are untouched,
        which keeps the scroll position steady — no flicker).

        `iid` is which channel the box belongs to, so ONE box can be redrawn
        on its own — see _on_count_change and the four celli that are not in
        the song."""
        holder = tk.Frame(parent, bg=bg)
        holder.pack(fill="x")
        self._multi_holders.append({"holder": holder, "fill": fill, "iid": iid})
        fill(holder)
        return holder

    def _refresh_multi_notes(self, only=None):
        """Re-fill every ✖N box; drop holders whose widgets are gone.

        `only` limits it to one channel's boxes. Everything else on screen is
        left alone — which is the whole point: redrawing widgets that cannot
        have changed is what the flashing WAS."""
        live = []
        for rec in getattr(self, "_multi_holders", []):
            h = rec["holder"]
            try:
                if not h.winfo_exists():
                    continue
                if only is None or rec.get("iid") == only:
                    for w in h.winfo_children():
                        w.destroy()
                    rec["fill"](h)
                live.append(rec)
            except Exception:
                pass
        self._multi_holders = live

    def _persist_counts(self):
        """Write the current counts into the active variant (only for the
        instruments that variant actually contains) and save."""
        v = self._find_variant(self.current_variant)
        if not v:
            return
        try:
            v["counts"] = {i: self._count_raw(i) for i in v.get("fixed", [])}
            self._persist_variants()
        except Exception:
            pass

    def _tick_if_count_changed(self, iid):
        """More or fewer of an instrument that is switched OFF: switch it on.

        His words, 2026-10-12: "Om jag okar/minskar antalet av nagot, och det
        inte ar PA... check-box-pa det." Only a real CHANGE counts - the spin
        box also calls its handler on FocusOut, and tabbing past a number must
        never tick anything. The last number seen per instrument is kept in
        self._count_seen (refreshed whenever a variant is loaded or Reset)."""
        try:
            seen = self.__dict__.setdefault("_count_seen", {})
            now = self._count_raw(iid)
            was = seen.get(iid, 1)
            seen[iid] = now
            if now == was:
                return
            var = self._vfixed_vars.get(iid)
            if var is None or var.get():
                return
            var.set(True)
            self._on_var_toggle()        # card box, group boxes, Update light
        except Exception:
            pass

    def _remember_counts_seen(self):
        """Take the counts as they stand now as 'nothing has changed yet'."""
        try:
            self._count_seen = {i: self._count_raw(i)
                                for i in self._vcount_vars}
        except Exception:
            pass

    def _on_count_change(self, iid, from_summary=False):
        """A count spin box changed — on a card, in Song Variants, or (since
        v2.7) on the Selected-Instruments row itself.
        Deliberately does NOT touch the instrument selection: changing 'how many
        chord guitars' must never re-tick or un-tick anything.

        from_summary=True means the spin box that fired this is one of the
        widgets _refresh_summary() would destroy. Rebuilding the panel from
        under a live Tk event is how you get a FocusOut on a dead widget (which
        fires this handler again) and a scroll position that jumps to the top on
        every click. So that path refreshes only the parts that actually depend
        on the count, in place.

        TWO THINGS DO NOT HAPPEN HERE ANY MORE (2026-09-23):

        * A count on a channel that is NOT in the mix redraws its own ✖N box
          and NOTHING else. stage_plan only lays out what is ticked, and so
          does every other engine here, so four celli you are not using
          cannot change one number on the right — and the whole panel was
          being rebuilt for them. His words: "det borde inte påverka valda
          instruments inställningar".
        * With ⟳ Update holding, a count only lights the button - from the
          left AND (since v3.28) from the right-hand panel as well."""
        self._mark_focus(iid)
        self._tick_if_count_changed(iid)
        # v3.28: nothing moves before Update / Save, wherever the count was changed - the
        # right-hand panel's own boxes included (they used to go in at once and made the
        # panel flicker).
        live = not self._hold_on()
        if live:
            # One entry, not a whole new snapshot: the SELECTION may still
            # be waiting, and committing that here would be this button
            # pressing the other one.
            try:
                self._applied_counts[iid] = self._count_raw(iid)
            except Exception:
                pass
            self._persist_counts()
        self._pending_dirty()
        if iid not in self._mix_ids():
            self._refresh_multi_notes(only=iid)
            return
        if not live:
            return                        # the ⟳ Update button now says so
        self._stage_cache_key = None      # counts feed stage_plan (DEL 02m)
        self._refresh_multi_notes()       # the ✖N boxes
        self._refresh_live_notes()        # Virtual Stage + duck/partner notes
        if not from_summary:
            self._refresh_summary()
        try:
            self._update_conflicts()
        except Exception:
            pass

    def _multi_plan_for(self, iid):
        """The multiples plan for an instrument at its current count, or None."""
        inst = next((x for x in EQ_DATA if x["id"] == iid), None)
        if not inst:
            return None
        n = self._count_of(iid)
        if n < 2:
            return None
        d = DEPTH.get(iid)
        return multiples_plan(iid, n, group=inst.get("group", ""),
                              lowcut=LOWCUT.get(iid),
                              depth_tier=(d[0] if d else None))

    def _fill_multi(self, holder, iid, bg=C_BG2, wrap=700, expanded=True):
        """The ✖N box: what actually changes because there is more than one of
        this instrument. Nothing is drawn at a count of 1."""
        plan = self._multi_plan_for(iid)
        if not plan:
            return None
        n = plan["n"]
        frame = tk.Frame(holder, bg=bg, padx=10, pady=6)
        frame.pack(fill="x", pady=(6, 0))

        head = tk.Frame(frame, bg=bg)
        head.pack(fill="x")
        tk.Label(head, text=f"✖{n}  Multiples", bg=bg, fg=MULTI_COLOUR,
                 font=("Segoe UI", 8, "bold")).pack(side="left")
        tk.Label(head, text=f"   {plan['label']} — {plan['headline']}",
                 bg=bg, fg=C_FG, font=FONT_SMALL,
                 wraplength=max(220, wrap - 120), justify="left",
                 anchor="w").pack(side="left", fill="x", expand=True)

        def line(text, colour=C_FG_DIM, bold=False):
            tk.Label(frame, text=text, bg=bg, fg=colour,
                     font=(("Segoe UI", 8, "bold") if bold else FONT_SMALL),
                     wraplength=wrap, justify="left", anchor="w").pack(fill="x")

        if plan["what"]:
            line("• " + plan["what"])
        line("• Level:  " + plan["gain_line"], "#cdd6e6")
        line("• Pan:    " + plan["pan_line"], "#9fdcff")
        if plan["tone"]:
            line("• Tone:   " + plan["tone"])
        if plan["hp"]:
            line("• Low cut: " + "  ·  ".join(plan["hp"]), LOWCUT_COLOUR)
        if expanded:
            line("• Balance: " + plan["level"])
            line("• Reverb:  " + plan["reverb"], DEPTH_COLOUR)
        line("• Bus:    " + plan["bus"], C_ACCENT)
        if plan["trap"]:
            line("⚠ " + plan["trap"], "#ffcf8f", bold=True)
        if plan["too_many"]:
            line("⚠ " + plan["too_many"], C_CUT, bold=True)
        return frame

    def _build_smarteq_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True,
                                wheel_fn=None):
        """A compact '🎯 smart:EQ group' footnote: the priority tier (Front/Mid/
        Back). The explanatory note shows only when expanded. The note is
        partner-aware (and LIVE): it never tells you to split the low end with a
        kick that is not in the song (see partner_note)."""
        if iid not in SMARTEQ_GROUP:
            return None
        return self._live_note(
            parent, bg,
            lambda h: self._fill_smarteq_footnote(h, iid, bg, wrap, expanded, wheel_fn))

    def _fill_smarteq_footnote(self, holder, iid, bg, wrap, expanded, wheel_fn=None):
        info = smarteq_group_for(iid, self._checked_ids())
        if not info:
            return None
        glyph, colour, label, note = info
        frame = tk.Frame(holder, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        # Only the tier (glyph + FRONT / MID / BACK) is coloured; the rest of
        # the line stays quiet (changed 2026-10-21 - it used to be all green).
        self._head_line(frame, "smarteq", iid,
                        engine_bits("smarteq", iid, self._checked_ids()),
                        bg=bg, fg=C_FG_DIM, wrap=wrap,
                        accents=[(r"[\u25b2\u25a0\u25bc]\s*(?:FRONT|MID|BACK)", tier_colour)])
        body = None
        if expanded:
            # The tier IS the setting and it is already in the head line above;
            # the note only says why that tier and not another one.
            body = self._note_label(frame, note, bg=bg, wrap=wrap, extra=True)
        self._tighten(frame, body is not None)
        if wheel_fn:
            self._bind_wheel(frame, wheel_fn)
        return frame

    def _build_ducking_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True,
                                explain_missing=True, wheel_fn=None):
        """A compact '🦆 Duck under X (Trackspacer)' footnote — LIVE, see
        _live_note()."""
        if iid not in DUCKING:
            return None
        return self._live_note(
            parent, bg,
            lambda h: self._fill_ducking_footnote(h, iid, bg, wrap, expanded,
                                                  explain_missing, wheel_fn))

    def _fill_ducking_footnote(self, holder, iid, bg, wrap, expanded,
                               explain_missing, wheel_fn=None):
        """Put the current duck advice inside a holder frame. Collapsed shows the
        two Trackspacer essentials (side-chain + High Cut/Amount) on ONE line.
        Expanded adds the reason and the Kickstart alternative.
        The 'start gentle' caution is deliberately NOT repeated per duck — it is
        the same sentence every time. It lives once, in the 🔀 Effects duck view,
        in Explain ▸ Ducking and in Help.

        SOURCE CHECK: once this instrument is ticked (= it is in the song), the
        duck only shows if its side-chain SOURCE is in the song too. A bass in a
        song with no kick gets 'no Kick in this song' instead of the old — and
        useless — 'duck the bass under the kick'. Untick everything and the card
        goes back to reference mode, showing what it WOULD duck under."""
        raw = DUCKING.get(iid)
        if not raw:
            return None
        sel = self._checked_ids()
        if iid in sel and not duck_source_present(raw["src"], sel):
            # In the right-hand summary we print NOTHING (no line = nothing to
            # do, the same rule as a dry channel having no reverb line). The
            # left-hand card explains it once, where you browse the instrument.
            if not explain_missing:
                return None
            frame = tk.Frame(holder, bg=bg, padx=10, pady=5)
            frame.pack(fill="x", pady=(6, 0))
            # A duck that has lost its source IS a deviation from the default —
            # the preset still has Trackspacer set up — so it never greys out.
            self._head_line(frame, "duck", iid,
                            engine_bits("duck", iid, sel), bg=bg, fg=C_FG_DIM,
                            wrap=wrap, bold=False)
            self._tighten(frame, False)
            if wheel_fn:
                self._bind_wheel(frame, wheel_fn)
            return frame
        d = raw
        # Three fields — the header, the side-chain and the numbers — and they
        # are laid out by hand rather than by _head_line, because the two
        # essentials belong side by side on their own row. Same comparison, so
        # a duck that is exactly what the preset holds still goes grey.
        bits = engine_bits("duck", iid, sel)
        if len(bits) < 3:
            bits = ["🦆 Duck under the %s  (Trackspacer)" % d["src"],
                    "Side-chain = " + d["src"], d["set"]]
        marks = self._marks("duck", iid, bits)
        show_det = self._details_on()
        # With Details off only the header is drawn, so the Δ marker must only
        # count the header - a hidden field cannot ask to be looked at.
        vis_marks = marks if show_det else marks[:1]
        frame = tk.Frame(holder, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        head_row = tk.Frame(frame, bg=bg)
        head_row.pack(fill="x")
        if self._diff_on():
            tk.Label(head_row, text="Δ ", bg=bg,
                     fg=(C_DIFF if not all(vis_marks) else bg),
                     font=("Segoe UI", 8, "bold"),
                     anchor="w").pack(side="left", anchor="n")
        src_acc = [(_re.escape(d["src"]), DUCK_SRC_COLOURS.get(d["src"], DUCK_SRC_DEFAULT))]
        self._accent_text(head_row, bits[0],
                          (C_DEFAULT if marks[0] else "#ffcf8f"), bg,
                          ("Segoe UI", 8, "bold"), src_acc,
                          side="left", fill="x", expand=True)
        # The two Trackspacer essentials, side by side with a clear gap between
        # them — they are short, and two half-empty lines wasted the space.
        essentials = tk.Frame(frame, bg=bg)
        if show_det:
            essentials.pack(fill="x")
        # 'Side-chain = Lead Vocal' repeats the header, and 'Band 500 Hz-5 kHz ·
        # Amount ...' is a Trackspacer value that stays put from song to song - both
        # are details, drawn only when Details is ticked.
        if show_det:
            self._accent_text(essentials, bits[1],
                              (C_DEFAULT if marks[1] else C_FG_DIM), bg,
                              FONT_SMALL, src_acc, side="left")
            tk.Label(essentials, text=bits[2], bg=bg,
                     fg=(C_DEFAULT if marks[2] else C_FG_DIM),
                     font=FONT_SMALL, wraplength=max(200, wrap - 200), justify="left",
                     anchor="w").pack(side="left", padx=(24, 0))
        if expanded:
            # 'why' explains the numbers on the line above → extra.
            # 'kickstart' is a different plug-in's SETTINGS ("'Classic' curve,
            # 1/4 notes, gentle depth") → essential, it is a thing to dial in.
            self._note_label(frame, d.get("why", ""), bg=bg, wrap=wrap, extra=True)
            if d.get("kickstart"):
                self._note_label(frame, "Kickstart — " + d["kickstart"],
                                 bg=bg, wrap=wrap, extra=False)
        # With Details off the header is all there is (plus the note when expanded).
        self._tighten(frame, show_det or bool(expanded))
        if wheel_fn:
            self._bind_wheel(frame, wheel_fn)
        return frame

    # ---- 🎪 VIRTUAL STAGE -------------------------------------------------

    def _stage(self):
        """The whole-stage plan for the current selection (DEL 02m), cached.

        stage_plan() lays out every channel at once — it runs the balance,
        ladder, collision and depth passes over the whole line-up — so calling
        it once per instrument block would redo all of that for every card on
        screen. The cache key is the selection + the counts + the perspective,
        which is exactly the set of things that can change an answer."""
        sel = frozenset(self._checked_ids())
        counts = tuple(sorted((i, self._count_of(i)) for i in sel))
        persp = self._stage_perspective()
        ov = self._stage_effective_table()
        # The hand placements are part of the answer, so they are part of
        # the key. Leaving them out would hand back yesterday's stage the
        # moment one of them changed.
        ovkey = tuple(sorted(
            (i, o["role"], o["side"], o["opposite"], o.get("sibling", ""))
            if isinstance(o, dict)
            else (i, o, "", "") for i, o in ov.items()))
        # v3.25: so are the tiers the pairs have moved.
        pairkey = (tuple(sorted((i, v[0]) for i, v in SMARTEQ_GROUP.layer.items())),
                   tuple(sorted((i, v[0]) for i, v in DEPTH.layer.items())))
        swam = self._swam_for_engines()
        sec = self._swam_sec_for_engines()
        turns = self._swam_turns_now()
        # v3.36: the pairs (Pair boxes + siblings) have PRIORITY in the SWAM room, so they are
        # part of the key and are handed to swam_apply as 'hold' groups.
        hold = self._swam_hold_groups(sel, ov)
        key = (sel, counts, persp, ovkey, pairkey, tuple(swam), tuple(sec), tuple(sorted(turns)),
               tuple(tuple(g) for g in hold))
        if getattr(self, "_stage_cache_key", None) != key:
            _rows, _info = stage_plan(sel, dict(counts), persp, overrides=ov)
            SWAM_TURNS.clear()
            SWAM_TURNS.update(turns)
            try:
                swam_apply(_rows, _info, swam, sec, hold)      # v3.26: SWAM channels leave Virtual Stage
            except Exception:
                pass
            self._stage_cache = (_rows, _info)
            self._stage_cache_key = key
        return self._stage_cache

    def _swam_hold_groups(self, sel, ov):
        """v3.36: the groups of parts that keep their SWAM spot when the room is crowded: every
        Pair number with 2+ ticked members (lowest pair number first), then siblings set by hand
        that are not inside one of those."""
        try:
            groups = [list(ids) for _n, ids in sorted(
                pair_groups(clean_pairs(self._pairs_for_engines()), set(sel)).items())]
            for a, b in stage_sibling_pairs(ov):
                if a in sel and b in sel and not any({a, b} <= set(g) for g in groups):
                    groups.append([a, b])
            return groups
        except Exception:
            return []

    def _swam_turns_now(self):
        """v3.34: the SWAM parts of THIS song whose copies play one at a time (setting swam_turns,
        kept per song name)."""
        try:
            return set((self.settings.get("swam_turns") or {}).get(self.current_variant or "Song", []))
        except Exception:
            return set()

    def _swam_turns_dialog(self):
        """File > SWAM: which parts with several copies take turns (one player) in THIS song."""
        song = self.current_variant or "Song"
        ids = [i for i in clean_swam(self._swam_for_engines()) if self._count_of(i) >= 2]
        top = tk.Toplevel(self.root)
        top.title("SWAM: copies that take turns")
        top.configure(bg=C_BG)
        top.transient(self.root)
        tk.Label(top, text="Song: %s\n\nA part with 2 or more copies: do the copies play AT THE SAME TIME,\n"
                           "or does one take over from the other (a little overlap at the joins)?\n"
                           "Taking turns = one player: every copy gets the SAME Angle/Distance.\n"
                           "Playing together = each copy gets its own spot, spaced apart." % song,
                 bg=C_BG, fg=C_FG, font=FONT_NORMAL, justify="left").pack(anchor="w", padx=14, pady=(12, 6))
        cur = self._swam_turns_now()
        vars_ = {}
        for i in ids:
            v = tk.BooleanVar(value=i in cur)
            vars_[i] = v
            tk.Checkbutton(top, text="%s (%d copies) take turns" % (_stage_name(i), self._count_of(i)),
                           variable=v, bg=C_BG, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG,
                           activeforeground=C_FG, font=FONT_NORMAL).pack(anchor="w", padx=24, pady=2)
        if not ids:
            tk.Label(top, text="No SWAM part has 2 or more copies in this song.\n(Tick SWAM on the row and "
                               "set its count to 2.)", bg=C_BG, fg=C_CUT, font=FONT_NORMAL,
                     justify="left").pack(anchor="w", padx=14, pady=8)

        def _ok():
            allt = dict(self.settings.get("swam_turns") or {})
            keep = [i for i, v in vars_.items() if v.get()]
            other = [i for i in allt.get(song, []) if i not in vars_]       # parts not shown now
            allt[song] = keep + other
            self.settings["swam_turns"] = allt
            save_settings(self.settings)
            self._stage_cache_key = None
            self._toast("Saved. Press ⟳ Update, then generate the SWAM presets again.")
            top.destroy()
        bar = tk.Frame(top, bg=C_BG)
        bar.pack(fill="x", padx=14, pady=10)
        tk.Button(bar, text="OK", bg=C_BTN, fg=C_BTN_FG, relief="flat", padx=14, pady=3,
                  font=FONT_SMALL, command=_ok).pack(side="right")
        tk.Button(bar, text="Cancel (Esc)", bg=C_BTN, fg=C_BTN_FG, relief="flat", padx=10, pady=3,
                  font=FONT_SMALL, command=top.destroy).pack(side="right", padx=6)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _swam_tune_dialog(self):
        """File > SWAM: Expression and Vibrato depth written into every generated preset."""
        folders = swam_find_folders(self._swam_dir())
        have = []
        for key, path in sorted(folders.items()):
            sd = swam_pick_seed(path, (self.settings.get("swam_seeds") or {}).get(os.path.basename(path), ""))
            if sd:
                e, vb = swam_preset_tune(sd[1])
                have.append("  %-22s Expression %s    Vibrato depth %s"
                            % (os.path.basename(path), "-" if e is None else "%.2f" % e,
                               "-" if vb is None else "%.2f" % vb))
        top = tk.Toplevel(self.root)
        top.title("SWAM: Expression and Vibrato")
        top.configure(bg=C_BG)
        top.transient(self.root)
        tk.Label(top, text="Written into EVERY generated SWAM preset, so you do not pull them by hand.\n"
                           "Expression: 1.0 = all the way up (the volume it adds). Vibrato depth: in the\n"
                           "same units as the preset (lower = less vibrato). Leave a box EMPTY = keep what\n"
                           "the sound you build from already holds.",
                 bg=C_BG, fg=C_FG, font=FONT_NORMAL, justify="left").pack(anchor="w", padx=14, pady=(12, 6))
        fr = tk.Frame(top, bg=C_BG)
        fr.pack(anchor="w", padx=14, pady=4)
        ents = {}
        for r, (lab, key, dflt) in enumerate((("Expression (0-1)", "swam_expression", 1.0),
                                              ("Vibrato depth", "swam_vibrato", None))):
            tk.Label(fr, text=lab, bg=C_BG, fg=C_FG, font=FONT_NORMAL, width=18, anchor="w").grid(row=r, column=0)
            e = tk.Entry(fr, width=10, bg=C_BG2, fg=C_FG, relief="flat", font=FONT_NORMAL,
                         insertbackground=C_FG)
            no_blink(e)
            cur = self.settings.get(key, dflt)
            e.insert(0, "" if cur in (None, "") else str(cur))
            e.grid(row=r, column=1, padx=6, pady=3)
            ents[key] = e
        tk.Label(top, text="The sounds you build from now hold:\n" + ("\n".join(have) or "  (none found)"),
                 bg=C_BG, fg=C_FG_DIM, font=FONT_MONO, justify="left").pack(anchor="w", padx=14, pady=(6, 4))

        def _num(s):
            s = s.strip().replace(",", ".")
            return None if s == "" else float(s)

        def _ok():
            try:
                for k, e in ents.items():
                    self.settings[k] = _num(e.get())
            except ValueError:
                from tkinter import messagebox
                messagebox.showinfo(APP_NAME, "Type a number (or leave the box empty).", parent=top)
                return
            if self.settings.get("swam_expression") is not None:
                self.settings["swam_expression"] = max(0.0, min(1.0, self.settings["swam_expression"]))
            save_settings(self.settings)
            self._toast("Saved. The next Generate writes these.")
            top.destroy()
        bar = tk.Frame(top, bg=C_BG)
        bar.pack(fill="x", padx=14, pady=10)
        tk.Button(bar, text="OK", bg=C_BTN, fg=C_BTN_FG, relief="flat", padx=14, pady=3,
                  font=FONT_SMALL, command=_ok).pack(side="right")
        tk.Button(bar, text="Cancel (Esc)", bg=C_BTN, fg=C_BTN_FG, relief="flat", padx=10, pady=3,
                  font=FONT_SMALL, command=top.destroy).pack(side="right", padx=6)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _swam_for_engines(self):
        """The SWAM ticks the right panel works from: the ones it was last built with while
        ⟳ Update is holding something back, the live ones otherwise (same rule as the pairs)."""
        asw = getattr(self, "_applied_swam", None)
        if self._hold_on() and asw is not None and self._pending_bits():
            return list(asw)
        return list(self._swam)

    def _swam_sec_for_engines(self):
        """The Section ticks, with the same hold rule as the SWAM ticks."""
        asw = getattr(self, "_applied_swam", None)
        if self._hold_on() and asw is not None and self._pending_bits():
            return clean_swam_sec(getattr(self, "_applied_swam_sec", None) or [], asw)
        return clean_swam_sec(self._swam_sec, self._swam)

    def _on_swam_sec_toggle(self, iid):
        """The Sect tick of a row (v3.29): run this part in the SWAM Section plug-in.
        Ticking it also makes the part SWAM (and switches it on); nothing moves until Update / Save."""
        var = self._vsec_vars.get(iid)
        if var is None:
            return
        cur = set(self._swam_sec)
        if var.get():
            cur.add(iid)
            sv = self._vswam_vars.get(iid)
            if sv is not None and not sv.get():
                sv.set(True)
                self._on_swam_toggle(iid)         # also switches the instrument ON
        else:
            cur.discard(iid)
        self._swam_sec = clean_swam_sec(cur)
        self._mark_focus(iid)
        if self._hold_on():
            self._pending_dirty()
            return
        v = self._find_variant(self.current_variant)
        if v:
            v["swam_sec"] = list(self._swam_sec)
            self._persist_variants()
        self._stage_cache_key = None
        self._refresh_live_notes()
        self._refresh_summary()
        for attr, fill in (("_stage_map_txt", getattr(self, "_stage_map_fill", None)),):
            w = getattr(self, attr, None)
            try:
                if w is not None and fill and w.winfo_exists():
                    fill(w)
            except Exception:
                pass

    def _on_swam_toggle(self, iid):
        """The SWAM tick of a row (v3.28).

        * Ticking SWAM switches the instrument ON, like raising its count does ("it is
          obviously in the mix if I say it is SWAM"). Un-ticking leaves it as it is.
        * Nothing on the right moves until ⟳ Update / Save: with the hold on this only
          lights the Update button (mark 🎻). The variant file is written on Save."""
        var = self._vswam_vars.get(iid)
        if var is None:
            return
        cur = set(self._swam)
        if var.get():
            cur.add(iid)
        else:
            cur.discard(iid)
        self._swam = clean_swam(cur)
        if not var.get() and iid in self._swam_sec:      # no SWAM, no Section
            self._swam_sec = [i for i in self._swam_sec if i != iid]
            sv2 = self._vsec_vars.get(iid)
            if sv2 is not None:
                sv2.set(False)
        self._mark_focus(iid)
        fv = self._vfixed_vars.get(iid)
        if var.get() and fv is not None and not fv.get():
            fv.set(True)
            self._on_var_toggle(iid)          # card box, group boxes, Update light
        if self._hold_on():
            self._pending_dirty()
            return
        v = self._find_variant(self.current_variant)
        if v:
            v["swam"] = list(self._swam)
            v["swam_sec"] = list(self._swam_sec)
            self._persist_variants()
        self._stage_cache_key = None
        self._refresh_live_notes()
        self._refresh_summary()
        for attr, fill in (("_stage_map_txt", getattr(self, "_stage_map_fill", None)),):
            w = getattr(self, attr, None)
            try:
                if w is not None and fill and w.winfo_exists():
                    fill(w)
            except Exception:
                pass

    def _load_swam_ui(self, raw, raw_sec=None):
        """Fill the SWAM + Sect ticks from a variant's saved lists."""
        self._swam = clean_swam(raw)
        self._swam_sec = clean_swam_sec(raw_sec, self._swam)
        for iid, var in self._vswam_vars.items():
            var.set(iid in self._swam)
        for iid, var in self._vsec_vars.items():
            var.set(iid in self._swam_sec)
        self._stage_cache_key = None

    def _stage_manual_table(self):
        """The ✋ hand placements for the current variant, sanitised."""
        try:
            return stage_overrides_clean(self._stage_manual)
        except Exception:
            return {}

    # ---- ⛓ PAIRS + PRIORITY (DEL 04c) --------------------------------------

    def _pair_sync(self):
        """Put the pair layer in step with the line-up that is ticked NOW.

        Cheap (a handful of dict entries), so it is simply called at every
        entry point that is about to read a tier: the stage, the panel ids,
        the live notes. The base tables are never edited - see _PairedDict."""
        try:
            ticked = self._checked_ids()
            counts = {i: self._count_of(i) for i in ticked}
            fx = pair_effects(self._pairs_for_engines(), ticked, counts)
        except Exception:
            fx = {"smarteq": {}, "depth": {}, "stage": {}}
        SMARTEQ_GROUP.layer = fx["smarteq"]
        DEPTH.layer = fx["depth"]
        self._pair_stage = fx["stage"]

    def _pairs_for_engines(self):
        """The pairs the right panel works from: the ones it was last built with
        while ⟳ Update is holding, the live ones otherwise (same rule as the
        line-up and the counts)."""
        ap = getattr(self, "_applied_pairs", None)
        if self._hold_on() and ap is not None and self._pending_bits():
            return ap
        return self._pairs

    def _stage_effective_table(self):
        """Hand placements on top of what the pairs derive."""
        manual = self._stage_manual_table()
        self._pair_sync()
        try:
            return stage_merge_pairs(manual, self._pair_stage)
        except Exception:
            return manual

    @staticmethod
    def _spin_int(var, lo, hi, default):
        try:
            return max(lo, min(hi, int(var.get())))
        except (AttributeError, TypeError, ValueError):
            return default

    def _on_pair_change(self, iid):
        """A Pair or Prio box was changed (arrows, typing + Enter, or FocusOut)."""
        pv, qv = self._vpair_vars.get(iid), self._vprio_vars.get(iid)
        if pv is None or qv is None:
            return
        pair = self._spin_int(pv, 0, PAIR_MAX, 0)
        prio = self._spin_int(qv, 1, PRIO_MAX, 1)
        # Write the cleaned numbers back, so a typed 'x' or '40' cannot stay.
        if pv.get() != str(pair):
            pv.set(str(pair))
        if qv.get() != str(prio):
            qv.set(str(prio))
        was = self._pairs.get(iid)
        new = [pair, prio] if pair else None
        self._paint_pair_box(iid)
        if (was or None) == new:
            return                            # FocusOut on an untouched box
        if new:
            self._pairs[iid] = new
        else:
            self._pairs.pop(iid, None)
        self._pairs = clean_pairs(self._pairs)
        self._mark_focus(iid)
        if self._hold_on():
            self._pending_dirty()              # lights the Update button; written on Save / Update
            return
        v = self._find_variant(self.current_variant)
        if v:
            v["pairs"] = clean_pairs(self._pairs)
            v["swam"] = list(self._swam)
            v["swam_sec"] = list(self._swam_sec)
            self._persist_variants()
        self._stage_cache_key = None
        self._pair_sync()
        self._refresh_live_notes()
        self._refresh_summary()

    def _paint_pair_box(self, iid):
        """A paired row shows its numbers in the accent colour."""
        sp = self._vpair_spins.get(iid)
        if not sp:
            return
        on = self._spin_int(self._vpair_vars.get(iid), 0, PAIR_MAX, 0) > 0
        for w in sp:
            try:
                w.config(fg=(C_ACCENT if on else C_FG_DIM))
            except Exception:
                pass

    def _load_pairs_ui(self, pairs):
        """Fill the Pair/Prio boxes from a variant's saved pairs."""
        self._pairs = clean_pairs(pairs)
        for iid, pv in self._vpair_vars.items():
            p = self._pairs.get(iid)
            pv.set(str(p[0]) if p else "0")
            qv = self._vprio_vars.get(iid)
            if qv is not None:
                qv.set(str(p[1]) if p else "1")
            self._paint_pair_box(iid)
        self._pair_sync()

    def _stage_perspective(self):
        """'audience' (hi-hat on the RIGHT) or 'drummer' (mirrored)."""
        try:
            v = self.stage_persp_var.get()
        except Exception:
            v = self.settings.get("stage_perspective", "audience")
        return "drummer" if v == "drummer" else "audience"

    def _on_stage_persp_change(self):
        """Flip the whole stage map between the audience's and the drummer's
        point of view. Everything that is not the kit is unaffected."""
        self.settings["stage_perspective"] = self._stage_perspective()
        save_settings(self.settings)
        self._stage_cache_key = None
        self._refresh_live_notes()
        self._refresh_summary()

    def _build_vstage_footnote(self, parent, iid, bg=C_BG2, wrap=700,
                               expanded=True, head=True):
        """A compact '🎪 Virtual Stage' footnote — Position · Distance · Room.

        LIVE, and more so than any other footnote in this program: every number
        depends on what ELSE is ticked, so it is registered with _live_note and
        re-filled the moment the line-up changes. That is also exactly why its
        presets are named by their numbers — see DEL 02m and DEL 02t."""
        return self._live_note(
            parent, bg,
            lambda h: self._fill_vstage_footnote(h, iid, bg, wrap, expanded,
                                                 head))

    def _build_swam_footnote(self, parent, iid, bg=C_BG2, wrap=700):
        """v3.29: ONLY the SWAM numbers of a part (Angle, Distance, room). These are settings he types
        into SWAM, so they print whatever the filters of the right panel say - exactly like the hand
        placements do - even when the 'Virtual Stage' block itself is filtered out."""
        return self._live_note(
            parent, bg,
            lambda h: self._fill_vstage_footnote(h, iid, bg, wrap, False, head=False, swam_only=True))

    def _fill_vstage_footnote(self, holder, iid, bg, wrap, expanded,
                              head=True, swam_only=False):
        try:
            rows, _info = self._stage()
        except Exception:
            return None
        row = rows.get(iid)
        if not row:
            return None
        if swam_only and not row.get("swam"):
            return None
        frame = tk.Frame(holder, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        # The one engine where the Δ really earns its keep: Position and
        # Distance move with the line-up, Room does not, so most of the time
        # exactly one of these three fields is left in colour.
        # head=False on the four low-end channels: the permanent row above
        # already prints this line. Everything BELOW it stays - the ✖N bass
        # option in particular, which is the one place this plug-in goes
        # from "no" to "here is how".
        if head:
            self._head_line(frame, "vstage", iid, head_bits(vstage_head(row)),
                            bg=bg,
                            fg=(C_FG_DIM if row.get("skip") else VSTAGE_COLOUR),
                            wrap=wrap,
                            accents=(None if row.get("skip") else [
                                (r"(?<=Virtual Stage: )\S+", STAGE_POS_COLOUR),
                                (r"(?<=Distance )\S+", STAGE_DIST_COLOUR),
                                (r"(?<=Room )\S+", STAGE_ROOM_COLOUR)]))
        # ---- v3.26: SWAM - the placement lives in SWAM's own room -------------
        sw = row.get("swam")
        if sw:
            tk.Label(frame, text=SWAM_DIVIDER, bg=bg, fg=SWAM_COLOUR,
                     font=("Segoe UI", 8, "bold"), anchor="w").pack(fill="x", pady=(3, 0))
            tk.Label(frame, text="\U0001f3bb SWAM room (Ambiente):  " + swam_text(sw),
                     bg=bg, fg=SWAM_COLOUR, font=("Segoe UI", 8, "bold"),
                     wraplength=wrap, justify="left", anchor="w").pack(fill="x")
            _room = ((_info or {}).get("swam") or {}).get("room")
            if _room:
                self._note_label(frame, "Room (shared by every SWAM instance; Room Type never changes): "
                                 "Room Sizes %s  \u00b7  Absorption %s  \u00b7  Mic: %s"
                                 % (_room["size"], _room["material"], _room["mic"]),
                                 bg=bg, fg="#cdd6e6", wrap=wrap, extra=False)
            for _mv in sw.get("moved") or []:
                self._note_label(frame, "\u21b3 " + _mv, bg=bg, fg=SWAM_COLOUR, wrap=wrap,
                                 extra=False)
        if swam_only:
            return self._tighten(frame, True)
        # ---- the ✖N bass option (DEL 02m) — SETTINGS, so never hidden ------
        # This is the one place the plug-in goes from "no" to "here is how",
        # so it prints in full whatever the comment settings say. Only the
        # "only if…" condition is a why, and that follows the extra rule.
        opt = row.get("option")
        if opt:
            tk.Label(frame, text="↳ " + opt["head"], bg=bg, fg=VSTAGE_COLOUR,
                     font=("Segoe UI", 8, "bold"), wraplength=wrap,
                     justify="left", anchor="w").pack(fill="x", pady=(3, 0))
            for ln in opt["lines"]:
                self._note_label(frame, "• " + ln, bg=bg, fg="#cdd6e6",
                                 wrap=wrap, extra=False)
            self._note_label(frame, "⚠ " + opt["condition"], bg=bg,
                             fg="#ffcf8f", wrap=wrap, extra=True)
        # ---- v3.30: backing vocals as doubles / harmonies / own parts ------
        # SETTINGS, so they print whatever the comment settings say; only the
        # why-line follows the extra-comments switch.
        alts = row.get("alts")
        if alts:
            tk.Label(frame, text="↳ " + alts["head"], bg=bg, fg=VSTAGE_COLOUR,
                     font=("Segoe UI", 8, "bold"), wraplength=wrap,
                     justify="left", anchor="w").pack(fill="x", pady=(3, 0))
            for ln in alts["lines"]:
                self._note_label(frame, "• " + ln, bg=bg, fg="#cdd6e6",
                                 wrap=wrap, extra=False)
            self._note_label(frame, alts["why"], bg=bg, wrap=wrap, extra=True)

        because = row.get("because") or []
        # ✋ A hand placement is a DECISION, not a reason for one, so its
        # lines print whatever the why-line setting says and whether or not
        # the block is expanded. The sheet has to be able to say "this
        # number is yours" - that is the price of letting you set it at all.
        hand = [b for b in because if b.startswith(STAGE_HAND)]
        rest = [b for b in because if not b.startswith(STAGE_HAND)]
        body = None
        for b in hand:
            self._note_label(frame, "↳ " + b, bg=bg, fg=C_DIFF, wrap=wrap,
                             extra=False, pady=(2, 0))
            body = True
        if expanded:
            body = self._note_label(frame, row.get("why", ""), bg=bg, wrap=wrap,
                                    extra=True) or body
            for b in rest:
                body = self._note_label(frame, "↳ " + b, bg=bg, fg=VSTAGE_COLOUR,
                                        wrap=wrap, extra=True, pady=(2, 0)) or body
        elif rest:
            # Collapsed: still show ONE reason, because the reason IS the point
            # — the number moved because of something else in the song. It is
            # still a why, so it goes when extra comments go; the head line
            # above keeps every number you actually dial in.
            body = self._note_label(frame, "↳ " + rest[-1], bg=bg, wrap=wrap,
                                    extra=True) or body
        return self._tighten(frame, bool(body) or bool(opt))

    def _build_depth_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True,
                              sel=None):
        """A compact '🌫 Depth' footnote (smart:reverb numbers). The plain-language
        note shows only when expanded.
        DRY channels (kick, basses) print NOTHING — 'No reverb (keep DRY)' on
        every bass was a line that only ever cost space. No reverb line = no
        reverb. Same rule everywhere in the program."""
        info = depth_for_sel(iid, sel)
        if not info:
            return None
        tier, spec, note, alone = info
        if tier == "dry":
            return None
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        self._head_line(frame, "depth", iid, engine_bits("depth", iid, sel),
                        bg=bg, fg=DEPTH_COLOUR, wrap=wrap,
                        accents=[(r"(?<=smart:reverb: )\w+", tier_colour)])
        body = self._note_label(frame, note, bg=bg, wrap=wrap,
                                extra=True) if expanded else None
        if alone:
            # One line that says WHY the numbers are bigger than the lead usually
            # gets. It explains a deviation, so it is always shown.
            body = self._note_label(frame, "↳ " + LEAD_ALONE_NOTE, bg=bg,
                                    fg=VSTAGE_COLOUR, wrap=wrap, extra=False) or body
        return self._tighten(frame, body is not None)

    def _build_comp_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True,
                             wheel_fn=None):
        """A compact '🗜 Compressor' footnote: tier + starting numbers. The
        plain-language note shows only when expanded. Sits after the EQ, before
        the time effects — the same place the compressor sits in the chain.
        Partner-aware and LIVE: no 'pair with the kick sidechain' in a song
        without a kick (see partner_note / _live_note)."""
        if iid not in COMPRESSION:
            return None
        return self._live_note(
            parent, bg,
            lambda h: self._fill_comp_footnote(h, iid, bg, wrap, expanded, wheel_fn))

    def _fill_comp_footnote(self, holder, iid, bg, wrap, expanded, wheel_fn=None):
        info = compression_for(iid, self._checked_ids())
        if not info:
            return None
        tier, spec, note = info
        frame = tk.Frame(holder, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        self._head_line(frame, "comp", iid,
                        engine_bits("comp", iid, self._checked_ids()),
                        bg=bg, fg=COMP_COLOUR, wrap=wrap)
        body = self._note_label(frame, note, bg=bg, wrap=wrap,
                                extra=True) if expanded else None
        self._tighten(frame, body is not None)
        if wheel_fn:
            self._bind_wheel(frame, wheel_fn)
        return frame

    def _fill_lowend_row(self, holder, iid, bg, wrap, expanded=False):
        """Draw the permanent low-end row. Never raises - a missing stage
        plan just means the Virtual Stage field says "see below"."""
        row = None
        try:
            stage_row = None
            if iid not in VSTAGE_SKIP:
                try:
                    rows, _i = self._stage()
                    stage_row = rows.get(iid)
                except Exception:
                    stage_row = None
            row = lowend_row(iid, self._count_of(iid), stage_row)
        except Exception:
            row = None
        if not row:
            return None
        frame = tk.Frame(holder, bg=bg, padx=10, pady=4)
        frame.pack(fill="x", pady=(4, 0))
        self._runs_text(frame, row["runs"], bg, ("Segoe UI", 8, "bold"), wrap)
        if row.get("extra"):
            tk.Label(frame, text="\u21b3 " + row["extra"], bg=bg, fg=C_FG_DIM,
                     font=FONT_SMALL, wraplength=wrap, justify="left",
                     anchor="w").pack(fill="x", pady=(2, 0))
        # The SubMass footnote used to hold this note and no longer prints
        # at all on these channels, so the row carries it. Same rule as
        # before: it is a why, so it follows the extra-comment setting and
        # only shows on an expanded block.
        if expanded and row.get("note"):
            self._note_label(frame, row["note"], bg=bg, wrap=wrap, extra=True)
        return frame

    def _build_submass_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True):
        """A compact '🌑 SubMass' footnote: Amp/Freq/Center starting numbers.
        Only shown for sounds that actually benefit from a tracked sub layer
        (kick, basses) — most instruments have no entry and this returns None."""
        info = submass_for(iid)
        if not info:
            return None
        amp, freq_hz, center_pct, note = info
        tier = submass_tier(amp)
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        self._head_line(frame, "submass", iid, engine_bits("submass", iid),
                        bg=bg, fg=SUBMASS_COLOUR, wrap=wrap)
        body = self._note_label(frame, note, bg=bg, wrap=wrap,
                                extra=True) if expanded else None
        return self._tighten(frame, body is not None)

    def _build_knock_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True):
        """The '\U0001f94a KNOCK' footnote: the preset for this instrument in the chosen KNOCK version
        (Options > Knock version), its numbers, and the alternatives. None when there is no entry."""
        presets = knock_for(iid)
        if not presets:
            return None
        ver = self._knock_version()
        p = presets[0]
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        tk.Label(frame, text="\U0001f94a KNOCK %s:  %s  \u00b7  %s" % (ver, p["cat"], p["name"]), bg=bg,
                 fg=KNOCK_COLOUR, font=("Segoe UI", 8, "bold"), wraplength=wrap, justify="left",
                 anchor="w").pack(fill="x")
        tk.Label(frame, text="  \u00b7  ".join(knock_bits(p, ver)), bg=bg, fg=C_FG_DIM, font=FONT_SMALL,
                 wraplength=wrap, justify="left", anchor="w").pack(fill="x")
        if len(presets) > 1:
            tk.Label(frame, text="Also: " + ", ".join(q["name"] for q in presets[1:]), bg=bg, fg=C_FG_DIM,
                     font=FONT_SMALL, wraplength=wrap, justify="left", anchor="w").pack(fill="x")
        body = self._note_label(frame, p["role"], bg=bg, wrap=wrap, extra=True) if expanded else None
        return self._tighten(frame, body is not None)

    # ---- smart:EQ group OVERVIEW (Front/Mid/Back + sub-bus plan) -------------
    # Instruments that share a family AND a tier can sit on ONE sub-bus = ONE of
    # smart:EQ's 10 group slots (e.g. both guitars; kick+snare). Basses are kept
    # separate (their low-end placement differs). This plan keeps you under 10.
    _SMARTEQ_SHORT_FAM = {
        "Vocals": "Vocals", "Drums & Percussion": "Drums", "Bass": "Bass",
        "Guitar": "Guitars", "Keys & Winds": "Keys/Winds", "Strings": "Strings",
        # v3.24: Brass got its own TAB, but it stays on the same smart:EQ bus family
        # as before, so no bus plan changes because of the new tab.
        "Brass": "Keys/Winds",
        # v3.27: Keys & Winds became three tabs; they stay ONE smart:EQ bus family.
        "Winds": "Keys/Winds", "Keys": "Keys/Winds", "Other": "Keys/Winds",
    }
    _SMARTEQ_FORCE_SOLO = {"bass_root", "bass_loop", "double_bass", "double_bass_section"}
    SMARTEQ_MAX_SLOTS = 10

    def _smarteq_base_buses(self, ids):
        """The raw family-per-tier bus list, before any merging.
        Each entry: {bus, tier, fam, members, solo, was}. 'was' = the bus names
        this entry came from (just itself, until something merges it)."""
        id2inst = {x["id"]: x for x in EQ_DATA}
        buses, order = {}, []
        for iid in ids:
            g = SMARTEQ_GROUP.get(iid)
            inst = id2inst.get(iid)
            if not g or not inst:
                continue
            tier = g[0]
            if iid in self._SMARTEQ_FORCE_SOLO:
                bus, solo, fam = inst["name"], True, "Bass"   # each bass = its own bus
            else:
                fam = self._SMARTEQ_SHORT_FAM.get(inst["group"], inst["group"])
                bus, solo = f"{fam} · {tier.upper()}", False
            if bus not in buses:
                buses[bus] = {"bus": bus, "tier": tier, "fam": fam, "solo": solo,
                              "members": [], "was": [bus], "merge": None}
                order.append(bus)
            buses[bus]["members"].append(inst["name"])
        return [buses[b] for b in order]

    def _smarteq_merge_candidates(self, buses):
        """Every merge from SMARTEQ_MERGES that would swallow >= 2 of these buses,
        best first. Returns [(spec, [bus dicts])].
        Solo buses (the basses) are skipped by every merge EXCEPT the one that
        explicitly targets the Bass family — that merge exists precisely to undo
        the solo rule when you would otherwise not fit."""
        out = []
        for spec in SMARTEQ_MERGES:
            _mid, tier, fams, _name, _newfam, _why = spec
            takes_solo = ("Bass" in fams)
            hit = [b for b in buses
                   if (takes_solo or not b["solo"]) and b["fam"] in fams
                   and (tier is None or b["tier"] == tier)]
            if len(hit) >= 2:
                out.append((spec, hit))
        return out

    @staticmethod
    def _smarteq_apply_merge(buses, spec, hit):
        """Fold 'hit' into one bus, keeping the list in its original order."""
        mid, _tier, _fams, _name, newfam, _why = spec
        merged = {
            "bus": merge_bus_name(spec),
            "tier": min((b["tier"] for b in hit), key=lambda t: TIER_RANK.get(t, 9)),
            "fam": newfam,
            "solo": False,
            "members": [m for b in hit for m in b["members"]],
            "was": [w for b in hit for w in b["was"]],
            "merge": mid,
        }
        first = min(buses.index(b) for b in hit)
        out = [b for b in buses if b not in hit]
        out.insert(first, merged)
        return out

    def _smarteq_busplan(self, ids, auto_merge=True):
        """Group instrument ids into suggested smart:EQ sub-buses, merging
        automatically until the plan fits smart:EQ's 10 group slots.

        Returns (plan, slot_count, merges) where
          plan   = [{bus, tier, fam, members, solo, was, merge}, …]
          merges = [{id, name, why, colour, buses, applied}, …]  — every merge the
                   program can see, applied ones first, each with its own colour so
                   the UI can paint the buses that belong together.
        """
        buses = self._smarteq_base_buses(ids)
        merges, applied_ids = [], set()

        # Apply the cheapest merges, top of the list first, until it fits.
        guard = 0
        while auto_merge and len(buses) > self.SMARTEQ_MAX_SLOTS and guard < 12:
            guard += 1
            cands = self._smarteq_merge_candidates(buses)
            cands = [(s, h) for s, h in cands if s[0] not in applied_ids]
            if not cands:
                break
            spec, hit = cands[0]
            merges.append({"id": spec[0], "name": merge_bus_name(spec), "why": spec[5],
                           "buses": [b["bus"] for b in hit], "applied": True})
            applied_ids.add(spec[0])
            buses = self._smarteq_apply_merge(buses, spec, hit)

        # Whatever is still on the table = optional, shown but not done for you.
        for spec, hit in self._smarteq_merge_candidates(buses):
            if spec[0] in applied_ids:
                continue
            merges.append({"id": spec[0], "name": merge_bus_name(spec), "why": spec[5],
                           "buses": [b["bus"] for b in hit], "applied": False})

        for i, m in enumerate(merges):
            m["colour"] = SMARTEQ_MERGE_COLOURS[i % len(SMARTEQ_MERGE_COLOURS)]

        # Which colour each bus should wear (merged into, or could merge into).
        colour_of = {}
        for m in merges:
            if m["applied"]:
                continue
            for b in m["buses"]:
                colour_of.setdefault(b, m["colour"])
        for b in buses:
            if b["merge"]:
                b["colour"] = next((m["colour"] for m in merges
                                    if m["id"] == b["merge"]), None)
            else:
                b["colour"] = colour_of.get(b["bus"])

        return buses, len(buses), merges

    def _show_smarteq_groups(self):
        """Popup: selected instruments laid out Front / Mid / Back, plus the
        suggested sub-bus plan and the 10-slot smart:EQ budget."""
        checked = self._panel_ids()
        used_all = not checked
        ids = checked or [x["id"] for x in EQ_DATA]

        plan, slots, merges = self._smarteq_busplan(ids)
        base_slots = len(self._smarteq_base_buses(ids))
        n_inst = len([i for i in ids if i in SMARTEQ_GROUP])

        top = tk.Toplevel(self.root)
        top.title("smart:EQ Group Placement")
        top.configure(bg=C_BG)
        top.geometry("780x600")
        top.resizable(True, True)
        top.transient(self.root)

        # Header
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🎯  smart:EQ Group Placement",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        # Slot budget line
        fits = slots <= self.SMARTEQ_MAX_SLOTS
        info = tk.Frame(top, bg=C_BG, pady=6, padx=14)
        info.pack(fill="x")
        src = "ALL instruments" if used_all else f"{n_inst} selected instruments"
        was_merged = [m for m in merges if m["applied"]]
        headline = f"{src}  →  {slots} sub-bus slot(s)"
        if was_merged:
            headline += f"   (was {base_slots} — merged down for you)"
        tk.Label(info, text=headline,
                 bg=C_BG, fg=C_FG, font=("Segoe UI", 10, "bold")).pack(side="left")
        tk.Label(info, text=f"   smart:EQ budget: {slots} / {self.SMARTEQ_MAX_SLOTS}"
                            + ("  ✓ fits" if fits else "  ⚠ still over limit"),
                 bg=C_BG, fg=(C_BOOST if fits else C_CUT),
                 font=("Segoe UI", 10, "bold")).pack(side="left")

        # Scrollable body
        body = tk.Frame(top, bg=C_BG)
        body.pack(fill="both", expand=True)
        canvas = tk.Canvas(body, bg=C_BG, bd=0, highlightthickness=0)
        vsb = tk.Scrollbar(body, orient="vertical", command=canvas.yview,
                           bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canvas.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        inner = tk.Frame(canvas, bg=C_BG)
        canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<MouseWheel>",
                    lambda e: canvas.yview_scroll(-1 if e.delta > 0 else 1, "units"))

        # Three tier columns
        cols = tk.Frame(inner, bg=C_BG, padx=10, pady=8)
        cols.pack(fill="both", expand=True)
        tiers = [("front", "▲ FRONT", C_BOOST, "wins masking · highest priority"),
                 ("mid",   "■ MID",   C_ACCENT, "supporting layer"),
                 ("back",  "▼ BACK",  C_NEUTRAL, "yields · carved for room")]
        for ci, (tier, label, colour, sub) in enumerate(tiers):
            col = tk.Frame(cols, bg=C_BG2, padx=8, pady=8)
            col.grid(row=0, column=ci, sticky="nsew", padx=4)
            cols.grid_columnconfigure(ci, weight=1, uniform="tier")
            tk.Label(col, text=label, bg=C_BG2, fg=colour,
                     font=("Segoe UI", 11, "bold")).pack(anchor="w")
            tk.Label(col, text=sub, bg=C_BG2, fg=C_FG_DIM,
                     font=FONT_SMALL).pack(anchor="w", pady=(0, 6))
            tk.Frame(col, bg=C_SEP, height=1).pack(fill="x", pady=(0, 6))
            tier_buses = [p for p in plan if p["tier"] == tier]
            if not tier_buses:
                tk.Label(col, text="—", bg=C_BG2, fg=C_FG_DIM,
                         font=FONT_SMALL).pack(anchor="w")
            for b in tier_buses:
                colour, solo, members = b.get("colour"), b["solo"], b["members"]
                # A coloured strip down the left edge = "this bus belongs to a
                # merge". Same colour on two cards = merge those two.
                shell = tk.Frame(col, bg=(colour or C_CARD))
                shell.pack(fill="x", pady=3)
                card = tk.Frame(shell, bg=C_CARD, padx=6, pady=4)
                card.pack(fill="x", padx=(4 if colour else 0, 0))
                tag = "" if solo else f"  ({len(members)})"
                tk.Label(card, text="🚌 " + b["bus"] + tag,
                         bg=C_CARD, fg=C_FG, font=("Segoe UI", 8, "bold"),
                         wraplength=210, justify="left", anchor="w").pack(fill="x")
                if b["merge"]:
                    tk.Label(card, text="◆ MERGED: " + " + ".join(b["was"]),
                             bg=C_CARD, fg=colour or C_ACCENT, font=("Segoe UI", 7, "bold"),
                             wraplength=210, justify="left", anchor="w").pack(fill="x")
                elif colour:
                    tk.Label(card, text="◆ could merge (see below)",
                             bg=C_CARD, fg=colour, font=("Segoe UI", 7, "bold"),
                             wraplength=210, justify="left", anchor="w").pack(fill="x")
                if solo:
                    tk.Label(card, text="   own bus — never merged",
                             bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                             wraplength=210, justify="left", anchor="w").pack(fill="x")
                else:
                    for nm in members:
                        tk.Label(card, text="   • " + nm, bg=C_CARD, fg=C_FG_DIM,
                                 font=FONT_SMALL, wraplength=210, justify="left",
                                 anchor="w").pack(fill="x")

        # ---- Merges: what was done for you, and what is still on the table ----
        if merges:
            mbox = tk.Frame(inner, bg=C_BG2, padx=14, pady=8)
            mbox.pack(fill="x", padx=10, pady=(4, 0))
            tk.Label(mbox, text="🎨 Merges — same colour = belongs on one bus",
                     bg=C_BG2, fg=C_ACCENT, font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(fill="x")
            for m in merges:
                row = tk.Frame(mbox, bg=C_BG2)
                row.pack(fill="x", pady=(6, 0))
                tk.Frame(row, bg=m["colour"], width=6).pack(side="left", fill="y")
                txt = tk.Frame(row, bg=C_BG2, padx=8)
                txt.pack(side="left", fill="x", expand=True)
                state = ("✔ DONE — the program already merged these"
                         if m["applied"] else "○ OPTIONAL — merge these if you want a slot back")
                tk.Label(txt, text=f"{' + '.join(m['buses'])}   →   “{m['name']}”",
                         bg=C_BG2, fg=m["colour"], font=("Segoe UI", 9, "bold"),
                         wraplength=680, justify="left", anchor="w").pack(fill="x")
                tk.Label(txt, text=state, bg=C_BG2,
                         fg=(C_BOOST if m["applied"] else C_FG_DIM),
                         font=("Segoe UI", 8, "bold"), anchor="w").pack(fill="x")
                tk.Label(txt, text=m["why"], bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
                         wraplength=680, justify="left", anchor="w").pack(fill="x")
            tk.Label(mbox, text="In Cubase: make one group channel with the merged name, route "
                                "every listed bus (or its channels) into it, and put ONE smart:EQ "
                                "on it. That is one group slot instead of several.",
                     bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=700,
                     justify="left", anchor="w").pack(fill="x", pady=(8, 0))

        # Footer: the rule + over-limit advice
        foot = tk.Frame(inner, bg=C_BG, padx=14, pady=8)
        foot.pack(fill="x")
        tk.Label(foot, text="How the sub-buses are chosen:", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        tk.Label(foot, text="• Same family + same tier → one sub-bus = one smart:EQ slot "
                            "(e.g. both guitars together; kick + snare together).\n"
                            "• Each bass stays on its OWN bus — their low-end placement differs.\n"
                            "• Over 10 slots, the cheapest merges above are applied automatically "
                            "(cheapest = the one you lose least by).\n"
                            "• Put each sub-bus into the smart:EQ group and rank them Front → Back.",
                 bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL, justify="left", anchor="w").pack(fill="x")
        if not fits:
            tk.Label(foot, text=f"⚠ Still {slots} buses > {self.SMARTEQ_MAX_SLOTS} slots after "
                                "every merge the program knows. Drop a channel from the song, or "
                                "leave the least masked bus out of the smart:EQ group entirely — "
                                "a bus with no smart:EQ is not a crime.",
                     bg=C_BG, fg=C_CUT, font=("Segoe UI", 8, "bold"),
                     wraplength=720, justify="left", anchor="w").pack(fill="x", pady=(6, 0))
        tk.Button(foot, text="🗺  Open the full Roadmap (routing tree)",
                  bg="#2d5a3a", fg=C_BTN_FG,      # change colour here (green-ish)
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=4, cursor="hand2",
                  command=self._show_roadmap).pack(anchor="w", pady=(10, 0))

        # Mouse-wheel over the whole content (not just the bare canvas).
        self._bind_wheel(inner, lambda e: canvas.yview_scroll(-1 if e.delta > 0 else 1, "units"))

        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    # ---- 🗺 ROADMAP: the whole routing tree, channel → bus → master -----------

    def _roadmap_counts(self):
        """{id: how many of this instrument} from the Song Variants spinboxes."""
        out = {}
        for iid in self.check_vars:
            try:
                out[iid] = self._count_of(iid)
            except Exception:
                out[iid] = 1
        return out

    def _show_roadmap(self):
        """Popup: the full bus roadmap — which channel feeds which bus, which bus
        feeds which, all the way to the master, plus a numbered build order and
        the smart:EQ slot budget. This is the 'so THAT is how it hangs together'
        view: the Channel Plan tells you what to put on a channel, the Roadmap
        tells you where that channel goes."""
        checked = self._panel_ids()
        used_all = not checked
        ids = checked or [x["id"] for x in EQ_DATA]
        counts = self._roadmap_counts()
        nodes, roots = build_roadmap(ids, counts)
        plan, slots, merges = self._smarteq_busplan(ids)

        top = tk.Toplevel(self.root)
        top.title("Bus Roadmap")
        top.configure(bg=C_BG)
        top.geometry("980x760")
        top.resizable(True, True)
        top.transient(self.root)

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🗺  Bus Roadmap — what feeds what",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        src = "ALL instruments" if used_all else f"{len(ids)} selected channel(s)"
        n_buses = len([b for b in nodes if b != ROADMAP_MASTER])
        info = tk.Frame(top, bg=C_BG, pady=6, padx=14)
        info.pack(fill="x")
        tk.Label(info, text=f"{src}  →  {n_buses} bus(es)  →  master",
                 bg=C_BG, fg=C_FG, font=("Segoe UI", 10, "bold")).pack(side="left")
        tk.Label(info, text=f"   smart:EQ: {slots} / {self.SMARTEQ_MAX_SLOTS} group slots",
                 bg=C_BG, fg=(C_BOOST if slots <= self.SMARTEQ_MAX_SLOTS else C_CUT),
                 font=("Segoe UI", 10, "bold")).pack(side="left")

        body = tk.Frame(top, bg=C_BG)
        body.pack(fill="both", expand=True)
        canvas = tk.Canvas(body, bg=C_BG, bd=0, highlightthickness=0)
        vsb = tk.Scrollbar(body, orient="vertical", command=canvas.yview,
                           bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canvas.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        inner = tk.Frame(canvas, bg=C_BG)
        canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

        wrap = tk.Frame(inner, bg=C_BG, padx=12, pady=8)
        wrap.pack(fill="both", expand=True)

        BUS_COLOUR = "#9fe0a0"
        tk.Label(wrap, text="THE TREE — read it bottom-up: channels feed sub-buses, "
                            "sub-buses feed section buses, section buses feed the master.",
                 bg=C_BG, fg=C_ACCENT, font=("Segoe UI", 10, "bold"),
                 anchor="w").pack(fill="x")

        def draw(bus, depth):
            n = nodes[bus]
            pad = 18 * depth
            box = tk.Frame(wrap, bg=C_CARD, padx=8, pady=5)
            box.pack(fill="x", padx=(pad, 0), pady=(6, 0))
            head = tk.Frame(box, bg=C_CARD)
            head.pack(fill="x")
            tk.Label(head, text="🚌 " + bus, bg=C_CARD, fg=BUS_COLOUR,
                     font=("Segoe UI", 10, "bold")).pack(side="left")
            tk.Label(head, text=f"   {n['sources']} channel(s) under it",
                     bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left")
            # A bus is exactly what carries ONE smart:EQ — flag the ones that do.
            if any(bus == b["bus"] or bus in b["was"] for b in plan):
                tk.Label(head, text="   🎯 smart:EQ slot", bg=C_CARD, fg=C_BOOST,
                         font=("Segoe UI", 8, "bold")).pack(side="left")
            why = BUS_WHY.get(bus)
            if why:
                tk.Label(box, text=why, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                         wraplength=820, justify="left", anchor="w").pack(fill="x")
            for _iid, nm, cnt in n["members"]:
                tk.Label(box, text=f"     ├─ {nm}" + (f"  ×{cnt}" if cnt > 1 else ""),
                         bg=C_CARD, fg=C_FG, font=FONT_SMALL,
                         anchor="w").pack(fill="x")
            for ch in n["children"]:
                tk.Label(box, text=f"     └▶ {ch}   (bus)", bg=C_CARD, fg=BUS_COLOUR,
                         font=("Segoe UI", 8, "bold"), anchor="w").pack(fill="x")
            for ch in n["children"]:
                draw(ch, depth + 1)

        for r in roots:
            draw(r, 0)

        # Channels the master gets directly (nothing to group them with).
        direct = nodes[ROADMAP_MASTER]["members"]
        if direct:
            box = tk.Frame(wrap, bg=C_CARD, padx=8, pady=5)
            box.pack(fill="x", pady=(8, 0))
            tk.Label(box, text="🎚 Straight to the master — no bus earned",
                     bg=C_CARD, fg=C_FG_DIM, font=("Segoe UI", 9, "bold"),
                     anchor="w").pack(fill="x")
            tk.Label(box, text="   " + ", ".join(nm for _i, nm, _c in direct),
                     bg=C_CARD, fg=C_FG, font=FONT_SMALL, wraplength=820,
                     justify="left", anchor="w").pack(fill="x")
            tk.Label(box, text=f"A bus needs at least {BUS_MIN_SOURCES} channels under it to be "
                               "worth making. One lonely tom is just a tom.",
                     bg=C_CARD, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=820,
                     justify="left", anchor="w").pack(fill="x")

        # ---- Build order: do it in this order and nothing dangles ----
        steps = tk.Frame(wrap, bg=C_BG2, padx=12, pady=8)
        steps.pack(fill="x", pady=(12, 0))
        tk.Label(steps, text="🔨 Build order in Cubase", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(fill="x")
        seq, seen = [], set()

        def collect(bus):
            for ch in nodes[bus]["children"]:
                collect(ch)
            if bus != ROADMAP_MASTER and bus not in seen:
                seen.add(bus)
                seq.append(bus)
        collect(ROADMAP_MASTER)
        for i, bus in enumerate(seq, 1):
            n = nodes[bus]
            feeds = ", ".join([nm for _i, nm, _c in n["members"]] + list(n["children"]))
            tk.Label(steps, text=f"{i}.  Create group channel “{bus}”  →  output to "
                                 f"“{n['parent']}”\n      Route into it: {feeds}",
                     bg=C_BG2, fg=C_FG, font=FONT_SMALL, wraplength=880,
                     justify="left", anchor="w").pack(fill="x", pady=(4, 0))
        tk.Label(steps, text=BUS_DO, bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
                 wraplength=880, justify="left", anchor="w").pack(fill="x", pady=(10, 0))

        # ---- The merges, again, because this is where you act on them ----
        if merges:
            mb = tk.Frame(wrap, bg=C_BG2, padx=12, pady=8)
            mb.pack(fill="x", pady=(10, 0))
            tk.Label(mb, text="🎨 smart:EQ merges (same colour = one bus)",
                     bg=C_BG2, fg=C_ACCENT, font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(fill="x")
            for m in merges:
                tk.Label(mb, text=("  ◆ done: " if m["applied"] else "  ◇ optional: ")
                               + " + ".join(m["buses"]) + f"  →  “{m['name']}”",
                         bg=C_BG2, fg=m["colour"], font=("Segoe UI", 9, "bold"),
                         wraplength=880, justify="left", anchor="w").pack(fill="x", pady=(4, 0))

        # ---- Why bother at all ----
        note = tk.Frame(wrap, bg=C_BG, pady=8)
        note.pack(fill="x")
        tk.Label(note, text="Why buses are worth the trouble:", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        tk.Label(note,
                 text="• ONE fader per section. Drums too loud? Pull Drums: All — not eight faders.\n"
                      "• ONE plug-in instead of many. If every tom gets the same treatment, put the "
                      "tom plug-ins on Drums: Toms and take them off the tom channels. Less CPU, one "
                      "place to tweak, and they stay identical by construction.\n"
                      "• ONE smart:EQ group slot per bus. That is the whole reason the 10-slot limit "
                      "is survivable: 30 channels can be 8 buses.\n"
                      "• ONE reverb send per section, if the section shares a depth (see 🌫 Reverb Groups).\n"
                      "• Do the low cut on the CHANNEL, the glue comp and smart:EQ on the BUS. Never "
                      "high-pass twice.",
                 bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL, wraplength=880,
                 justify="left", anchor="w").pack(fill="x")

        self._bind_wheel(inner, lambda e: canvas.yview_scroll(-1 if e.delta > 0 else 1, "units"))
        canvas.bind("<MouseWheel>",
                    lambda e: canvas.yview_scroll(-1 if e.delta > 0 else 1, "units"))
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    # ---- smart:reverb group OVERVIEW (the EFFICIENT model: one bus per depth) -
    # Fewest instances wins: instruments that share a DEPTH share ONE reverb bus
    # (= one instance = one Distance/character). So you need only 2–3 reverb buses
    # total (Near/Mid/Far), not one per track — far under the 7-channel group cap.
    # Route each track to its depth bus (e.g. rhythm gtr→Near bus, chord gtr→Mid
    # bus — NOT a reverb on each channel). Kick/bass stay DRY. The 7-limit only
    # bites if you instead put reverb on many individual channels and group them.
    SMARTREVERB_MAX_SLOTS = 7
    _SMARTREVERB_BUSNAME = {"front": "Front (Room)", "near": "Near (Room)",
                            "mid": "Mid (Room↔Hall)", "far": "Far (Hall)"}

    # Bus order = how the room sits from the listener outwards, with the dry
    # channels (kick, bass) last because they never reach a reverb at all.
    _REVERB_BUS_ORDER = ("front", "near", "mid", "far", "dry")

    # smart:EQ tier → (glyph, colour) for the per-row marker the Channel Plan
    # prints when it is NOT split into FRONT/MID/BACK boxes (⇅ pick order).
    # Same three shapes and the same three colours as the box headings, so the
    # two orders read as the same plan seen two ways.
    _TIER_GLYPH = {"front": ("▲", C_BOOST),
                   "mid":   ("■", C_ACCENT),
                   "back":  ("▼", C_NEUTRAL)}

    def _reverb_bus_label(self, iid):
        """Name of the smart:reverb bus this channel SHARES with the others in
        its depth tier — the heading used in the 📋 Instruments view."""
        d = DEPTH.get(iid)
        if not d:
            return "No depth set"
        tier = d[0]
        if tier == "dry":
            return "DRY — no reverb send"
        return self._SMARTREVERB_BUSNAME.get(tier, tier.title())

    def _instruments_by_bus(self, ids):
        """`ids` re-ordered so channels that land on the SAME reverb bus are
        adjacent. Inside a bus the EQ_DATA order is kept, so nothing else moves."""
        pos = {x["id"]: i for i, x in enumerate(EQ_DATA)}

        def key(iid):
            tier = (DEPTH.get(iid) or ("",))[0]
            try:
                rank = self._REVERB_BUS_ORDER.index(tier)
            except ValueError:
                rank = len(self._REVERB_BUS_ORDER)      # unknown tier → last
            return (rank, pos.get(iid, 10 ** 6))

        return sorted(ids, key=key)

    def _smartreverb_groupplan(self, ids):
        """Group reverb-using instruments into ONE bus per depth tier, pulling the
        Distance/Size numbers from DEPTH_SPEC. Returns (buses, dry_names). Each bus
        = {tier, name, char, distance, size, members:[names], count}."""
        id2inst = {x["id"]: x for x in EQ_DATA}
        dry = []
        bucket = {"front": [], "near": [], "mid": [], "far": []}
        for iid in ids:
            d = DEPTH.get(iid)
            inst = id2inst.get(iid)
            if not d or not inst:
                continue
            tier = d[0]
            if tier == "dry":
                dry.append(inst["name"])
            else:
                bucket[tier].append(inst["name"])
        buses = []
        for tier in ("front", "near", "mid", "far"):
            if not bucket[tier]:
                continue
            spec = DEPTH_SPEC[tier]
            buses.append({"tier": tier, "name": self._SMARTREVERB_BUSNAME[tier],
                          "char": spec["char"], "distance": spec["distance"],
                          "size": spec["size"], "width": spec["width"],
                          "members": bucket[tier], "count": len(bucket[tier])})
        return buses, dry

    def _show_smartreverb_groups(self):
        """Popup: the most efficient smart:reverb plan — one bus per depth tier,
        which tracks route to each, and the starting Distance/character."""
        checked = self._panel_ids()
        used_all = not checked
        ids = checked or [x["id"] for x in EQ_DATA]
        buses, dry = self._smartreverb_groupplan(ids)
        n_rev = sum(b["count"] for b in buses)

        top = tk.Toplevel(self.root)
        top.title("smart:reverb Group Placement")
        top.configure(bg=C_BG)
        top.geometry("780x600")
        top.resizable(True, True)
        top.transient(self.root)

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🌫  smart:reverb Group Placement",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        info = tk.Frame(top, bg=C_BG, pady=6, padx=14)
        info.pack(fill="x")
        src = "ALL instruments" if used_all else "selected instruments"
        tk.Label(info, text=f"{n_rev} reverb track(s) from {src}  →  only {len(buses)} reverb bus(es) "
                            f"(≤ {self.SMARTREVERB_MAX_SLOTS} group cap is no issue)",
                 bg=C_BG, fg=C_BOOST, font=("Segoe UI", 10, "bold")).pack(side="left")

        body = tk.Frame(top, bg=C_BG)
        body.pack(fill="both", expand=True)
        canvas = tk.Canvas(body, bg=C_BG, bd=0, highlightthickness=0)
        vsb = tk.Scrollbar(body, orient="vertical", command=canvas.yview,
                           bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canvas.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        inner = tk.Frame(canvas, bg=C_BG)
        canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

        wrap = tk.Frame(inner, bg=C_BG, padx=12, pady=8)
        wrap.pack(fill="both", expand=True)
        if not buses:
            tk.Label(wrap, text="No reverb instruments selected (all dry / none ticked).",
                     bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL).pack(anchor="w")
        for b in buses:
            card = tk.Frame(wrap, bg=C_BG2, padx=10, pady=8)
            card.pack(fill="x", pady=4)
            tk.Label(card, text=f"🌫 {b['name']} bus   ·   Distance ~{b['distance']}   ·   "
                                f"Size ~{b['size']}   ·   Width ~{b['width']}   ·   {b['count']} track(s)",
                     bg=C_BG2, fg=DEPTH_COLOUR, font=("Segoe UI", 11, "bold")).pack(anchor="w")
            tk.Label(card, text=f"One smart:reverb instance — puck toward {b['char']} "
                                f"(stay on the Room↔Hall axis, not Spring/Plate). All tracks below send here.",
                     bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=720, justify="left").pack(anchor="w", pady=(0, 6))
            tk.Frame(card, bg=C_SEP, height=1).pack(fill="x", pady=(0, 6))
            for nm in b["members"]:
                tk.Label(card, text="   • " + nm, bg=C_BG2, fg=C_FG,
                         font=FONT_SMALL, anchor="w").pack(fill="x")

        # DRY channels are deliberately NOT listed. A channel with no reverb bus
        # simply does not appear here — that is the information.

        foot = tk.Frame(wrap, bg=C_BG, pady=8)
        foot.pack(fill="x")
        tk.Label(foot, text="Reading the numbers:", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(fill="x")
        tk.Label(foot, text="• DISTANCE is the front/back knob: LOW ≈ near / up front, HIGH ≈ far back. "
                            "So FAR = far back = high Distance (~78). Near ~25, Mid ~50.\n"
                            "• All tracks on one bus SHARE its Distance/Size/Width — that's intended. The depth "
                            "contrast lives BETWEEN the Near/Mid/Far buses, not within one, so they don't need to "
                            "differ by a few. (Want a subtle 3-D spread within a tier like 23/25/27? That needs a "
                            "separate reverb instance per channel — more instances; only if you specifically want it.)\n"
                            "• SIZE = room size (smart:reverb default ≈40): smaller for Near (~30), bigger for Far (~65). "
                            "If unsure, leaving Size at 40 is fine.\n"
                            "• WIDTH = stereo spread of the reverb (default ≈80): narrower (~60–70) for centred sources "
                            "you want focused (lead vocal, snare); wider (~90–100) for stereo beds (pads, strings, "
                            "overheads). The per-bus number above is a sensible average.\n"
                            "• CHARACTER (the puck): it's a BLEND, not a switch — LEAN toward a corner, you don't "
                            "have to drag fully into it (the corner = 100% of that type, usually too much). Start in "
                            "the centre and move ~⅓–½ toward the target: Near→toward Room, Far→toward Hall, Mid "
                            "between them. The exact spot is whatever sounds good to you. Spring/Plate are vintage "
                            "effect colours, NOT depth.\n"
                            "\nWhy this is efficient:\n"
                            "• Same depth → ONE reverb bus (one instance). 2–3 buses cover the whole mix — fewest "
                            "instances, cohesive space, no 7-channel worry.\n"
                            "• Route each track to its depth bus. Different depths can't share (Rhythm Gtr=Near, "
                            "Chord Gtr=Mid → different buses, not a reverb per channel). Same depth shares (Hi-Hat + Ride).\n"
                            "• Want only TWO buses? Fold Mid into Near (a 'Close' bus, Distance ~35) and keep Far.\n"
                            "• Kick & bass stay DRY. Leads: add PRE-DELAY ~60–120 ms so they stay up front.",
                 bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL, justify="left",
                 wraplength=720, anchor="w").pack(fill="x")

        # Mouse-wheel over the whole content AND the bare canvas margins.
        _rev_wheel = lambda e: canvas.yview_scroll(-1 if e.delta > 0 else 1, "units")
        canvas.bind("<MouseWheel>", _rev_wheel)
        self._bind_wheel(inner, _rev_wheel)

        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    @staticmethod
    def _db_str_range(band):
        """Format the dB cell for the Range engine (lo→hi for TRY bands)."""
        btype = band["type"]
        db    = band["db"]
        if btype == "char":
            lo = band.get("db_lo")
            hi = band.get("db_hi")
            if lo is not None and hi is not None:
                lo_s = f"+{lo}" if lo > 0 else str(lo)
                hi_s = f"+{hi}" if hi > 0 else str(hi)
                return f"{lo_s}→{hi_s}"
            return f"±{abs(db)}" if db != 0 else "±?"
        return f"+{db}" if db > 0 else str(db) if db != 0 else "—"

    # ---- 🦻 Hearing marks on a band row ------------------------------------

    def _hearing_on(self):
        """True once a profile has been filled in (see DEL 02k)."""
        return hearing_active(getattr(self, "hearing", {}))

    def _hearing_cell(self, parent, band, bg=C_CARD):
        """The ✔ / ◐ / ⛔ column for one band. Draws an empty spacer when there
        is no profile, so every table keeps the same column layout."""
        if not self._hearing_on():
            return
        hz = _parse_hz_midpoint(band.get("hz", ""))
        mark = hearing_mark(hz, self.hearing)
        if not mark:
            glyph, colour, tip = "✔", C_BOOST, "You hear this range well — judge it by ear."
        else:
            glyph, colour, tip = mark
        lbl = tk.Label(parent, text=glyph, bg=bg, fg=colour,
                       font=("Segoe UI", 9), width=2, anchor="w")
        lbl.pack(side="left")
        self._attach_tooltip(lbl, tip)

    def _hearing_band_note(self, parent, band, bg=C_CARD, wrap=700):
        """The extra line under a band when the profile changes what to do with
        it: a capped gain, or a 'TRY' band the program has decided for you."""
        if not self._hearing_on():
            return
        hz = _parse_hz_midpoint(band.get("hz", ""))
        st = hearing_state_for_hz(hz, self.hearing)
        if st in ("", "ok"):
            return
        msgs = []
        decided, sentence = hearing_decide(band, self.hearing)
        if sentence:
            msgs.append(sentence)
        else:
            capped, why = hearing_cap_db(hz, band.get("db"), self.hearing)
            if why:
                sign = "+" if capped > 0 else ""
                msgs.append(f"Use {sign}{capped} dB — {why}.")
        for m in msgs:
            tk.Label(parent, text="      🦻 " + m, bg=bg, fg=HEARING_COLOUR,
                     font=("Segoe UI", 8), wraplength=wrap, justify="left",
                     anchor="w").pack(fill="x")

    def _build_card_bands_range(self, inner, visible_bands):
        """Original engine: frequency RANGE + generic filter name + dB."""
        hdr2 = tk.Frame(inner, bg=C_CARD)
        hdr2.pack(fill="x")
        if self._hearing_on():
            tk.Label(hdr2, text="🦻", bg=C_CARD, fg=HEARING_COLOUR, font=FONT_SMALL,
                     width=2, anchor="w").pack(side="left")
        tk.Label(hdr2, text="Frequency",   bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=12, anchor="w").pack(side="left")
        tk.Label(hdr2, text="Zone",        bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=14, anchor="w").pack(side="left")
        tk.Label(hdr2, text="Filter",      bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=14, anchor="w").pack(side="left")
        tk.Label(hdr2, text="Type",        bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=5,  anchor="w").pack(side="left")
        tk.Label(hdr2, text="dB",          bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=9,  anchor="w").pack(side="left")
        tk.Label(hdr2, text="What it does",bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,            anchor="w").pack(side="left", fill="x", expand=True)

        for band in visible_bands:
            brow = tk.Frame(inner, bg=C_CARD)
            brow.pack(fill="x", pady=1)

            btype  = band["type"]
            tcol   = TYPE_COLOR.get(btype, C_NEUTRAL)
            tlbl   = TYPE_LABEL.get(btype, "—")
            db_str = self._db_str_range(band)

            self._hearing_cell(brow, band, bg=C_CARD)
            tk.Label(brow, text=band["hz"],    bg=C_CARD, fg=C_FG,     font=FONT_MONO,  width=12, anchor="w").pack(side="left")
            tk.Label(brow, text=band["note"],  bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=14, anchor="w").pack(side="left")
            tk.Label(brow, text=band["filter"],bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=14, anchor="w").pack(side="left")
            tk.Label(brow, text=tlbl, bg=C_CARD, fg=tcol,
                     font=("Segoe UI", 8, "bold"), width=5, anchor="w").pack(side="left")
            tk.Label(brow, text=db_str, bg=C_CARD, fg=tcol,
                     font=("Consolas", 9, "bold"), width=9, anchor="w").pack(side="left")
            tk.Label(brow, text=band["label"], bg=C_CARD, fg=C_FG_DIM,
                     font=FONT_SMALL, anchor="w").pack(side="left", fill="x", expand=True)
            self._hearing_band_note(inner, band, bg=C_CARD, wrap=700)

    def _build_card_bands_kirchhoff(self, inner, visible_bands):
        """Kirchhoff engine: exact Shape · Freq · Gain · Q · Slope per band."""
        hdr2 = tk.Frame(inner, bg=C_CARD)
        hdr2.pack(fill="x")
        if self._hearing_on():
            tk.Label(hdr2, text="🦻", bg=C_CARD, fg=HEARING_COLOUR, font=FONT_SMALL,
                     width=2, anchor="w").pack(side="left")
        tk.Label(hdr2, text="Shape",       bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=11, anchor="w").pack(side="left")
        tk.Label(hdr2, text="Freq",        bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=8,  anchor="w").pack(side="left")
        tk.Label(hdr2, text="Gain",        bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=9,  anchor="w").pack(side="left")
        tk.Label(hdr2, text="Q",           bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=5,  anchor="w").pack(side="left")
        tk.Label(hdr2, text="Slope",       bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=10, anchor="w").pack(side="left")
        tk.Label(hdr2, text="Zone",        bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, width=12, anchor="w").pack(side="left")
        tk.Label(hdr2, text="What it does / how to shape it",
                 bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, anchor="w").pack(side="left", fill="x", expand=True)

        for band in visible_bands:
            k     = kirchhoff_band(band)
            btype = band["type"]
            tcol  = TYPE_COLOR.get(btype, C_NEUTRAL)

            brow = tk.Frame(inner, bg=C_CARD)
            brow.pack(fill="x", pady=1)

            self._hearing_cell(brow, band, bg=C_CARD)
            tk.Label(brow, text=k["ktype"], bg=C_CARD, fg=C_ACCENT,
                     font=("Segoe UI", 8, "bold"), width=11, anchor="w").pack(side="left")
            tk.Label(brow, text=k["freq"],  bg=C_CARD, fg=C_FG,
                     font=FONT_MONO, width=8, anchor="w").pack(side="left")
            tk.Label(brow, text=k["gain"],  bg=C_CARD, fg=tcol,
                     font=("Consolas", 9, "bold"), width=9, anchor="w").pack(side="left")
            tk.Label(brow, text=k["q"],     bg=C_CARD, fg=C_FG_DIM,
                     font=FONT_MONO, width=5, anchor="w").pack(side="left")
            tk.Label(brow, text=k["slope"], bg=C_CARD, fg=C_FG_DIM,
                     font=FONT_SMALL, width=10, anchor="w").pack(side="left")
            tk.Label(brow, text=band["note"], bg=C_CARD, fg=C_FG_DIM,
                     font=FONT_SMALL, width=12, anchor="w").pack(side="left")
            tk.Label(brow, text=band["label"], bg=C_CARD, fg=C_FG_DIM,
                     font=FONT_SMALL, anchor="w").pack(side="left", fill="x", expand=True)
            self._hearing_band_note(inner, band, bg=C_CARD, wrap=700)

    def _toggle_check(self, var, iid):
        var.set(not var.get())
        self._on_check(iid)

    def _on_check(self, iid):
        """A tick on an instrument CARD.

        The card box and the picker box ask the same question - "is this in
        the mix" - so they are kept in step. They were not, before: a card
        tick never reached the variant, and was quietly thrown away the next
        time that variant was loaded."""
        self._mark_focus(iid)
        pv = self._vfixed_vars.get(iid)
        if pv is not None:
            try:
                pv.set(bool(self.check_vars[iid].get()))
            except Exception:
                pass
        self._sync_group_all_boxes()
        self._sync_var_group_boxes()
        if self._hold_on():
            self._pending_dirty()
            self._update_conflicts()
            self._save_current_settings()
            return
        self._commit_left()

    def _checked_ids(self):
        """The instruments ticked on the left — i.e. 'what is in this song'.
        Used to gate advice that only makes sense when a partner instrument is
        actually present (see ducking_for).

        While the ⟳ Update button is lit this hands back the line-up the
        RIGHT panel was last built from, NOT the one the left side is
        currently ticking. Every engine here asks this one question, so
        answering it with the committed line-up holds the whole panel still
        without freezing a single widget."""
        try:
            if self._pending_bits() and self._applied_sel is not None:
                return set(self._applied_sel)
            return {iid for iid, v in self.check_vars.items() if v.get()}
        except Exception:
            return set()

    def _panel_ids(self):
        """The line-up the right panel works from, in picker order."""
        self._pair_sync()               # v3.25: the pairs' tiers, before anyone reads them
        live = self._checked_ids()
        return [iid for iid in self.check_vars if iid in live]

    def _mix_ids(self):
        """Everything that is in the mix now OR is waiting to be."""
        out = set(self._checked_ids())
        try:
            out |= {i for i, v in self._vfixed_vars.items() if v.get()}
        except Exception:
            pass
        return out

    # ---- ⟳ UPDATE: what the right panel is working from -------------------

    def _hold_on(self):
        """True when the left side waits for ⟳ Update."""
        try:
            return bool(self.hold_left_var.get())
        except Exception:
            return True

    def _compute_pending_bits(self):
        """What the left side has that the right panel has not taken in.

        A list of (mark, instrument id): "+" added, "-" removed, "#" a
        different count. COMPARED rather than flagged - a flag is a thing
        somebody has to remember to clear, and the day it is forgotten the
        panel lies about being current."""
        if not self._hold_on():
            return []
        applied = self._applied_sel
        if applied is None:
            return []
        want = {i for i, v in self._vfixed_vars.items() if v.get()}
        out = [("+", i) for i in sorted(want - applied)]
        out += [("-", i) for i in sorted(applied - want)]
        counts = self._applied_counts or {}
        for i in sorted(want & applied):
            try:
                if self._count_raw(i) != int(counts.get(i, 1) or 1):
                    out.append(("#", i))
            except (TypeError, ValueError):
                pass
        ap = getattr(self, "_applied_pairs", None)
        if ap is not None:                     # v3.25: pairs wait for Update as well
            cur = clean_pairs(self._pairs)
            for i in sorted(set(ap) | set(cur)):
                if ap.get(i) != cur.get(i):
                    out.append(("&", i))
        asw = getattr(self, "_applied_swam", None)
        if asw is not None:                    # v3.28: a SWAM tick waits for Update as well
            for i in sorted(set(asw) ^ set(clean_swam(self._swam))):
                out.append(("~", i))
            asec = set(getattr(self, "_applied_swam_sec", None) or [])
            for i in sorted(asec ^ set(clean_swam_sec(self._swam_sec, self._swam))):
                if i in set(asw) & set(clean_swam(self._swam)):
                    out.append(("~", i))
        return out

    def _pending_bits(self):
        """_compute_pending_bits, remembered. _count_of() asks this once per
        instrument per redraw, so it must not walk sixty Tk variables each
        time."""
        if self._pending_cache is None:
            try:
                self._pending_cache = self._compute_pending_bits()
            except Exception:
                self._pending_cache = []
        return self._pending_cache

    def _pending_dirty(self):
        """Something moved on either side: recount, and relabel the button."""
        self._pending_cache = None
        self._sync_update_button()

    def _snapshot_applied(self):
        """Remember exactly what the right panel is now showing."""
        try:
            self._applied_sel = {i for i, v in self.check_vars.items() if v.get()}
            self._applied_counts = {i: self._count_raw(i)
                                    for i in self._vcount_vars}
            self._applied_pairs = clean_pairs(self._pairs)
            self._applied_swam = list(clean_swam(self._swam))
            self._applied_swam_sec = list(clean_swam_sec(self._swam_sec, self._swam))
        except Exception:
            pass
        self._pending_dirty()

    def _sync_update_button(self):
        """Label and colour of ⟳ Update. It says how many changes the panel
        has not taken in, because a stale panel that looks fresh is worse
        than no panel at all."""
        try:
            bits = self._pending_bits()
        except Exception:
            return
        for name in ("update_btn", "update_btn2"):      # Song Variants + Selected Instruments
            btn = getattr(self, name, None)
            if btn is None:
                continue
            try:
                if bits:
                    btn.config(text="⟳ Update (%d)" % len(bits),
                               bg=C_UPD_WAIT, fg="#ffffff")
                else:
                    btn.config(text=("⟳ Update" if self._hold_on()
                                     else "⟳ Update — live"),
                               bg=C_UPD_IDLE, fg=C_BTN_FG)
            except Exception:
                pass

    def _commit_left(self, persist=True):
        """Hand the left side to the variant, the app and the right panel.

        persist=False is the ⟳ Update button (v3.25): everything Save does EXCEPT
        writing the variant file. The variant in memory is brought up to date, so
        closing the program still writes it (the old promise), but clicking Update
        never touches the file by itself."""
        v = self._find_variant(self.current_variant)
        if v:
            v["fixed"], v["counts"] = self._ui_to_current_variant()
            v["stage_manual"] = dict(self._stage_manual)
            v["pairs"] = clean_pairs(self._pairs)
            v["swam"] = list(self._swam)
            v["swam_sec"] = list(self._swam_sec)
            if persist:
                self._persist_variants()
        self._apply_variant_to_app()
        self._update_conflicts()

    def _do_update(self):
        """⟳ Update — the left side goes into the right panel, all at once."""
        waiting = bool(self._pending_bits())
        self._commit_left(persist=False)       # v3.25: Update does not save
        if not waiting:
            self._toast("Nothing was waiting — both sides already agree.")

    def _var_reset(self):
        """↩ Reset — a BLANK left side: every box off, every count back to 1.

        His words, 2026-09-23: "Jag vill ha en reset som nollställer alla
        markerade checkbox till OFF och alla siffror till 1." So that is
        what it is - a clean sheet to build the next song on, not an undo
        of the last few clicks.

        IT ONLY ASKS WHEN IT CANNOT BE TAKEN BACK. With ⟳ Update holding
        (the default) nothing is lost: the right-hand panel still shows the
        line-up, and the variant on disk still holds it, so clicking that
        variant in the list on the left loads the whole thing straight
        back. With the hold switched off, Reset commits and overwrites the
        variant on the spot - and then there IS nothing to load back, so
        that is the one case it asks about.

        v3.9 (2026-10-17): the ✋ Stage hand placements AND the forced 🏠
        room are cleared too ("Reset nollstaller inte STAGE-knappens
        innehall och kanske inte rum. Det behovs."). They used to be left
        alone on the argument that they only apply to ticked channels - but
        the next song then inherited the last song's Roles, Sides, pairings
        and a forced room. They are cleared in memory only; the variant on
        disk keeps them until ⟳ Update / close writes the blank sheet, so
        clicking the variant in the list still brings them back with the
        line-up."""
        from tkinter import messagebox
        if not self._hold_on():
            if not messagebox.askyesno(
                    APP_NAME,
                    "Reset the whole line-up?\n\n"
                    "Every instrument is unticked and every count goes back "
                    "to 1.\n\n"
                    "The ⟳ Update button is switched off, so this is "
                    "written to ‘%s’ at once and cannot be taken back."
                    % self.current_variant):
                return
        for var in self._vfixed_vars.values():
            var.set(False)
        for var in self.check_vars.values():
            var.set(False)
        for var in self._vcount_vars.values():
            var.set("1")
        self._remember_counts_seen()
        self._sync_var_group_boxes()
        self._sync_group_all_boxes()
        # ✋ Stage by hand + forced 🏠 room go back to Auto (in memory only;
        # _commit_left / close write them into the variant).
        self._stage_manual = {}
        self._load_pairs_ui({})                    # ⛓ pairs go back to none as well
        self._stage_cache_key = None
        self._sync_room_btn()
        self._manual_sync()
        if self._hold_on():
            self._pending_dirty()
            self._update_conflicts()
            self._save_current_settings()
            self._toast("↩ Reset — all off, all counts 1, Stage by hand and "
                        "Room back to Auto. ⟳ Update puts it on the right.")
            return
        self._commit_left()
        self._toast("↩ Reset — all off, all counts 1, Stage by hand and "
                    "Room back to Auto.")

    def _set_ground(self, silent=False):
        """⚓ Remember the line-up on the left as my Ground."""
        fixed, counts = self._ui_to_current_variant()
        if not fixed:
            self._toast("Nothing on the left to make a Ground of.")
            return
        self.ground = {"name": self.current_variant, "fixed": list(fixed),
                       "counts": dict(counts),
                       "stage_manual": dict(self._stage_manual),
                       "pairs": clean_pairs(self._pairs),
                       "swam": list(self._swam), "swam_sec": list(self._swam_sec)}
        self._persist_variants()
        if not silent:
            self._toast("⚓ Ground saved — %d instruments." % len(fixed))

    def _var_ground(self):
        """⚓ Ground — back to the line-up you always come back to.

        Shift-click the button (or File ▸ Set … as my Ground) saves the one
        you have instead. It is a snapshot and not a pointer at a variant, so
        renaming or deleting the variant it came from cannot empty it — see
        clean_ground()."""
        from tkinter import messagebox
        g = self.ground
        if not g:
            if not messagebox.askyesno(
                    APP_NAME,
                    "No Ground saved yet.\n\n"
                    "Make the line-up on the left your Ground?\n\n"
                    "⚓ Ground then always brings it back, whatever else you "
                    "have been trying.\n"
                    "(Shift-click the button to change it later.)"):
                return
            self._set_ground()
            return
        fixed = set(g.get("fixed") or ())
        counts = g.get("counts") or {}
        for iid, var in self._vfixed_vars.items():
            var.set(iid in fixed)
        for iid, var in self.check_vars.items():
            var.set(iid in fixed)
        for iid, var in self._vcount_vars.items():
            var.set(str(counts.get(iid, 1)))
        self._stage_manual = stage_overrides_clean(g.get("stage_manual"))
        self._load_pairs_ui(g.get("pairs"))
        self._load_swam_ui(g.get("swam"), g.get("swam_sec"))
        self._sync_var_group_boxes()
        self._sync_group_all_boxes()
        self._stage_cache_key = None
        if self._hold_on():
            self._pending_dirty()
            self._update_conflicts()
            self._toast("⚓ Ground is on the LEFT — click ⟳ Update to use it.")
            return
        self._commit_left()
        self._toast("⚓ Ground.")

    def _on_hold_change(self):
        """The ⟳ Update mode was switched. Turning it OFF must never leave a
        stale panel behind, so whatever was waiting goes in at once."""
        self.settings["hold_left_updates"] = self._hold_on()
        save_settings(self.settings)
        if not self._hold_on():
            self._commit_left()
        self._pending_dirty()

    def _clear_all(self):
        """File ▸ Clear all selections, and the panel's own "Clear all".

        The same thing as ↩ Reset, and deliberately the same CODE: two
        buttons that both say "clear" and then do slightly different things
        (one leaving the counts at 4) is a trap, and the only difference
        there ever was is that this one forgot the counts."""
        self._var_reset()

    # ---- All / none per instrument group tab --------------------------------

    def _on_group_all(self, group):
        """The 'All' checkbox in a group tab's toolbar: tick or untick every
        instrument in THAT group in one click. Tri-state ('mix') means the group
        is partly ticked — clicking it then selects the whole group."""
        var = self._group_all_vars.get(group)
        if var is None:
            return
        # A click on a tri-state box lands on "0"/"1" from Tk's own toggle, but
        # "partly ticked -> click" should mean SELECT ALL, not clear.
        want = True if var.get() != "0" else False
        for inst in GROUP_MAP[group]:
            v = self.check_vars.get(inst["id"])
            if v is not None:
                v.set(want)
            pv = self._vfixed_vars.get(inst["id"])
            if pv is not None:
                pv.set(want)
        self._sync_group_all_boxes()
        self._sync_var_group_boxes()
        if self._hold_on():
            self._pending_dirty()
            self._update_conflicts()
            self._save_current_settings()
            return
        self._commit_left()

    def _sync_group_all_boxes(self):
        """Keep every group's All checkbox in step with its instruments:
        all ticked = on, none = off, some = tri-state."""
        for group, var in getattr(self, "_group_all_vars", {}).items():
            ids = [i["id"] for i in GROUP_MAP.get(group, [])]
            on = [i for i in ids if self.check_vars.get(i) is not None
                  and self.check_vars[i].get()]
            if not ids:
                continue
            if len(on) == len(ids):
                var.set("1")
            elif not on:
                var.set("0")
            else:
                var.set("mix")

    # ---- TAB 7: SONG VARIANTS -----------------------------------------------

    def _build_variants_tab(self):
        """Build the 'Song Variants' tab and insert it at index 0 (default tab)."""
        frame = tk.Frame(self.notebook, bg=C_BG)
        self.notebook.insert(0, frame, text="  ★ Song Variants  ")
        self.tab_frames["__variants__"] = frame

        # Toolbar — TWO rows, and the split is the meaning.
        #
        # He expected tighter padding to be enough: "om alla de knapparna
        # blir inte mycket ledigt utrymme mellan ord och kant, sa blir det
        # dessutom plats for tva knappar". It buys a little (padx 8 -> 5,
        # gap 2 -> 1, and row one breathes better for it) but not enough:
        # six buttons already fill the left pane at its default width, and
        # three more would simply be CLIPPED - invisible until the sash is
        # dragged, which is the worst of both worlds.
        #
        # So the second row is not a compromise, it is the point: the top
        # row acts on the LIST of variants, the bottom row acts on the
        # LINE-UP in the one you are looking at. They were never the same
        # kind of button.
        bar = tk.Frame(frame, bg=C_BG2, pady=5, padx=8)
        bar.pack(fill="x")
        row_list = tk.Frame(bar, bg=C_BG2)
        row_list.pack(fill="x")
        row_mix = tk.Frame(bar, bg=C_BG2)
        row_mix.pack(fill="x", pady=(4, 0))

        def tb(text, cmd, row=None, pad=1, bg=C_BTN, fg=C_BTN_FG):
            b = tk.Button(row if row is not None else row_list,
                          text=text, command=cmd,
                          bg=bg, fg=fg,               # normal colour: C_BTN = "#0f3460"
                          activebackground=C_BG, activeforeground=C_FG,
                          font=FONT_SMALL, relief="flat", padx=5, pady=3,
                          cursor="hand2")
            b.pack(side="left", padx=pad)
            return b

        # v3.25: his order - New, Rename, Duplicate, Delete, then Save As... and
        # Save LAST, and ⟳ Update right after Save: it does what Save does, except
        # that it does not write the variant file.
        tb("New", self._var_new)
        tb("Rename", self._var_rename)
        tb("Duplicate", self._var_duplicate)
        tb("Delete", self._var_delete)
        tb("SWAM", self._generate_swam_button)     # v3.28: generate the SWAM room presets of this song
        tb("Save As…", self._var_save_as)
        tb("Save", self._var_save)
        # ⟳ Update carries its own state in its colour and its label — see
        # _sync_update_button. ⚓ Ground restores; Shift-click saves.
        self.update_btn = tb("⟳ Update", self._do_update, bg=C_UPD_IDLE)
        tb("↩ Reset", self._var_reset, row=row_mix, bg=C_RESET_BTN)
        self.ground_btn = tb("⚓ Ground", self._var_ground, row=row_mix,
                             bg=C_GROUND_BTN)
        self.ground_btn.bind("<Shift-Button-1>",
                             lambda e: (self._set_ground(), "break")[1])
        tk.Label(row_mix, text="  ← this line-up", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left")
        self._sync_update_button()

        # Body: variants list | (picker over conflicts)
        body = tk.PanedWindow(frame, orient="horizontal", bg=C_BG,
                              sashwidth=5, sashrelief="flat", bd=0)
        body.pack(fill="both", expand=True)

        # --- Left: list of variants ---
        left = tk.Frame(body, bg=C_BG2)
        body.add(left, minsize=150)
        tk.Label(left, text="My song variants", bg=C_BG3, fg=C_FG,
                 font=FONT_HEADER, anchor="w", padx=8, pady=4).pack(fill="x")
        self._var_listbox = tk.Listbox(
            left, bg=C_BG2, fg=C_FG,
            selectbackground=C_ACCENT, selectforeground=C_SONG_NOW_FG,  # the current song
            activestyle="none", highlightthickness=0, bd=0,
            exportselection=False, font=FONT_HEADER)
        self._var_list_names = []   # song name per row (the rows carry a ▶ prefix)
        self._var_listbox.pack(fill="both", expand=True, padx=4, pady=4)
        self._var_listbox.bind("<<ListboxSelect>>", self._on_variant_select)

        # --- Right ---
        right = tk.Frame(body, bg=C_BG)
        body.add(right, minsize=320)

        ph = tk.Frame(right, bg=C_BG2, padx=8, pady=4)
        ph.pack(fill="x")
        tk.Label(ph, text="Instruments in this variant",
                 bg=C_BG2, fg=C_FG, font=FONT_HEADER).pack(side="left")
        tk.Label(ph, text="   [✓]=in this mix    [#]=how many you have",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left", padx=6)

        pcanvas = tk.Canvas(right, bg=C_BG, bd=0, highlightthickness=0)
        pvsb = tk.Scrollbar(right, orient="vertical", command=pcanvas.yview,
                            bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        pcanvas.configure(yscrollcommand=pvsb.set)
        pvsb.pack(side="right", fill="y")
        pcanvas.pack(side="top", fill="both", expand=True)
        pinner = tk.Frame(pcanvas, bg=C_BG)
        pwin = pcanvas.create_window((0, 0), window=pinner, anchor="nw")
        pinner.bind("<Configure>", lambda e: pcanvas.configure(scrollregion=pcanvas.bbox("all")))
        pcanvas.bind("<Configure>", lambda e: pcanvas.itemconfig(pwin, width=e.width))

        # ⛓ Column heads for the two new boxes - the same fixed cells as the rows.
        # v3.27: PINNED - it sits above the scrolling list, so the column names are
        # always in view. Packed after the scrollbar and before the canvas, so it is
        # exactly as wide as the rows.
        chead = tk.Frame(right, bg=C_BG)
        chead.pack(side="top", fill="x", padx=8, pady=(4, 0), before=pcanvas)
        for txt in ("Prio", "Pair", "SWAM", "Sect"):
            hc = tk.Frame(chead, bg=C_BG, width=PAIR_CELL_W, height=16)
            hc.pack_propagate(False)
            hc.pack(side="right", padx=(0, 4))
            tk.Label(hc, text=txt, bg=C_BG, fg=C_ACCENT,
                     font=("Segoe UI", 8, "bold")).pack(fill="both", expand=True)
        tk.Label(chead, text="Pair: same number = one level (0 = none).  "
                             "Prio: who owns it (9 = most).  SWAM: placed in SWAM's room.  "
                             "Sect: run in the SWAM Section plug-in.",
                 bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left")

        for group in GROUPS:
            # Group header = name + its own All/none box (same idea as the
            # instrument tabs: build a whole drum kit / string section in one
            # click instead of ticking every row).
            ghdr = tk.Frame(pinner, bg=C_BG3)
            ghdr.pack(fill="x", pady=(6, 0))
            tk.Label(ghdr, text=group, bg=C_BG3, fg=C_FG, font=FONT_HEADER,
                     anchor="w", padx=8).pack(side="left")
            gav = tk.StringVar(value="0")
            self._var_group_all_vars[group] = gav
            tk.Checkbutton(ghdr, text="all / none", variable=gav,
                           onvalue="1", offvalue="0", tristatevalue="mix",
                           bg=C_BG3, fg=C_ACCENT,      # normal colour: C_ACCENT = "#7eb8f7"
                           selectcolor=C_BG2,          # normal colour: C_BG2 = "#16213e"
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=FONT_SMALL, highlightthickness=0, bd=0,
                           cursor="hand2",
                           command=lambda g=group: self._on_var_group_all(g)
                           ).pack(side="right", padx=(0, 8))
            for inst in GROUP_MAP[group]:
                iid = inst["id"]
                rowf = tk.Frame(pinner, bg=C_BG)
                rowf.pack(fill="x", padx=8)
                # ⛓ v3.25: PAIR + PRIO, far right. Packed FIRST, from the right, in
                # fixed-width cells: the header lines up exactly, and in a narrow pane
                # it is the name that gets clipped, never the boxes.
                prv = self._vprio_vars.setdefault(iid, tk.StringVar(value="1"))
                pav = self._vpair_vars.setdefault(iid, tk.StringVar(value="0"))
                boxes = []
                for var, lo, hi, tip in ((prv, 1, PRIO_MAX, "Prio"),
                                         (pav, 0, PAIR_MAX, "Pair")):
                    cell = tk.Frame(rowf, bg=C_BG, width=PAIR_CELL_W, height=20)
                    cell.pack_propagate(False)
                    cell.pack(side="right", padx=(0, 4))
                    sb = tk.Spinbox(cell, from_=lo, to=hi, width=2,
                                    textvariable=var, justify="center",
                                    bg=C_BG2, fg=C_FG_DIM, buttonbackground=C_BG2,
                                    insertofftime=0, insertontime=9999999,
                                    relief="flat", highlightthickness=0,
                                    font=FONT_SMALL, wrap=False,
                                    command=lambda i=iid: self._on_pair_change(i))
                    sb.pack(fill="both", expand=True)
                    sb.bind("<FocusOut>", lambda e, i=iid: self._on_pair_change(i))
                    sb.bind("<Return>",   lambda e, i=iid: self._on_pair_change(i))
                    boxes.append(sb)
                self._vpair_spins[iid] = boxes
                # 🎻 v3.26: SWAM tick, left of Pair (packed after it, from the right).
                scell = tk.Frame(rowf, bg=C_BG, width=PAIR_CELL_W, height=20)
                scell.pack_propagate(False)
                scell.pack(side="right", padx=(0, 4))
                if swam_ok(iid):
                    sv = self._vswam_vars.setdefault(iid, tk.BooleanVar(value=iid in self._swam))
                    tk.Checkbutton(scell, variable=sv, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                                   activebackground=C_BG, highlightthickness=0, bd=0,
                                   cursor="hand2",
                                   command=lambda i=iid: self._on_swam_toggle(i)).pack(expand=True)
                # v3.29: Sect tick, left of SWAM (packed after it, from the right).
                xcell = tk.Frame(rowf, bg=C_BG, width=PAIR_CELL_W, height=20)
                xcell.pack_propagate(False)
                xcell.pack(side="right", padx=(0, 4))
                if swam_section_ok(iid):
                    xv = self._vsec_vars.setdefault(iid, tk.BooleanVar(value=iid in self._swam_sec))
                    tk.Checkbutton(xcell, variable=xv, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                                   activebackground=C_BG, highlightthickness=0, bd=0,
                                   cursor="hand2",
                                   command=lambda i=iid: self._on_swam_sec_toggle(i)).pack(expand=True)
                fv = tk.BooleanVar(value=False)
                # The count variable is SHARED with the spin box on the
                # instrument card (created in __init__), so changing it in one
                # place updates the other immediately.
                cv = self._vcount_vars.setdefault(iid, tk.StringVar(value="1"))
                self._vfixed_vars[iid] = fv
                tk.Checkbutton(rowf, variable=fv, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                               activebackground=C_BG, highlightthickness=0, bd=0,
                               command=lambda i=iid: self._on_var_toggle(i)).pack(side="left")
                # Count: how many of this instrument the variant has (default 1).
                # A fixed (non-blinking) cursor — no insert blink — per CLAUDE.md.
                spin = tk.Spinbox(rowf, from_=1, to=MAX_INSTRUMENT_COUNT, width=2,
                                  textvariable=cv, justify="center",
                                  bg=C_BG2, fg=C_CHAR, buttonbackground=C_BG2,
                                  insertofftime=0, insertontime=9999999,
                                  relief="flat", highlightthickness=0,
                                  font=FONT_SMALL, wrap=False,
                                  command=lambda i=iid: self._on_count_change(i))
                spin.pack(side="left", padx=(2, 0))
                # Typing a number (rather than clicking the arrows) also persists.
                spin.bind("<FocusOut>", lambda e, i=iid: self._on_count_change(i))
                spin.bind("<Return>",   lambda e, i=iid: self._on_count_change(i))
                tk.Label(rowf, text="●", fg=inst.get("color", C_FG), bg=C_BG,
                         font=("Segoe UI", 10)).pack(side="left", padx=(4, 2))
                tk.Label(rowf, text=inst["name"], bg=C_BG, fg=C_FG,
                         font=FONT_NORMAL).pack(side="left")

        def _pw(e, _c=pcanvas):
            _c.yview_scroll(-2 if e.delta > 0 else 2, "units")
            return "break"
        pcanvas.bind("<MouseWheel>", _pw)
        self._bind_wheel(pinner, _pw)

        # Conflicts / recommendations. The 🔎 focus view unpacks these three
        # (separator, heading, text box) and the instrument list takes the
        # room back; the text itself is still generated and still there the
        # moment the long face is switched on again.
        csep = tk.Frame(right, bg=C_SEP, height=1)
        csep.pack(fill="x")
        ch = tk.Frame(right, bg=C_BG2, padx=8, pady=3)
        ch.pack(fill="x")
        tk.Label(ch, text="⚠  Conflicts & recommendations",
                 bg=C_BG2, fg="#ffb347", font=FONT_HEADER).pack(side="left")
        cff = tk.Frame(right, bg=C_BG2)
        cff.pack(fill="x")
        self._var_conflict_widgets = [(csep, {"fill": "x"}),
                                      (ch,   {"fill": "x"}),
                                      (cff,  {"fill": "x"})]
        self._var_conflict_text = tk.Text(
            cff, height=9, bg=C_BG2, fg=C_FG, font=FONT_SMALL,
            relief="flat", bd=0, wrap="word", insertontime=0, padx=8, pady=6)
        cvsb = tk.Scrollbar(cff, orient="vertical",
                            command=self._var_conflict_text.yview, bg=C_BG2)
        self._var_conflict_text.configure(yscrollcommand=cvsb.set)
        cvsb.pack(side="right", fill="y")
        self._var_conflict_text.pack(side="left", fill="x", expand=True)

        # Populate UI from the current variant (does NOT force app selection on startup)
        self._refresh_variant_list()
        self._load_variant_ui(self._find_variant(self.current_variant), apply_to_app=False)

    # ---- variant helpers ----------------------------------------------------

    def _find_variant(self, name):
        for v in self.variants:
            if v["name"] == name:
                return v
        return self.variants[0] if self.variants else None

    def _variant_selection(self):
        """Set of instrument ids ticked (in this mix) in the tab."""
        return {iid for iid, var in self._vfixed_vars.items() if var.get()}

    def _on_var_group_all(self, group):
        """All/none for one group in the Song Variants tab. Partly ticked
        ('mix') + click = put the WHOLE group in the variant."""
        var = self._var_group_all_vars.get(group)
        if var is None:
            return
        want = var.get() != "0"
        for inst in GROUP_MAP[group]:
            v = self._vfixed_vars.get(inst["id"])
            if v is not None:
                v.set(want)
        self._sync_var_group_boxes()
        self._on_var_toggle()

    def _sync_var_group_boxes(self):
        """Keep the variant tab's group boxes in step: all / none / tri-state."""
        for group, var in getattr(self, "_var_group_all_vars", {}).items():
            ids = [i["id"] for i in GROUP_MAP.get(group, [])]
            if not ids:
                continue
            on = [i for i in ids if self._vfixed_vars.get(i) is not None
                  and self._vfixed_vars[i].get()]
            var.set("1" if len(on) == len(ids) else ("0" if not on else "mix"))

    def _count_raw(self, iid):
        """What the spin box says RIGHT NOW (>= 1), whatever is waiting.
        Anything that WRITES the variant uses this one."""
        try:
            n = int(self._vcount_vars[iid].get())
        except (ValueError, KeyError):
            n = 1
        return max(1, min(MAX_INSTRUMENT_COUNT, n))

    def _count_of(self, iid):
        """Current count for an instrument (>= 1), tolerant of bad text input.

        Applied-aware, for exactly the reason _checked_ids() is: while
        something is waiting for ⟳ Update the engines keep working from the
        count the right panel was built with, so the panel holds still."""
        if self._pending_bits():
            try:
                return max(1, min(MAX_INSTRUMENT_COUNT,
                                  int((self._applied_counts or {}).get(
                                      iid, self._count_raw(iid)))))
            except (TypeError, ValueError):
                pass
        return self._count_raw(iid)

    def _ui_to_current_variant(self):
        """Return (fixed_ids, counts_dict) from the current tab state."""
        fixed = [iid for iid, var in self._vfixed_vars.items() if var.get()]
        counts = {iid: self._count_raw(iid) for iid in fixed}
        return fixed, counts

    def _refresh_variant_list(self):
        # Always A-Z; self.variants (and the file) keep their own order.
        lb = self._var_listbox
        names = sorted((v["name"] for v in self.variants), key=song_sort_key)
        self._var_list_names = names
        lb.delete(0, "end")
        for n in names:
            lb.insert("end", ("▶  " if n == self.current_variant else "      ") + n)
        if self.current_variant in names:
            i = names.index(self.current_variant)
            lb.selection_clear(0, "end")
            lb.selection_set(i)
            lb.see(i)
        self._sync_current_song_mark()

    def _sync_current_song_mark(self):
        """Name the current song in the title bar (every tab shows it)."""
        lbl = getattr(self, "now_song_lbl", None)
        if lbl is None:
            return
        name = self.current_variant or ""
        if len(name) > SONG_NOW_CHARS - 8:
            name = name[:SONG_NOW_CHARS - 9] + "…"
        lbl.config(text="♪ Now: " + name)

    def _load_variant_ui(self, v, apply_to_app=True):
        if not v:
            return
        self.current_variant = v["name"]
        fixed = set(v.get("fixed", []))
        counts = v.get("counts", {}) or {}
        # 🎪 The hand placements belong to the SONG, so they arrive with it.
        self._stage_manual = stage_overrides_clean(v.get("stage_manual"))
        self._load_pairs_ui(v.get("pairs"))       # ⛓ v3.25: pairs travel with the song too
        self._load_swam_ui(v.get("swam"), v.get("swam_sec"))         # 🎻 v3.26: so does which parts are SWAM
        self._stage_cache_key = None
        for iid, var in self._vfixed_vars.items():
            var.set(iid in fixed)
        for iid, var in self._vcount_vars.items():
            var.set(str(counts.get(iid, 1)))
        self._remember_counts_seen()
        self._sync_var_group_boxes()
        self._refresh_multi_notes()    # a new variant can bring new counts
        if apply_to_app:
            self._apply_variant_to_app()
        self._pending_dirty()
        self._update_conflicts()

    def _apply_variant_to_app(self):
        """Drive the app-wide instrument checkboxes (and Summary) from the
        variant — and take a new snapshot, because this IS the moment the
        right panel catches up with the left. The snapshot is taken BEFORE
        the redraw: the redraw reads it."""
        sel = self._variant_selection()
        for iid, cv in self.check_vars.items():
            cv.set(iid in sel)
        self._sync_group_all_boxes()
        self._stage_cache_key = None
        self._snapshot_applied()
        self._refresh_multi_notes()
        self._refresh_live_notes()
        self._refresh_summary()
        self._save_current_settings()

    def _persist_variants(self):
        save_variants(self.variants, self.current_variant, self.ground)

    def _on_variant_select(self, evt=None):
        sel = self._var_listbox.curselection()
        if not sel:
            return
        if sel[0] >= len(self._var_list_names):
            return
        v = self._find_variant(self._var_list_names[sel[0]])
        if v:
            self._load_variant_ui(v, apply_to_app=True)
            self._refresh_variant_list()    # moves the ▶ to the new song
            self._persist_variants()

    def _on_var_toggle(self, iid=None):
        """A tick in the picker.

        With ⟳ Update holding, this writes NOTHING yet: the variant is
        written on Update and again on close, which keeps the old promise
        (the next launch starts with exactly what you ended with) while
        leaving ↩ Reset something real to undo."""
        if iid:
            self._mark_focus(iid)
        self._sync_var_group_boxes()
        # The card boxes ask the same question; keep them in step.
        for iid, var in self._vfixed_vars.items():
            cv = self.check_vars.get(iid)
            try:
                if cv is not None and bool(cv.get()) != bool(var.get()):
                    cv.set(bool(var.get()))
            except Exception:
                pass
        self._sync_group_all_boxes()
        if self._hold_on():
            self._pending_dirty()
            self._update_conflicts()
            return
        self._commit_left()

    def _var_save(self):
        v = self._find_variant(self.current_variant)
        if not v:
            return
        # Save = Update as well (2026-10-12): the same road the Update
        # button takes, so the right-hand panel shows what was just saved.
        self._commit_left()
        self._toast(f"Saved variant: {v['name']}  \u2014  and updated")

    def _ow(self, what):
        """v3.37: the 'overwrite?' answer of one generator run (asked only if a file already exists)."""
        return _OverwriteAsk(self, what)

    def _ask_overwrite_popup(self, what, dst=None):
        """Modal question: replace the existing preset files with the new ones? True = overwrite.
        Esc / closing the window = keep the existing files (the safe answer)."""
        top = tk.Toplevel(self.root)
        top.title("Overwrite existing presets?")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        top.transient(self.root)
        result = {"ok": False}
        where = ""
        if dst:
            where = "\n\nFor example:\n%s" % dst
        tk.Label(top, text="%s presets with these names already exist.%s" % (what, where),
                 bg=C_BG3, fg=C_FG, font=FONT_NORMAL, justify="left", wraplength=520,
                 anchor="w").pack(padx=16, pady=(14, 6), anchor="w")
        tk.Label(top, text="If you overwrite, the NEW presets replace the existing ones (each old file is kept "
                           "next to it as a .bak copy). If you keep the existing ones, the plug-in keeps loading "
                           "the OLD sound; presets that do not exist yet are created either way.",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL, justify="left", wraplength=520,
                 anchor="w").pack(padx=16, pady=(0, 10), anchor="w")
        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(padx=16, pady=(0, 14), fill="x")

        def _yes(e=None):
            result["ok"] = True
            top.destroy()

        def _no(e=None):
            result["ok"] = False
            top.destroy()

        tk.Button(btns, text="Overwrite with new", command=_yes,
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG, activeforeground=C_FG,
                  relief="flat", padx=14, pady=3, cursor="hand2").pack(side="right", padx=(6, 0))
        tk.Button(btns, text="Keep existing (Esc)", command=_no,
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG, activeforeground=C_FG,
                  relief="flat", padx=14, pady=3, cursor="hand2").pack(side="right")
        top.protocol("WM_DELETE_WINDOW", _no)
        top.update_idletasks()
        x = self.root.winfo_rootx() + (self.root.winfo_width() - top.winfo_width()) // 2
        y = self.root.winfo_rooty() + (self.root.winfo_height() - top.winfo_height()) // 3
        top.geometry("+%d+%d" % (max(x, 0), max(y, 0)))
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", _no)
        top.wait_window()
        return result["ok"]

    def _ask_string(self, title, prompt, initial=""):
        """Modal text prompt with a FIXED (non-blinking) cursor. Enter=OK, Esc=Cancel.
        Returns the entered string (stripped) or None if cancelled."""
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        top.transient(self.root)
        result = {"value": None}

        tk.Label(top, text=prompt, bg=C_BG3, fg=C_FG,
                 font=FONT_NORMAL).pack(padx=16, pady=(14, 4), anchor="w")
        ent = tk.Entry(top, bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                       insertofftime=0, insertontime=9999999,   # fixed, never blinks
                       relief="flat", font=FONT_NORMAL, width=36)
        ent.pack(padx=16, pady=(0, 10))
        ent.insert(0, initial)
        ent.select_range(0, "end")

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(padx=16, pady=(0, 14), fill="x")

        def _ok(e=None):
            result["value"] = ent.get().strip()
            top.destroy()

        def _cancel(e=None):
            result["value"] = None
            top.destroy()

        tk.Button(btns, text="OK", command=_ok,
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG, activeforeground=C_FG,
                  relief="flat", padx=14, pady=3, cursor="hand2").pack(side="right", padx=(6, 0))
        tk.Button(btns, text="Cancel", command=_cancel,
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG, activeforeground=C_FG,
                  relief="flat", padx=14, pady=3, cursor="hand2").pack(side="right")

        top.bind("<Return>", _ok)
        top.update_idletasks()
        x = self.root.winfo_rootx() + (self.root.winfo_width()  - top.winfo_width())  // 2
        y = self.root.winfo_rooty() + (self.root.winfo_height() - top.winfo_height()) // 3
        top.geometry(f"+{max(x, 0)}+{max(y, 0)}")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", _cancel)
        ent.focus_set()
        top.wait_window()
        return result["value"] or None

    def _var_new(self):
        from tkinter import messagebox
        name = self._ask_string("New variant", "Name:")
        if not name or not name.strip():
            return
        name = name.strip()
        if any(x["name"] == name for x in self.variants):
            messagebox.showinfo(APP_NAME, "A variant with that name already exists.")
            return
        self.variants.append({"name": name, "fixed": [], "counts": {},
                              "stage_manual": {}, "pairs": {}, "swam": []})
        self.current_variant = name
        self._refresh_variant_list()
        self._load_variant_ui(self._find_variant(name), apply_to_app=True)
        self._persist_variants()

    def _var_save_as(self):
        from tkinter import messagebox
        name = self._ask_string("Save variant as", "New name:",
                                initial=self.current_variant)
        if not name or not name.strip():
            return
        name = name.strip()
        if any(x["name"] == name for x in self.variants):
            messagebox.showinfo(APP_NAME, "A variant with that name already exists.")
            return
        fixed, counts = self._ui_to_current_variant()
        self.variants.append({"name": name, "fixed": fixed, "counts": counts,
                              "stage_manual": dict(self._stage_manual),
                              "pairs": clean_pairs(self._pairs),
                              "swam": list(self._swam), "swam_sec": list(self._swam_sec)})
        self.current_variant = name
        self._refresh_variant_list()
        self._commit_left()                  # Save as = Update as well
        self._toast(f"Saved as: {name}  \u2014  and updated")

    def _var_rename(self):
        from tkinter import messagebox
        v = self._find_variant(self.current_variant)
        if not v:
            return
        name = self._ask_string("Rename variant", "New name:", initial=v["name"])
        if not name or not name.strip():
            return
        name = name.strip()
        if name != v["name"] and any(x["name"] == name for x in self.variants):
            messagebox.showinfo(APP_NAME, "A variant with that name already exists.")
            return
        v["name"] = name
        self.current_variant = name
        self._refresh_variant_list()
        self._persist_variants()

    def _var_duplicate(self):
        v = self._find_variant(self.current_variant)
        if not v:
            return
        existing = {x["name"] for x in self.variants}
        base = v["name"] + " copy"
        name, n = base, 2
        while name in existing:
            name = f"{base} {n}"
            n += 1
        fixed, counts = self._ui_to_current_variant()
        self.variants.append({"name": name, "fixed": list(fixed),
                              "counts": dict(counts),
                              "stage_manual": dict(self._stage_manual),
                              "pairs": clean_pairs(self._pairs),
                              "swam": list(self._swam), "swam_sec": list(self._swam_sec)})
        self.current_variant = name
        self._refresh_variant_list()
        self._persist_variants()

    def _var_delete(self):
        from tkinter import messagebox
        if len(self.variants) <= 1:
            messagebox.showinfo(APP_NAME, "Keep at least one variant.")
            return
        v = self._find_variant(self.current_variant)
        if not v:
            return
        if not messagebox.askyesno(APP_NAME, f"Delete variant '{v['name']}'?"):
            return
        self.variants = [x for x in self.variants if x is not v]
        self.current_variant = self.variants[0]["name"]
        self._refresh_variant_list()
        self._load_variant_ui(self._find_variant(self.current_variant), apply_to_app=True)
        self._persist_variants()

    def _update_conflicts(self):
        """Analyse the selected instruments and give actionable EQ advice:
        (a) regions where several instruments boost (clashes), and
        (b) targeted tips for the specific combination in the song."""
        txt = self._var_conflict_text
        txt.configure(state="normal")
        txt.delete("1.0", "end")
        txt.tag_configure("h", foreground=C_ACCENT, font=FONT_HEADER)

        sel = self._variant_selection()
        insts = [x for x in EQ_DATA if x["id"] in sel]
        id2name = {x["id"]: x["name"] for x in EQ_DATA}

        # Instruments you have more than one of in this variant (count > 1).
        # The conflicts box lives on the LEFT and reads the left side, so it
        # follows the spin boxes straight away - nothing here waits.
        multiples = [(x["id"], x["name"], self._count_raw(x["id"]))
                     for x in insts if self._count_raw(x["id"]) > 1]

        if len(insts) < 2 and not multiples:
            txt.insert("end", "Select at least two instruments to see clashes and tips.")
            txt.configure(state="disabled")
            return

        def add(s, tag=None):
            txt.insert("end", s + "\n", tag) if tag else txt.insert("end", s + "\n")

        # ---- MULTIPLES: advice for having several of the same instrument ----
        if multiples:
            add("MULTIPLES (more than one of the same part)", "h")
            for iid, nm, n in multiples:
                plan = self._multi_plan_for(iid)
                if not plan:
                    continue
                add(f"• {n}× {nm}  [{plan['label']}] — {plan['headline']}")
                if plan["what"]:
                    add(f"    {plan['what']}")
                add(f"    Level: {plan['gain_line']}")
                add("    Pan:   " + plan["pan_line"])
                if plan["tone"]:
                    add(f"    Tone:  {plan['tone']}")
                if plan["hp"]:
                    add("    Low cut: " + "  ·  ".join(plan["hp"]))
                add(f"    Bus:   {plan['bus']}")
                if plan["trap"]:
                    add(f"    ⚠ {plan['trap']}")
                if plan["too_many"]:
                    add(f"    ⚠ {plan['too_many']}")
            add("")

        def has(*ids):   return all(i in sel for i in ids)
        def anyof(*ids): return any(i in sel for i in ids)

        # ---- Boost map per region (+ who pushes MELODIC presence 2–6 kHz) ----
        # Drums/bass also have energy at 2–6 kHz (beater click, grind) but that is
        # wanted attack, not melodic presence competing with the lead — exclude them
        # from the "who owns 3–5 kHz" advice.
        RHYTHM_LOW = {"kick", "snare", "hihat", "ride", "cymbals", "toms", "percussion",
                      "hand_drums",
                      "bass_root", "bass_loop", "double_bass", "double_bass_section"}
        region_boost = {}
        presence = []                      # melodic names boosting in 2–6 kHz
        for inst in insts:
            hot = False
            for b in inst.get("bands", []):
                db = b.get("db", 0)
                if not ((b.get("type") == "boost") or (db and db > 0)):
                    continue
                hz = _parse_hz_midpoint(b.get("hz", ""))
                if not hz:
                    continue
                region_boost.setdefault(_region_of(hz), set()).add(inst["name"])
                if 2000 <= hz < 6000 and inst["id"] not in RHYTHM_LOW:
                    hot = True
            if hot:
                presence.append(inst["name"])

        REGION_ADVICE = {
            "Sub (<60 Hz)":       "keep ONE source here (kick or bass); high-pass the rest.",
            "Bass (60–250 Hz)":   "split fundamentals (kick ~60 Hz, bass ~90 Hz) and sidechain; high-pass everything else.",
            "Lo-mid (250–500 Hz)": "the mud zone — cut it on all but one; this is where mixes get cloudy.",
            "Mid (500 Hz–2 kHz)": "pan competing parts apart and carve; only one should be forward.",
            "Hi-mid (2–6 kHz)":   "the 'who's in front' zone — let ONE own 3–5 kHz, dip it on the others.",
            "Highs (>6 kHz)":     "high-pass cymbals/hats and keep air boosts gentle to avoid harsh buildup.",
        }
        order = ["Sub (<60 Hz)", "Bass (60–250 Hz)", "Lo-mid (250–500 Hz)",
                 "Mid (500 Hz–2 kHz)", "Hi-mid (2–6 kHz)", "Highs (>6 kHz)"]

        clash_lines = []
        for r in order:
            names = sorted(region_boost.get(r, []))
            if len(names) >= 2:
                clash_lines.append(f"• {r}: {', '.join(names)} — {REGION_ADVICE[r]}")

        if clash_lines:
            add("BAND CLASHES (multiple boosts)", "h")
            for l in clash_lines:
                add(l)
            add("")

        # ---- Targeted tips for the specific combination ----
        tips = []
        if has("bass_root", "bass_loop"):
            tips.append("Two basses: let Root Bass own < 100 Hz; high-pass the Bass Loop ~80–120 Hz "
                        "and push it into 500 Hz–3 kHz so the lines don't mask each other.")
        if "kick" in sel and anyof("bass_root", "bass_loop"):
            tips.append("Kick + bass share 60–100 Hz: sidechain the bass to the kick and split their "
                        "boosts (kick ~60 Hz, bass ~90 Hz).")
        if has("guitar_rhythm", "guitar_chords"):
            tips.append("Two rhythm/chord guitars: hard-pan L/R and EQ each a bit differently "
                        "(one brighter, one warmer) so they widen instead of clash.")
        comp = [id2name[i] for i in ("guitar_rhythm", "guitar_chords", "organ",
                                     "accordion", "piano_bg") if i in sel]
        if len(comp) >= 2:
            tips.append("Comping layers (" + ", ".join(comp) + ") pile up in 200–800 Hz — pan them apart, "
                        "cut that range on all but one, and give each its own narrow 'home' band.")
        if "piano_bg" in sel and anyof("guitar_rhythm", "guitar_chords", "organ", "accordion"):
            tips.append("Piano (background) is support, not lead — dip its 2–5 kHz and cut 300–500 Hz so it "
                        "tucks UNDER the guitars/organ.")
        if "accordion" in sel and anyof("organ", "piano_bg", "piano_riff", "guitar_chords"):
            tips.append("Accordion vs the other chordal parts: they all live 300 Hz–4 kHz. Pan the "
                        "accordion opposite them, cut its 300–600 Hz box, and let ONE of them own "
                        "the 1–2 kHz mids at a time.")
        if "accordion" in sel and anyof("bass_root", "bass_loop", "double_bass", "double_bass_section"):
            tips.append("Accordion + bass: the accordion's left-hand bass/chord reeds double the bass "
                        "line. High-pass the accordion at 80–120 Hz (or don't play those reeds) so "
                        "the low end stays clean.")
        for bed, lead, _hp, why in BED_LEAD_PAIRS:
            if has(bed, lead):
                tips.append("%s + %s: one instrument, two jobs, opposite EQ. %s"
                            % (id2name[bed], id2name[lead], why))
        role_leads = [i for i in (lead for _b, lead, _h, _w in BED_LEAD_PAIRS) if i in sel]
        rivals = [i for i in ("vocals_lead", "piano_riff", "saxophone", "harmonica",
                              "trumpet", "violin", "flute")
                  if i in sel and i not in role_leads]
        if role_leads and (rivals or len(role_leads) > 1):
            tips.append(", ".join(id2name[i] for i in role_leads) +
                        (" carries" if len(role_leads) == 1 else " carry") +
                        " the tune — and every melody instrument lands on the same 1–3 kHz. "
                        "ONE at a time: trade phrases, split octaves, or pan them apart, and dip 3–5 kHz "
                        "on whichever one is answering.")
        if has("piano_riff", "guitar_lead"):
            tips.append("Piano riff vs Lead guitar: both want the 1–3 kHz hook spot — let one carry the "
                        "melody at a time, split octaves, or pan them apart.")
        if len(presence) >= 2:
            if "vocals_lead" in sel:
                others = sorted(n for n in presence if n != id2name["vocals_lead"])
                tips.append("Lead Vocal owns 3–5 kHz — cut 2–4 dB there on: " + ", ".join(others) + ".")
            else:
                tips.append("Presence battle in 3–5 kHz (" + ", ".join(sorted(presence)) +
                            "): pick ONE to sit forward and dip 3–5 kHz on the rest.")
        if has("vocals_extra", "vocals_lead"):
            tips.append("Extra Vocals vs Lead Vocal: dip 3–5 kHz on the extra layer, and let the duck bring it back up "
                        "when the lead stops - a trailing word then swells in the gap the lead leaves.")
        if has("vocals_choir_pad", "vocals_lead"):
            tips.append("Choir/Vocal Pad vs Lead Vocal: carve 3–5 kHz on the pad and sidechain it to the lead.")
        if has("vocals_backing", "vocals_lead"):
            tips.append("Backing vocals: high-pass more, cut more mud, and use less 3–5 kHz than the lead so "
                        "they sit behind it.")
        if has("hihat", "cymbals"):
            tips.append("Hi-hat + cymbals/overheads stack in the highs — high-pass the hat ~300–500 Hz and "
                        "tame 6–8 kHz if it gets harsh or fatiguing.")
        if "toms" in sel and ("kick" in sel or anyof("bass_root", "bass_loop")):
            tips.append("Toms vs kick/bass in 60–200 Hz — gate the toms and high-pass them slightly so the "
                        "low end stays tight.")
        strings = [i for i in ("violin", "viola", "viola_front", "cello", "double_bass", "double_bass_section", "string_section") if i in sel]
        if strings and anyof("vocals_lead", "guitar_lead", "piano_riff",
                             "organ_lead", "brass_lead", "strings_lead",
                             "accordion_lead", "viola_front"):
            tips.append("Strings vs the lead in 2–8 kHz — keep the bow 'air' on the strings gentle so it "
                        "doesn't mask the lead's presence.")
        if "double_bass" in sel and anyof("bass_root", "bass_loop"):
            tips.append("Double Bass + electric/synth bass: pick one to own the sub; high-pass the other and "
                        "separate them by octave/region.")
        # ---- Horns (v2.5) ----
        horns = [id2name[i] for i in ("trumpet", "trombone", "saxophone", "flugelhorn",
                                      "french_horn", "tuba", "euphonium", "bass_trombone",
                                      "alto_trombone", "tenor_trombone", "tenor_bass_trombone",
                                      "double_bass_trombone", "piccolo_trumpet",
                                      "horn_section", "brass") if i in sel]
        if len(horns) >= 2:
            tips.append("Horns (" + ", ".join(horns) + ") are ONE instrument in the arrangement: bus them, "
                        "glue-compress the bus, cut 500 Hz–1 kHz there once, and put a single Trackspacer on "
                        "the bus rather than one per horn.")
        if "horn_section" in sel and anyof("trumpet", "trombone", "tenor_trombone", "saxophone"):
            tips.append("You have both the Horn Section card AND individual horns ticked. Treat the section "
                        "card as the BUS — do the shared cuts there and keep the channel EQs minimal, or you "
                        "will cut 500 Hz–1 kHz twice.")
        if anyof("trumpet", "saxophone", "harmonica") and "vocals_lead" in sel:
            hot = [id2name[i] for i in ("trumpet", "saxophone", "harmonica") if i in sel]
            tips.append(", ".join(hot) + " vs the Lead Vocal: these land exactly on the voice (1–5 kHz) and "
                        "are louder than it. Duck them under the vocal, pan them well off-centre, and if you "
                        "can, arrange them to ANSWER the vocal lines rather than play underneath them.")
        if anyof("trombone", "tenor_trombone", "tenor_bass_trombone", "double_bass_trombone") and anyof("bass_root", "bass_loop", "double_bass", "double_bass_section"):
            tips.append("Trombone + bass: the bone sits on 100–250 Hz with the bass. Decide who owns it — "
                        "normally the bass — and high-pass the trombone at 120–150 Hz so it adds harmony, "
                        "not weight.")
        if "saxophone" in sel and "trumpet" in sel:
            tips.append("Sax + trumpet: the trumpet owns 3–6 kHz (blare) and the sax owns 1–3 kHz (reed core). "
                        "Give each that band and dip it on the other, and pan them to opposite sides.")
        if "guitar_acoustic" in sel and anyof("guitar_rhythm", "guitar_chords"):
            tips.append("Acoustic + electric guitars: the acoustic is the wide-band one, so it yields. "
                        "High-pass it at 100–120 Hz, cut 250–500 Hz, and let it live above 2 kHz as texture "
                        "while the electrics keep the body.")
        if "guitar_acoustic" in sel and "vocals_lead" in sel and not anyof(
                "guitar_rhythm", "guitar_chords", "piano_bg"):
            tips.append("Voice + acoustic only: nothing else is holding the low end, so give the acoustic its "
                        "body back — high-pass at 80 Hz instead of 120, and keep 100–250 Hz rather than "
                        "cutting it. The full-band recipe will make a duo sound thin.")
        if "harmonica" in sel and anyof("guitar_lead", "piano_riff", "saxophone", "trumpet"):
            tips.append("Harmonica vs the other solo voices: they all want 2–4 kHz. Only one of them takes a "
                        "solo at a time — automate the others down rather than trying to EQ them apart.")

        if tips:
            add("TIPS FOR THIS COMBINATION", "h")
            for t in tips:
                add("• " + t)

        if not clash_lines and not tips:
            add("No major band clashes detected. ✓")
        txt.configure(state="disabled")

    # ---- PLUGIN LIBRARY TAB -------------------------------------------------

    def _persist_plugins(self):
        save_plugins(self.plugins)

    def _plugins_by_status(self, *statuses):
        """List of plugins whose status is one of `statuses`."""
        s = set(statuses)
        return [p for p in self.plugins if p.get("status") in s]

    def _liked_plugins_of_kind(self, kind):
        """Favourite/like/core plugins of a kind, best first; disliked excluded.
        Used by the inserts map and the suggestion engine."""
        rank = {"favorite": 0, "core": 1, "like": 2}
        out = [p for p in self.plugins
               if p.get("kind") == kind and p.get("status") in rank]
        out.sort(key=lambda p: (rank.get(p["status"], 9), p["name"].lower()))
        return out

    def _open_url(self, url):
        if not url:
            return
        try:
            import webbrowser
            open_url(url)
        except Exception:
            pass

    def _build_plugins_tab(self):
        """Build the '🧩 Plugins' tab (a personal, editable plugin library) and
        insert it at position 1 (right after Song Variants)."""
        frame = tk.Frame(self.notebook, bg=C_BG)
        self.notebook.insert(1, frame, text="  🧩 Plugins  ")
        self.tab_frames["__plugins__"] = frame
        self.plugins_frame = frame      # the 🔎 focus view hides this tab

        # Toolbar: add + filter
        bar = tk.Frame(frame, bg=C_BG2, pady=5, padx=8)
        bar.pack(fill="x")
        tk.Button(bar, text="➕ Add plugin", command=self._add_plugin_dialog,
                  bg=C_BTN, fg=C_BTN_FG,            # normal colour: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=8, pady=3,
                  cursor="hand2").pack(side="left")
        tk.Label(bar, text="Show:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(12, 4))
        self._plugin_filter_var = tk.StringVar(value=self._plugin_kind_filter)
        opts = ["All", "★ Focus", "♥ Favourites", "👍 Liked", "· Untested",
                "👎 Disliked", "⚙ Core tools"] + ["— " + k for k in PLUGIN_KINDS]
        om = tk.OptionMenu(bar, self._plugin_filter_var, *opts,
                           command=lambda v: self._on_plugin_filter())
        om.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG,
                     highlightthickness=0, bd=0, font=FONT_SMALL, relief="flat",
                     cursor="hand2")
        om["menu"].configure(bg=C_BG, fg=C_FG, activebackground=C_BG3,
                             activeforeground=C_FG)
        om.pack(side="left")

        # Status legend (right)
        for st in ("favorite", "like", "untested", "dislike"):
            glyph, col, lbl = PLUGIN_STATUS[st]
            tk.Label(bar, text=f"{glyph} {lbl}", bg=C_BG2, fg=col,
                     font=FONT_SMALL).pack(side="right", padx=(8, 0))

        # Reminder line
        self._plugin_reminder = tk.Label(frame, bg=C_BG2, fg=C_FG_DIM,
                                         font=FONT_SMALL, anchor="w", justify="left",
                                         wraplength=900, padx=10, pady=4)
        self._plugin_reminder.pack(fill="x")
        tk.Frame(frame, bg=C_SEP, height=1).pack(fill="x")

        # Scrollable list
        canvas = tk.Canvas(frame, bg=C_BG, bd=0, highlightthickness=0)
        vsb = tk.Scrollbar(frame, orient="vertical", command=canvas.yview,
                           bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canvas.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        self._plugins_canvas = canvas
        inner = tk.Frame(canvas, bg=C_BG)
        win = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>", lambda e: canvas.itemconfig(win, width=e.width))
        self._plugins_inner = inner

        def _pw(e, _c=canvas):
            _c.yview_scroll(-2 if e.delta > 0 else 2, "units")
            return "break"
        self._plugins_wheel = _pw
        canvas.bind("<MouseWheel>", _pw)

        self._refresh_plugins_list()

    def _on_plugin_filter(self):
        self._plugin_kind_filter = self._plugin_filter_var.get()
        self._refresh_plugins_list()

    def _refresh_plugins_list(self):
        """Rebuild the plugin rows, grouped by kind, honouring the current filter."""
        inner = self._plugins_inner
        for w in inner.winfo_children():
            w.destroy()

        # Reminder summary
        n_fav = len(self._plugins_by_status("favorite"))
        n_like = len(self._plugins_by_status("like"))
        n_unt = len(self._plugins_by_status("untested"))
        n_dis = len(self._plugins_by_status("dislike"))
        favs = ", ".join(p["name"] for p in self._plugins_by_status("favorite")) or "—"
        self._plugin_reminder.config(
            text=f"Library: ♥ {n_fav}  ·  👍 {n_like}  ·  · {n_unt} untested  ·  👎 {n_dis}.   "
                 f"Don't forget your favourites: {favs}.   "
                 "Tag each plugin ♥/👍/👎 — disliked ones drop out of suggestions and the "
                 "inserts map. The () / (()) tag = how many channels it sits on.")

        # ---- ★ FOCUS: the tools you are actually working with right now ----
        # Pinned to the very top, in YOUR order, because a 70-entry library is a
        # library you scroll past. Click ★ on any row below to add/remove.
        focus_rows = []
        for want in self.focus_plugins:
            canon = focus_canonical(want).strip().lower()
            hit = next((p for p in self.plugins
                        if p.get("name", "").strip().lower() == canon), None)
            if hit is not None and hit not in focus_rows:
                focus_rows.append(hit)
        if focus_rows:
            fbox = tk.Frame(inner, bg=C_CARD, padx=10, pady=8)
            fbox.pack(fill="x", padx=8, pady=(6, 0))
            tk.Label(fbox, text="★ Your focus right now — these first, the rest when you need them",
                     bg=C_CARD, fg="#ffd479", font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(fill="x")
            tk.Label(fbox, text="Listed in chain order (top of the channel strip → bottom). "
                               "Click the ★ on any plugin row below to add or remove one.",
                     bg=C_CARD, fg=C_FG_DIM, font=("Segoe UI", 8),
                     wraplength=560, justify="left", anchor="w").pack(fill="x", pady=(0, 4))
            for p in sorted(focus_rows, key=plugin_chain):
                r = tk.Frame(fbox, bg=C_CARD)
                r.pack(fill="x", pady=(4, 0))
                tk.Label(r, text="★", bg=C_CARD, fg="#ffd479",
                         font=("Segoe UI", 9), width=2, anchor="nw").pack(side="left")
                col = tk.Frame(r, bg=C_CARD)
                col.pack(side="left", fill="x", expand=True)
                vend = f"   ·   {p['vendor']}" if p.get("vendor") else ""
                tk.Label(col, text=f"{p['name']}{vend}   ·   {p.get('kind','')}",
                         bg=C_CARD, fg=C_FG, font=("Segoe UI", 9, "bold"),
                         anchor="w").pack(fill="x")
                job = FOCUS_JOB.get(p["name"]) or p.get("note") or ""
                if job:
                    tk.Label(col, text=job, bg=C_CARD, fg=C_FG_DIM,
                             font=FONT_SMALL, wraplength=540, justify="left",
                             anchor="w").pack(fill="x")

        # ---- "You own this but never use it — here is what it would buy you" ----
        # Only the ★ ones, at the top, because a list of 12 maybes is a list you
        # never act on. Every plugin's full verdict still shows on its own row.
        starred = [p for p in self.plugins
                   if (plugin_verdict(p) or ("",))[0] == "use"]
        if starred:
            box = tk.Frame(inner, bg=C_CARD, padx=10, pady=8)
            box.pack(fill="x", padx=8, pady=(6, 0))
            tk.Label(box, text="★ Start using these — the real gaps in your chain",
                     bg=C_CARD, fg=C_BOOST, font=("Segoe UI", 10, "bold"),
                     anchor="w").pack(fill="x")
            for p in starred:
                _r, _l, colour, text = plugin_verdict(p)
                tk.Label(box, text=f"• {p['name']}"
                              + (f"  ({p['vendor']})" if p.get("vendor") else ""),
                         bg=C_CARD, fg=colour, font=("Segoe UI", 9, "bold"),
                         anchor="w").pack(fill="x", pady=(6, 0))
                tk.Label(box, text="   " + text, bg=C_CARD, fg=C_FG_DIM,
                         font=FONT_SMALL, wraplength=560, justify="left",
                         anchor="w").pack(fill="x")
            tk.Label(box, text="One at a time. Learn what it does to YOUR mixes before adding the "
                               "next — a plugin you half-understand is worse than no plugin.",
                     bg=C_CARD, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=560,
                     justify="left", anchor="w").pack(fill="x", pady=(8, 0))

        # Which plugins pass the filter?
        f = self._plugin_kind_filter
        status_map = {"♥ Favourites": "favorite", "👍 Liked": "like",
                      "· Untested": "untested", "👎 Disliked": "dislike",
                      "⚙ Core tools": "core"}
        def passes(p):
            if f == "All":
                return True
            if f == "★ Focus":
                return plugin_is_focus(p, self.focus_plugins)
            if f in status_map:
                return p.get("status") == status_map[f]
            if f.startswith("— "):
                return p.get("kind") == f[2:]
            return True
        shown = [p for p in self.plugins if passes(p)]

        # Group by kind, kinds ordered by chain position.
        kinds = sorted({p.get("kind", "Multi") for p in shown},
                       key=lambda k: PLUGIN_KIND_CHAIN.get(k, 50))
        if not shown:
            tk.Label(inner, text="\n  No plugins match this filter.",
                     bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL).pack(anchor="w", padx=10)
        for kind in kinds:
            tk.Label(inner, text=f"  {kind}", bg=C_BG3, fg=C_FG, font=FONT_HEADER,
                     anchor="w", padx=8).pack(fill="x", pady=(8, 0))
            # ★ focus tools sort to the top of their own kind, so the ones you
            # are learning are never buried under the ones you own.
            for p in sorted([x for x in shown if x.get("kind") == kind],
                            key=lambda x: (0 if plugin_is_focus(x, self.focus_plugins)
                                           else 1, x["name"].lower())):
                self._build_plugin_row(inner, p)

        self._bind_wheel(inner, self._plugins_wheel)

    def _build_plugin_row(self, parent, p):
        """One plugin row: status buttons · scope tag · name/vendor · link · edit/del,
        plus the program's VERDICT underneath when it has one ('should I actually
        be using this, and why?')."""
        row = tk.Frame(parent, bg=C_BG)
        row.pack(fill="x", padx=8, pady=1)
        is_core = (p.get("status") == "core")

        # Status controls
        if is_core:
            glyph, col, _ = PLUGIN_STATUS["core"]
            tk.Label(row, text=glyph, bg=C_BG, fg=col, font=("Segoe UI", 11),
                     width=6, anchor="w").pack(side="left")
        else:
            sb = tk.Frame(row, bg=C_BG)
            sb.pack(side="left")
            for st in ("favorite", "like", "dislike"):
                glyph, col, lbl = PLUGIN_STATUS[st]
                active = (p.get("status") == st)
                tk.Button(sb, text=glyph,
                          bg=(col if active else C_BG2),
                          fg=(C_BG if active else col),
                          activebackground=C_BG3, activeforeground=C_FG,
                          font=("Segoe UI", 9), relief="flat", bd=0, padx=3, pady=0,
                          cursor="hand2",
                          command=lambda q=p, s=st: self._set_plugin_status(q, s)).pack(side="left", padx=1)

        # ★ Focus toggle — pins this plugin to the box at the top of the tab.
        focused = plugin_is_focus(p, self.focus_plugins)
        tk.Button(row, text="★",
                  bg=("#ffd479" if focused else C_BG2),      # normal colour: C_BG2 = "#16213e"
                  fg=(C_BG if focused else "#ffd479"),
                  activebackground=C_BG3, activeforeground=C_FG,
                  font=("Segoe UI", 9), relief="flat", bd=0, padx=3, pady=0,
                  cursor="hand2",
                  command=lambda q=p: self._toggle_plugin_focus(q)).pack(side="left", padx=(4, 0))

        # Scope tag (click to cycle all → many → few)
        scope = p.get("scope", "many")
        tk.Button(row, text=f"[{scope}]",
                  bg=C_BG2, fg=C_ACCENT, activebackground=C_BG3, activeforeground=C_FG,
                  font=("Segoe UI", 8), relief="flat", bd=0, padx=4, pady=0,
                  cursor="hand2", width=7,
                  command=lambda q=p: self._cycle_plugin_scope(q)).pack(side="left", padx=(6, 4))

        # Name (with scope notation) + vendor
        name_col = C_FG if p.get("status") != "dislike" else C_FG_DIM
        nm = plugin_wrapped_name(p)
        vend = f"  ·  {p['vendor']}" if p.get("vendor") else ""
        lbl = tk.Label(row, text=nm + vend, bg=C_BG, fg=name_col,
                       font=FONT_NORMAL, anchor="w")
        lbl.pack(side="left", fill="x", expand=True)
        if p.get("note"):
            tk.Label(row, text="ⓘ", bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9),
                     cursor="hand2").pack(side="left")
            self._attach_tooltip(lbl, p["note"])

        # Right-side actions: edit, delete (user-added), link
        if p.get("url"):
            tk.Button(row, text="🔗", bg=C_BG, fg=C_ACCENT, activebackground=C_BG3,
                      activeforeground=C_FG, font=("Segoe UI", 9), relief="flat", bd=0,
                      cursor="hand2",
                      command=lambda u=p["url"]: self._open_url(u)).pack(side="right", padx=2)
        tk.Button(row, text="✎", bg=C_BG, fg=C_FG_DIM, activebackground=C_BG3,
                  activeforeground=C_FG, font=("Segoe UI", 9), relief="flat", bd=0,
                  cursor="hand2",
                  command=lambda q=p: self._add_plugin_dialog(q)).pack(side="right", padx=2)
        if not p.get("builtin", False):
            tk.Button(row, text="🗑", bg=C_BG, fg=C_CUT, activebackground=C_BG3,
                      activeforeground=C_FG, font=("Segoe UI", 9), relief="flat", bd=0,
                      cursor="hand2",
                      command=lambda q=p: self._delete_plugin(q)).pack(side="right", padx=2)

        # ---- Verdict: the "should I use this?" answer, if we have one ----
        v = plugin_verdict(p)
        if v:
            _rank, label, colour, text = v
            vr = tk.Frame(parent, bg=C_BG)
            vr.pack(fill="x", padx=8, pady=(0, 3))
            tk.Label(vr, text="        " + label, bg=C_BG, fg=colour,
                     font=("Segoe UI", 8, "bold"), anchor="nw",
                     width=18).pack(side="left")
            tk.Label(vr, text=text, bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=520, justify="left", anchor="nw").pack(
                         side="left", fill="x", expand=True)

    def _attach_tooltip(self, widget, text):
        """Lightweight hover tooltip (fixed, non-blinking)."""
        tip = {"win": None}
        def show(_e=None):
            if tip["win"] or not text:
                return
            t = tk.Toplevel(widget)
            t.overrideredirect(True)
            t.configure(bg=C_BG3)
            tk.Label(t, text=text, bg=C_BG3, fg=C_FG, font=FONT_SMALL,
                     wraplength=320, justify="left", padx=8, pady=5).pack()
            x = widget.winfo_rootx() + 10
            y = widget.winfo_rooty() + widget.winfo_height() + 4
            t.geometry(f"+{x}+{y}")
            tip["win"] = t
        def hide(_e=None):
            if tip["win"]:
                tip["win"].destroy()
                tip["win"] = None
        widget.bind("<Enter>", show)
        widget.bind("<Leave>", hide)

    def _set_plugin_status(self, p, status):
        """Set a plugin's status; clicking the active one again clears to untested."""
        p["status"] = "untested" if p.get("status") == status else status
        self._persist_plugins()
        self._refresh_plugins_list()
        self._refresh_summary()    # inserts map / suggestions may change

    def _toggle_plugin_focus(self, p):
        """Add/remove a plugin from the ★ focus set (remembered between runs)."""
        name = p.get("name", "")
        if plugin_is_focus(p, self.focus_plugins):
            self.focus_plugins = [x for x in self.focus_plugins
                                  if focus_canonical(x).strip().lower()
                                  != name.strip().lower()]
        else:
            self.focus_plugins.append(name)
        self.settings["focus_plugins"] = list(self.focus_plugins)
        self._save_current_settings()
        self._refresh_plugins_list()
        self._refresh_summary()     # the insert map stars change too

    def _cycle_plugin_scope(self, p):
        p["scope"] = PLUGIN_SCOPE_NEXT.get(p.get("scope", "many"), "many")
        self._persist_plugins()
        self._refresh_plugins_list()
        self._refresh_summary()

    def _delete_plugin(self, p):
        from tkinter import messagebox
        if p.get("builtin", False):
            return
        if not messagebox.askyesno(APP_NAME, f"Delete '{p['name']}' from your library?"):
            return
        self.plugins = [x for x in self.plugins if x is not p]
        self._persist_plugins()
        self._refresh_plugins_list()
        self._refresh_summary()

    def _add_plugin_dialog(self, existing=None):
        """Add a new plugin, or edit an existing one (pass the dict). Enter saves,
        Esc cancels. Built-in entries keep their name read-only."""
        editing = existing is not None
        p = existing or {}
        top = tk.Toplevel(self.root)
        top.title("Edit plugin" if editing else "Add plugin")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        top.transient(self.root)

        rows = tk.Frame(top, bg=C_BG3, padx=16, pady=12)
        rows.pack(fill="both", expand=True)

        def field(label, r):
            tk.Label(rows, text=label, bg=C_BG3, fg=C_FG, font=FONT_NORMAL,
                     anchor="w").grid(row=r, column=0, sticky="w", pady=3, padx=(0, 8))

        # Name
        field("Name", 0)
        name_var = tk.StringVar(value=p.get("name", ""))
        name_e = tk.Entry(rows, textvariable=name_var, bg=C_BG2, fg=C_FG,
                          insertbackground=C_FG, insertofftime=0, insertontime=9999999,
                          relief="flat", font=FONT_NORMAL, width=34)
        name_e.grid(row=0, column=1, sticky="we", pady=3)
        if p.get("builtin"):
            name_e.configure(state="readonly")     # don't rename a built-in entry

        # Vendor
        field("Vendor", 1)
        vendor_var = tk.StringVar(value=p.get("vendor", ""))
        tk.Entry(rows, textvariable=vendor_var, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0, insertontime=9999999,
                 relief="flat", font=FONT_NORMAL, width=34).grid(row=1, column=1, sticky="we", pady=3)

        # Kind
        field("Kind / type", 2)
        kind_var = tk.StringVar(value=p.get("kind", "Multi"))
        km = tk.OptionMenu(rows, kind_var, *PLUGIN_KINDS)
        km.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG,
                     highlightthickness=0, bd=0, font=FONT_SMALL, relief="flat", cursor="hand2")
        km["menu"].configure(bg=C_BG, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG)
        km.grid(row=2, column=1, sticky="w", pady=3)

        # Scope
        field("Used on", 3)
        scope_var = tk.StringVar(value=p.get("scope", "many"))
        sm = tk.OptionMenu(rows, scope_var, "all", "many", "few")
        sm.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG,
                     highlightthickness=0, bd=0, font=FONT_SMALL, relief="flat", cursor="hand2")
        sm["menu"].configure(bg=C_BG, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG)
        sm.grid(row=3, column=1, sticky="w", pady=3)
        tk.Label(rows, text="all = (almost) every channel · many = (Name) · few = ((Name))",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL).grid(row=4, column=1, sticky="w")

        # Status
        field("I…", 5)
        status_var = tk.StringVar(value=p.get("status", "untested")
                                  if p.get("status") in PLUGIN_STATUS_PICK else "untested")
        stm = tk.OptionMenu(rows, status_var, *PLUGIN_STATUS_PICK)
        stm.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG,
                      highlightthickness=0, bd=0, font=FONT_SMALL, relief="flat", cursor="hand2")
        stm["menu"].configure(bg=C_BG, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG)
        stm.grid(row=5, column=1, sticky="w", pady=3)

        # URL
        field("Link (URL)", 6)
        url_var = tk.StringVar(value=p.get("url", ""))
        tk.Entry(rows, textvariable=url_var, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0, insertontime=9999999,
                 relief="flat", font=FONT_NORMAL, width=34).grid(row=6, column=1, sticky="we", pady=3)

        # Note
        field("Note", 7)
        note_var = tk.StringVar(value=p.get("note", ""))
        tk.Entry(rows, textvariable=note_var, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0, insertontime=9999999,
                 relief="flat", font=FONT_NORMAL, width=34).grid(row=7, column=1, sticky="we", pady=3)

        rows.grid_columnconfigure(1, weight=1)

        btns = tk.Frame(top, bg=C_BG3, padx=16, pady=(0, 14))
        btns.pack(fill="x")

        def _save(_e=None):
            from tkinter import messagebox
            name = name_var.get().strip()
            if not name:
                messagebox.showinfo(APP_NAME, "Please enter a name.")
                return
            if p.get("builtin"):
                # built-in: keep core status; only edit scope/kind/url/note/vendor
                p["vendor"] = vendor_var.get().strip()
                p["kind"]   = kind_var.get()
                p["scope"]  = scope_var.get()
                p["url"]    = url_var.get().strip()
                p["note"]   = note_var.get().strip()
                if p.get("status") != "core":
                    p["status"] = status_var.get()
            else:
                data = _normalize_plugin({
                    "name": name, "vendor": vendor_var.get().strip(),
                    "kind": kind_var.get(), "status": status_var.get(),
                    "scope": scope_var.get(), "url": url_var.get().strip(),
                    "note": note_var.get().strip(), "builtin": False})
                if editing:
                    p.update(data)
                else:
                    self.plugins.append(data)
            self._persist_plugins()
            self._refresh_plugins_list()
            self._refresh_summary()
            top.destroy()
            self._toast("Saved." if editing else f"Added {name}.")

        def _cancel(_e=None):
            top.destroy()

        tk.Button(btns, text="Save", command=_save,
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG, activeforeground=C_FG,
                  relief="flat", padx=14, pady=3, cursor="hand2").pack(side="right", padx=(6, 0))
        tk.Button(btns, text="Cancel", command=_cancel,
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG, activeforeground=C_FG,
                  relief="flat", padx=14, pady=3, cursor="hand2").pack(side="right")

        top.bind("<Return>", _save)
        top.update_idletasks()
        x = self.root.winfo_rootx() + (self.root.winfo_width() - top.winfo_width()) // 2
        y = self.root.winfo_rooty() + (self.root.winfo_height() - top.winfo_height()) // 3
        top.geometry(f"+{max(x, 0)}+{max(y, 0)}")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", _cancel)
        if not p.get("builtin"):
            name_e.focus_set()
        top.wait_window()

    def _pending_banner(self, parent):
        """The one line that stops a held panel from looking like a fresh
        one. Click it and it updates — the same as the button."""
        bits = self._pending_bits()
        if not bits:
            return
        marks = {"+": "+", "-": "−", "#": "✖", "&": "⛓", "~": "\U0001f3bb"}
        names = ",  ".join("%s %s" % (marks.get(m, m), _stage_name(i))
                           for m, i in bits[:5])
        if len(bits) > 5:
            names += ",  +%d more" % (len(bits) - 5)
        f = tk.Frame(parent, bg=C_UPD_WAIT, padx=8, pady=4, cursor="hand2")
        f.pack(fill="x", padx=6, pady=(4, 6))
        tk.Label(f, text="⟳  %d change%s waiting — this panel still shows "
                         "the line-up you last clicked Update on."
                      % (len(bits), "" if len(bits) == 1 else "s"),
                 bg=C_UPD_WAIT, fg="#ffffff",   # normal colour: C_UPD_WAIT (amber)
                 font=("Segoe UI", 8, "bold"), wraplength=460,
                 justify="left", anchor="w").pack(fill="x")
        tk.Label(f, text=names, bg=C_UPD_WAIT, fg="#ffe9c8", font=FONT_SMALL,
                 wraplength=460, justify="left", anchor="w").pack(fill="x")
        for w in (f,) + tuple(f.winfo_children()):
            w.bind("<Button-1>", lambda e: self._do_update())

    def _toast(self, msg):
        """Tiny auto-closing confirmation (1 s)."""
        try:
            top = tk.Toplevel(self.root)
            top.configure(bg=C_BG3)
            top.overrideredirect(True)
            tk.Label(top, text=msg, bg=C_BG3, fg=C_FG,
                     font=FONT_NORMAL, padx=16, pady=8).pack()
            top.update_idletasks()
            x = self.root.winfo_rootx() + self.root.winfo_width() // 2 - top.winfo_width() // 2
            y = self.root.winfo_rooty() + 60
            top.geometry(f"+{max(x, 0)}+{max(y, 0)}")
            top.after(1000, top.destroy)
        except Exception:
            pass

    # ---- SUMMARY PANEL (RIGHT) ----------------------------------------------

    def _build_summary(self, parent):
        """Right panel: header + scrollable summary of checked instruments."""
        # Header
        hdr = tk.Frame(parent, bg=C_BG3, pady=6, padx=10)
        hdr.pack(fill="x")
        # v3.29: the fold button sits at the far left of this header, so it never moves while
        # the left side comes and goes.
        self.fold_btn = tk.Button(hdr, text="◀ Fold left side", bg=C_BTN, fg=C_BTN_FG,
                                  activebackground=C_BG, activeforeground=C_FG,
                                  font=FONT_SMALL, relief="flat", padx=8, pady=2,
                                  width=16, cursor="hand2", command=self._toggle_left_fold)
        self.fold_btn.pack(side="left", padx=(0, 10))
        tk.Label(hdr, text="📋  Selected Instruments",
                 bg=C_BG3, fg=C_FG, font=FONT_HEADER).pack(side="left")
        self.sel_count_lbl = tk.Label(hdr, text="(0)",
                                       bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL)
        self.sel_count_lbl.pack(side="left", padx=6)

        clear_btn = tk.Button(hdr, text="Clear all",
                              bg=C_BTN, fg=C_BTN_FG,  # change colour: C_BTN = "#0f3460"
                              activebackground=C_BG, activeforeground=C_FG,
                              font=FONT_SMALL, relief="flat", padx=8, pady=2,
                              cursor="hand2", command=self._clear_all)
        clear_btn.pack(side="right")

        # v3.35: the song's ROOM SIZE (Virtual Stage; the same on every instance) right under the
        # 'Selected Instruments (n)' title, so it is found at a glance instead of by hunting through the cards. A fixed-width
        # label: the header never changes size because of the text. SWAM parts have their own room
        # (they leave Virtual Stage) - that one is shown beside it when the song has any.
        # (It sits on its own thin strip directly under the header: at the normal window size the
        # header line itself is only ~475 px wide and already full - a button there was cut off.)
        info_strip = tk.Frame(parent, bg=C_BG3, padx=10, pady=0)
        info_strip.pack(fill="x")
        # Two fixed lines: 1 = the Virtual Stage room, 2 = the SWAM room (Room Sizes + Absorption;
        # Room Type never changes, so it is not shown).
        self.room_info_lbl = tk.Label(info_strip, text="", bg=C_BG3, fg=VSTAGE_COLOUR,
                                      font=("Segoe UI", 9, "bold"), width=34, height=2,
                                      anchor="nw", justify="left")
        self.room_info_lbl.pack(side="left", pady=(0, 4))
        btn_col = tk.Frame(info_strip, bg=C_BG3)
        btn_col.pack(side="right", pady=(0, 4))
        # v3.36: everything about the song (line-up, pairs, stage, SWAM room) as text on the clipboard,
        # to paste into a chat.
        self.copy_info_btn = tk.Button(btn_col, text="\U0001f4cb Copy info", bg=C_BTN, fg=C_BTN_FG,
                                       activebackground=C_BG, activeforeground=C_FG,
                                       font=FONT_SMALL, relief="flat", padx=8, pady=1, width=15,
                                       cursor="hand2", command=self._copy_info)
        self.copy_info_btn.pack(side="top")
        # v3.35: ends Steinberg's MediaBay background process so Cubase re-reads the preset folders.
        self.mediabay_btn = tk.Button(btn_col, text="☠ Kill MediaBay", bg=C_BTN, fg=C_BTN_FG,
                                      activebackground=C_BG, activeforeground=C_FG,
                                      font=FONT_SMALL, relief="flat", padx=8, pady=1, width=15,
                                      cursor="hand2", command=self._kill_mediabay)
        self.mediabay_btn.pack(side="top", pady=(2, 0))

        # View selector. The compact "Channel Plan" is the DEFAULT view; the other
        # two are the per-instrument detail summary and the effect-sorting view.
        # The two Group-placement popups stay in this panel; everything that used to
        # be a 'Selected / All' button (Overview + all preset generation) now lives
        # in the new "Generate" menu next to File / Help.
        view_row = tk.Frame(parent, bg=C_BG2, padx=8, pady=4)
        view_row.pack(fill="x")
        tk.Label(view_row, text="View:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(0, 4))
        self._view_btns = {}
        for mode, label in [("channelplan", "📐 Channel Plan"),
                            ("instruments", "📋 Instruments"),
                            ("effects",     "🔀 Effects")]:
            b = tk.Button(view_row, text=label,
                          bg=C_BTN, fg=C_BTN_FG,   # active state is set in _sync_view_buttons
                          activebackground=C_BG, activeforeground=C_FG,
                          font=FONT_SMALL, relief="flat", padx=8, pady=3, cursor="hand2",
                          command=lambda m=mode: self._set_right_mode(m))
            b.pack(side="left", padx=2)
            self._view_btns[mode] = b

        # ⇅ ORDER — the one button that swaps how the two list views are sorted.
        # Deliberately NOT in _panel_extra_btns: the focus view is exactly where
        # you need it, so it stays on the row when the four popups are unpacked.
        # The label says what you are looking at now, not what the click does —
        # the same way the three View buttons above name the view they show.
        tk.Label(view_row, text="│", bg=C_BG2, fg=C_SEP,
                 font=FONT_SMALL).pack(side="left", padx=(6, 2))
        self.order_btn = tk.Button(view_row, text="⇅ Pick order",
                                   bg=C_BTN, fg=C_BTN_FG,
                                   activebackground=C_BG, activeforeground=C_FG,
                                   font=FONT_SMALL, relief="flat", padx=8, pady=3,
                                   cursor="hand2", command=self._toggle_list_order)
        self.order_btn.pack(side="left", padx=2)

        # ✋ STAGE + 🏠 ROOM - right after "Pick order", and (like it) NOT in
        # _panel_extra_btns, so the 🔎 focus view keeps them: "latthittad".
        self.stage_hand_btn = tk.Button(
            view_row, text="✋ Stage", bg=C_GROUND_BTN, fg=C_BTN_FG,
            activebackground=C_BG, activeforeground=C_FG, font=FONT_SMALL,
            relief="flat", padx=8, pady=3, cursor="hand2",
            command=self._show_stage_manual)
        self.stage_hand_btn.pack(side="left", padx=2)
        self.room_btn = tk.Button(
            view_row, text="🏠 Room: Auto", bg=C_BTN, fg=C_BTN_FG,
            activebackground=C_BG, activeforeground=C_FG, font=FONT_SMALL,
            relief="flat", padx=8, pady=3, cursor="hand2",
            command=self._pick_room_menu)
        self.room_btn.pack(side="left", padx=2)
        # v3.27: the same Save as in Song Variants, right where you are looking when you
        # have just picked the room.
        self.save_here_btn = tk.Button(
            view_row, text="\U0001f4be Save", bg=C_BTN, fg=C_BTN_FG,
            activebackground=C_BG, activeforeground=C_FG, font=FONT_SMALL,
            relief="flat", padx=8, pady=3, cursor="hand2", command=self._var_save)
        self.save_here_btn.pack(side="left", padx=2)
        # v3.28: and ⟳ Update after it - the same one as in Song Variants.
        self.update_btn2 = tk.Button(
            view_row, text="⟳ Update", bg=C_UPD_IDLE, fg=C_BTN_FG,
            activebackground=C_BG, activeforeground=C_FG, font=FONT_SMALL,
            relief="flat", padx=8, pady=3, cursor="hand2", command=self._do_update)
        self.update_btn2.pack(side="left", padx=2)

        # Group-placement popups — kept here in the right panel, as requested.
        # The 🔎 focus view unpacks all four (they are on the View / Generate /
        # Help menus too), so each one is remembered together with the pack()
        # call that put it there. Build order = right-to-left on the row.
        self._panel_extra_btns = []

        def _extra(text, colour, cmd, pack_kw):
            b = tk.Button(view_row, text=text,
                          bg=colour, fg=C_BTN_FG,
                          activebackground=C_BG, activeforeground=C_FG,
                          font=FONT_SMALL, relief="flat", padx=8, pady=3,
                          cursor="hand2", command=cmd)
            b.pack(**pack_kw)
            self._panel_extra_btns.append((b, pack_kw))

        _extra("🌫 Reverb Groups",   "#2d4a5a",   # change colour here (teal-ish)
               self._show_smartreverb_groups, {"side": "right", "padx": (6, 0)})
        _extra("🎯 smart:EQ Groups", "#2d5a3a",   # change colour here (green-ish)
               self._show_smarteq_groups,     {"side": "right"})
        _extra("🗺 Roadmap",         "#5a4a2d",   # change colour here (amber-ish)
               self._show_roadmap,            {"side": "right", "padx": (0, 6)})
        _extra("🦻 My rules",        "#5a3a52",   # change colour here (plum-ish)
               self._show_hearing_rules,      {"side": "right", "padx": (0, 6)})

        # Legend
        leg = tk.Frame(parent, bg=C_BG2, padx=8, pady=4)
        leg.pack(fill="x")
        for label, color in [("BOOST", C_BOOST), ("CUT", C_CUT), ("TRY", C_CHAR), ("NEUTRAL", C_NEUTRAL)]:
            tk.Label(leg, text="●", fg=color, bg=C_BG2, font=("Segoe UI", 10)).pack(side="left")
            tk.Label(leg, text=label, fg=color, bg=C_BG2, font=FONT_SMALL).pack(side="left", padx=(0, 8))

        # Instrument-section filter — ONLY relevant (and shown) in the 📋 Instruments
        # view; see _sync_view_buttons() for the show/hide. Default = nothing ticked
        # = every section shows, same as always. Tick one or more categories to show
        # ONLY those sections in every instrument block below — a quick way to scan
        # e.g. just Comp. or just Reverb settings across many channels. "Reset"
        # clears all ticks back to the default (show everything).
        saved_filters = self.settings.get("instr_filters", ["eqgroup", "duck", "reverb"])
        if not isinstance(saved_filters, list):
            saved_filters = []
        # Settings written before the five "set & forget" boxes became one:
        # any of the old section keys in the file ticks the single new box, so
        # an older settings file opens looking the way it was left.
        saved_filters = set(saved_filters)
        for key, members in self.INSTR_FILTER_EXPAND.items():
            if saved_filters & set(members):
                saved_filters.add(key)
        self._instr_filter_vars = {key: tk.BooleanVar(value=(key in saved_filters))
                                   for key, _ in self.INSTR_FILTERS}
        self.instr_filter_frame = tk.Frame(parent, bg=C_BG2, padx=8, pady=4)
        tk.Label(self.instr_filter_frame, text="Filter:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(0, 4))
        for key, label in self.INSTR_FILTERS:
            if key == "submass":
                # 'Details' is NOT a section filter - it only decides whether the
                # lines of preset-set values (Crossovers, Low cut, Unmask,
                # Side-chain ...) are drawn. Off by default.
                tk.Checkbutton(self.instr_filter_frame, text="Details",
                               variable=self.details_var,
                               bg=C_BG2, fg=C_FG, selectcolor=C_BG3,
                               activebackground=C_BG2, activeforeground=C_FG,
                               font=FONT_SMALL, cursor="hand2",
                               command=self._on_details_toggle).pack(side="left", padx=(0, 2))
            tk.Checkbutton(self.instr_filter_frame, text=label,
                          variable=self._instr_filter_vars[key],
                          bg=C_BG2, fg=C_FG, selectcolor=C_BG3,
                          activebackground=C_BG2, activeforeground=C_FG,
                          font=FONT_SMALL, cursor="hand2",
                          command=self._on_instr_filter_toggle).pack(side="left", padx=(0, 2))
        tk.Button(self.instr_filter_frame, text="Reset",
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=8, pady=2, cursor="hand2",
                  command=self._reset_instr_filters).pack(side="left", padx=(8, 0))
        # ---- how much prose, right here on the row you read -----------------
        # These two also live in the View menu, but this is the strip you are
        # already looking at when the panel feels too long, so they belong on
        # it. Same variables, so the menu and these stay in step by themselves.
        tk.Label(self.instr_filter_frame, text="│", bg=C_BG2,
                 fg=C_SEP, font=FONT_SMALL).pack(side="left", padx=(8, 4))
        tk.Checkbutton(self.instr_filter_frame, text="💬 Why-lines",
                       variable=self.extra_comments_var,
                       bg=C_BG2, fg=C_FG_DIM, selectcolor=C_BG3,
                       activebackground=C_BG2, activeforeground=C_FG,
                       font=FONT_SMALL, cursor="hand2",
                       command=self._on_comment_setting_change).pack(side="left")
        tk.Checkbutton(self.instr_filter_frame, text="↕ Compact",
                       variable=self.hide_empty_var,
                       bg=C_BG2, fg=C_FG_DIM, selectcolor=C_BG3,
                       activebackground=C_BG2, activeforeground=C_FG,
                       font=FONT_SMALL, cursor="hand2",
                       command=self._on_comment_setting_change).pack(side="left")
        # Δ belongs on this strip more than any of them: it is the switch you
        # reach for while you are reading the panel and wondering which of
        # these nine plug-ins you have to open.
        tk.Checkbutton(self.instr_filter_frame, text="Δ Only what differs",
                       variable=self.default_diff_var,
                       bg=C_BG2, fg=C_DIFF, selectcolor=C_BG3,
                       activebackground=C_BG2, activeforeground=C_FG,
                       font=FONT_SMALL, cursor="hand2",
                       command=self._on_default_diff_change).pack(side="left")
        tk.Button(self.instr_filter_frame, text="📐 Defaults",
                  bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                  activeforeground=C_FG, font=FONT_SMALL, relief="flat",
                  padx=8, pady=2, cursor="hand2",
                  command=self._show_defaults).pack(side="left", padx=(6, 0))
        # Not packed here on purpose — _sync_view_buttons() packs/hides it
        # depending on the active view, so it stays out of the way elsewhere.

        self._summary_sep = tk.Frame(parent, bg=C_SEP, height=1)
        self._summary_sep.pack(fill="x")
        self._sync_view_buttons()

        # Scrollable canvas
        canvas = tk.Canvas(parent, bg=C_BG2, bd=0, highlightthickness=0)
        vsb = tk.Scrollbar(parent, orient="vertical", command=canvas.yview,
                           bg=C_BG2, troughcolor=C_BG2, activebackground=C_ACCENT)
        canvas.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)

        self.summary_canvas = canvas
        self.summary_inner  = tk.Frame(canvas, bg=C_BG2)
        self.summary_win_id = canvas.create_window((0, 0), window=self.summary_inner, anchor="nw")

        def _cfg(e):
            canvas.configure(scrollregion=canvas.bbox("all"))

        def _resize(e):
            canvas.itemconfig(self.summary_win_id, width=e.width)

        self.summary_inner.bind("<Configure>", _cfg)
        canvas.bind("<Configure>", _resize)
        canvas.bind("<MouseWheel>", lambda e: self._scroll_summary(e))

        self._refresh_summary()

    # ---- v3.25: THE PANEL FOLLOWS WHAT YOU TOUCHED, AND NEVER SHOWS A BIG EMPTY AREA ----
    def _mark_focus(self, iid):
        """Remember the instrument you changed last, wherever you changed it (a card,
        the picker, the panel itself). The panel scrolls to it after every redraw."""
        base = str(iid or "").partition("#")[0]
        if base:
            self._focus_iid = base

    def _summary_anchor_y(self):
        """Top of the focused instrument's row/block inside the panel, or None."""
        iid = getattr(self, "_focus_iid", None)
        inner = getattr(self, "summary_inner", None)
        if not iid or inner is None:
            return None
        name = next((x["name"] for x in EQ_DATA if x["id"] == iid), None)
        if not name:
            return None
        pat = re.compile(r"^%s(\s+\u2716\d+)?$" % re.escape(name))

        def find(w):
            for c in w.winfo_children():
                if isinstance(c, tk.Label):
                    t = str(c.cget("text")).replace("\u25cf", "").strip()
                    if pat.match(t):
                        return c
                f = find(c)
                if f is not None:
                    return f
            return None

        lab = find(inner)
        if lab is None:
            return None
        y, w = 0, lab
        while w is not None and w is not inner:
            y += w.winfo_y()
            w = w.master
        return y

    def _summary_settle(self, top_if_none=False):
        """After the panel was rebuilt: fit the scroll area to the content, jump to
        the instrument touched last, and never leave the view past the end (that is
        the big empty space after switching to a shorter view or filter)."""
        cv = getattr(self, "summary_canvas", None)
        inner = getattr(self, "summary_inner", None)
        if cv is None or inner is None:
            return
        try:
            cv.update_idletasks()
            h = max(1, inner.winfo_reqheight())
            w = max(1, inner.winfo_reqwidth())
            cv.configure(scrollregion=(0, 0, w, h))
            ch = cv.winfo_height()
            y = self._summary_anchor_y()
            if y is not None:
                cv.yview_moveto(max(0, y - 14) / float(h))
            elif top_if_none:
                cv.yview_moveto(0)
            if h <= ch:
                cv.yview_moveto(0)
            elif cv.canvasy(0) + ch > h:
                cv.yview_moveto((h - ch) / float(h))
        except tk.TclError:
            pass

    def _scroll_summary(self, event):
        try:
            self.summary_canvas.yview_scroll(max(1, abs(round(event.delta / 40))) * (-1 if event.delta > 0 else 1), "units")
        except Exception:
            pass

    # ---- CONTEXT-AWARE PER-INSTRUMENT RECOMMENDATIONS -----------------------
    # These turn the right panel from "static defaults" into "exactly what to set
    # for THIS combination of instruments".
    RHYTHM_LOW_IDS = {"kick", "snare", "hihat", "ride", "cymbals", "toms", "percussion",
                      "bass_root", "bass_loop", "double_bass", "double_bass_section"}
    # Who wins the 3–5 kHz presence zone when several melodic parts compete:
    LEAD_PRIORITY = ["vocals_lead", "guitar_lead", "piano_riff", "organ_lead", "organ_melody",
                     "brass_lead", "strings_lead", "violin", "viola_front", "flute",
                     "accordion_lead", "accordion", "brass", "synth_pluck", "synth_mallet",
                     "guitar_single_low"]

    # Default pan position per instrument (starting point; refined by context below).
    PAN_BASE = {
        "kick": "Centre", "snare": "Centre",
        "bass_root": "Centre (keep lows mono)", "bass_loop": "Centre (keep lows mono)",
        "double_bass": "Centre", "double_bass_section": "Centre (keep lows mono)",
        "toms": "Spread (floor L → rack R)",
        "hihat": "Slightly off-centre (~20–30% R)", "cymbals": "Wide L+R (overheads)",
        "ride": "Slightly off-centre (~20–30%, like the hi-hat)",
        "percussion": "Off-centre, opposite the hi-hat",
        "vocals_lead": "Centre", "vocals_backing": "Wide — hard-pan doubles L/R; harmonies only ~10% off centre",
        "vocals_choir_pad": "Wide stereo",
        "vocals_extra": "Wide - or one side, opposite the backing vocals",
        "organ": "Off-centre",
        "organ_lead": "Centre–slightly off (it is a lead) — same side as the background organ",
        "organ_melody": "A step off-centre - between the lead organ and the bed, same side as the background organ",
        "brass_lead": "Centre–slightly off (it is a lead), in from the horn row",
        "accordion_lead": "Centre–slightly off (it is a lead) — same side as the padding accordion",
        "flute_bg": "Well off-centre (a bed, not the solo flute)",
        "violin_bg": "Well off-centre (a bed, not the solo violin)",
        "strings_lead": "Centre–slightly off (it is a lead) — much narrower than the section bed",
        "accordion": "Off-centre (opposite the organ/piano)",
        "piano_bg": "Off-centre", "piano_riff": "Off-centre",
        "guitar_rhythm": "Off-centre", "guitar_chords": "Off-centre",
        "guitar_lead": "Centre (or slightly off)", "guitar_single_low": "Centre–slightly off",
        "synth_pad": "Wide stereo", "synth_pluck": "Off-centre (or ping-pong)",
        "synth_mallet": "Off-centre (opposite the cymbals)",
        "guitar_acoustic": "Off-centre (opposite the electrics)",
        "flute": "Slightly off-centre", "brass": "Slightly off-centre / section spread",
        "trumpet": "Off-centre (~30–40%, clear of the vocal)",
        "trombone": "Off-centre, opposite the trumpet",
        "tenor_trombone": "Off-centre, opposite the trumpet",
        "tenor_bass_trombone": "Off-centre, opposite the trumpet",
        "saxophone": "Off-centre (~30–40%, opposite the trumpet)",
        "horn_section": "Spread (bone L → sax centre-ish → trumpet R)",
        "harmonica": "Off-centre (~30%, opposite the lead guitar)",
        "woodwind": "Slightly off-centre",
        "clarinet": "Slightly right of centre (centre-right of the wind row)",
        "oboe": "Slightly left of centre (centre-left of the wind row)",
        "bassoon": "Right of centre, low end centred",
        "contrabassoon": "Centre (keep lows mono)",
        "flugelhorn": "Off-centre (~30%, next to the trumpet)",
        "french_horn": "Slightly off-centre, back of the horn row",
        "tuba": "Centre (keep lows mono)",
        "english_horn": "Slightly left of centre, next to the oboe",
        "euphonium": "Slightly off-centre, low end centred",
        "bass_clarinet": "Right of centre, low end centred",
        "contrabass_clarinet": "Centre (keep lows mono)",
        "piccolo": "Off-centre (~30%, opposite the hi-hat)",
        "alto_flute": "Slightly off-centre",
        "bass_flute": "Slightly off-centre",
        "soprano_sax": "Off-centre (~30-40%, opposite the trumpet)",
        "alto_sax": "Off-centre (~30-40%, opposite the trumpet)",
        "tenor_sax": "Off-centre (~30-40%, opposite the trumpet)",
        "baritone_sax": "Centre-right, low end centred",
        "piccolo_trumpet": "Off-centre (~30-40%, clear of the vocal)",
        "alto_trombone": "Off-centre, opposite the trumpet",
        "bass_trombone": "Centre-left, low end centred",
        "double_bass_trombone": "Centre-left, low end centred",
        "violin": "Off-centre / section spread", "viola": "Off-centre",
        "viola_front": "Centre–slightly off (it carries the tune) — closer and narrower than the viola bed",
        "cello": "Slightly off-centre", "string_section": "Wide stereo",
    }

    # Plain-language meaning of the pan terms that aren't a single L–R knob
    # position. Shown in the Pan effect view and in Help.
    PAN_TERMS = [
        ("Spread",
         "ONE part recorded with several mics, panned so each piece sits where it "
         "is on the kit. For TOMS: floor tom hard-ish LEFT, rack toms toward RIGHT "
         "(your guess is right) — a left-to-right sweep across the drums."),
        ("Wide L+R",
         "A STEREO PAIR (overheads / room mics): its two channels go hard LEFT and "
         "hard RIGHT, so the kit gets full stereo width instead of one point."),
        ("Wide stereo",
         "A naturally stereo source (pad, choir, doubles): spread it well out to "
         "both sides — not a single pan position."),
        ("Off-centre",
         "Nudged a bit to one side (~20–40%, not hard) to clear the centre for the "
         "lead vocal/kick/snare/bass."),
    ]

    # ---- KIRCHHOFF STEREO MODE (Mid/Side) PER INSTRUMENT --------------------
    # Numbers-first guidance for getting AIR, SPACE/WIDTH and CLARITY (no mud)
    # WITHOUT having to A/B by ear. Each Kirchhoff band can run on:
    #   Stereo (L+R) · Left · Right · Mid (centre) · Side (the wide/stereo part).
    # Cheat-codes baked in:
    #   • AIR / SPACE  = a Side high-shelf boost above ~10 kHz (+2…+3 dB).
    #   • KEEP IT TIGHT = high-pass the SIDE low end (lows stay mono/centred).
    #   • NO PORRIDGE  = cut 200–500 Hz in MID (cleans the centre, keeps width).
    # Mono/centre sources have (almost) no Side, so there M/S does little —
    # work them in Stereo or Mid and just keep the lows mono.
    STEREO_MODE = {
        "kick":            "Mono → Stereo/Mid only. No usable Side. Keep dead centre.",
        "snare":           "Mostly Mono → Stereo/Mid. Stereo room/OH? Side high-shelf +2 dB @10 kHz for a little spread.",
        "toms":            "Mono → Stereo/Mid.",
        "percussion":      "Often stereo → Side high-shelf +2…+3 dB @10 kHz for sparkle/width; keep Mid clean.",
        "bass_root":       "Keep lows MONO → high-pass the SIDE @120 Hz; do body/tone in MID.",
        "bass_loop":       "Keep lows MONO → high-pass the SIDE @150 Hz; EQ in MID.",
        "double_bass":     "Keep lows MONO → high-pass the SIDE @120 Hz; body in MID.",
        "vocals_lead":     "Centre → work in MID (all cuts/boosts). Leave the Side clean.",
        "vocals_backing":  "WIDTH lives here → SIDE high-shelf +3 dB @10 kHz to spread the doubles; MID cut −3 dB @200–400 Hz.",
        "vocals_choir_pad":"WIDE pad → SIDE air +3 dB @10 kHz (space); MID cut −4 dB @400–800 Hz (de-mud); high-pass SIDE @150 Hz.",
        "vocals_extra":    "Colour layer → SIDE air +2 dB @10 kHz; MID cut −4 dB @250–500 Hz; keep any trailing WORD in the MID so its consonants stay clear.",
        "organ":           "Rotary = stereo → SIDE +2…+3 dB @6–8 kHz (width); MID cut −3 dB @300–600 Hz so it leaves the centre.",
        "accordion_lead":  "A lead is a CENTRE part → the 800 Hz–2 kHz reed core and the 2–4 kHz lift both go in MID. Leave the treble/bass-side stereo trick to the padding accordion; width is what puts it behind the singer.",
        "flute_bg":        "One player holding a note → mostly MID. There is no Side to work with unless you doubled the take; if you did, SIDE +2 dB @10 kHz and keep the 800 Hz–2 kHz core in MID.",
        "violin_bg":       "One player holding a note → MID, including the 1–3 kHz CUT. Doubled? SIDE +2 dB @10 kHz for width, and high-pass the SIDE @300 Hz so the bed stays out of the centre's way.",
        "brass_lead":      "A line, not a block → work in MID: the 1.5–3 kHz core, the honk cut, the blare cut. A sampled section can keep a little SIDE air above 8 kHz, but nothing below it.",
        "strings_lead":    "A melody is a CENTRE part → the 1–3 kHz core and the mud cut both go in MID. Keep the SIDE silk to +1 dB at most: the wide 8–14 kHz shelf is exactly what makes the BED sound far away.",
        "organ_lead":      "A lead is a CENTRE part → do all of it in MID: the 1–3 kHz note core, the mud cut, the lot. Leslie width only above 6 kHz in the SIDE, and less of it than the bed organ gets — width is what makes a bed.",
        "organ_melody":    "Mostly a MID part: the 1–3 kHz note core and the mud cut go in MID. Allow a little more SIDE shimmer above 6 kHz than the lead organ gets (+1.5 dB), still less than the bed.",
        "accordion":       "Two mics (treble side + bass side) = stereo → SIDE +2 dB @8–10 kHz (width); MID cut −3…−4 dB @300–600 Hz so it leaves the centre; high-pass the SIDE @150 Hz.",
        "piano_bg":        "Stereo take → MID cut −4 dB @300–500 Hz + dip 2–5 kHz (sit back); SIDE air +1…+2 dB @10 kHz (space).",
        "piano_riff":      "MID lift +3 dB @1–3 kHz (hook = centre); SIDE air +2 dB @10 kHz for sparkle.",
        "guitar_rhythm":   "Hard-panned L/R = mono per side → Stereo is fine. Stereo/doubled? SIDE +2 dB @8–10 kHz.",
        "guitar_chords":   "Hard-panned L/R = mono per side → Stereo is fine. Stereo/doubled? SIDE +2 dB @8–10 kHz.",
        "guitar_lead":     "Centre lead → MID. Keep the Side clean.",
        "guitar_single_low":"Mono → Stereo/Mid.",
        "synth_pad":       "WIDE bed → SIDE high-shelf +3 dB @8–14 kHz (air/space); MID cut −4 dB @400–800 Hz + dip 3–5 kHz; high-pass SIDE @120 Hz.",
        "synth_pluck":     "Stereo/ping-pong → SIDE +2 dB @10 kHz (width); keep the body in MID.",
        "synth_mallet":    "Often stereo → SIDE +2 dB @8–12 kHz (bell shimmer width); fundamental ~1 kHz in MID.",
        "flute":           "Mostly MID (core tone). Stereo take? SIDE +2 dB @10 kHz for air.",
        "brass":           "Section = stereo → SIDE +2 dB @8 kHz (spread); MID cut −3 dB @500 Hz–1 kHz (honk).",
        "trumpet":         "One player = mono → Stereo/Mid. Do the 3–6 kHz blare cut in MID; leave the Side alone.",
        "trombone":        "Mono → Stereo/Mid. Keep 100–600 Hz in MID so the low horn stays centred and doesn't smear the bass.",
        "tenor_trombone":        "Mono → Stereo/Mid. Keep 100–600 Hz in MID so the low horn stays centred and doesn't smear the bass.",
        "tenor_bass_trombone":        "Mono → Stereo/Mid. Keep 100–600 Hz in MID so the low horn stays centred and doesn't smear the bass.",
        "saxophone":       "Mono (one horn, one mic) → work in MID like a vocal. Stereo/room take? SIDE +2 dB @8–10 kHz for a little air.",
        "horn_section":    "Section = stereo → SIDE +2…+3 dB @8–10 kHz (spread the three horns); MID cut −3 dB @500 Hz–1 kHz (the section blare); high-pass the SIDE @150 Hz.",
        "harmonica":       "Mono → Stereo/Mid. Amped/room take? SIDE +2 dB @8 kHz — but keep the 4–7 kHz cut in MID where the harshness actually is.",
        "woodwind":        "Mostly MID (reed/definition).",
        "clarinet":        "Mostly MID (reed). Stereo/room take? SIDE +2 dB @8-10 kHz for air.",
        "oboe":            "Mono -> Stereo/Mid. Keep the 1-1.5 kHz nasal cut in MID where the honk is.",
        "bassoon":         "Mostly MID (body). Keep 80-250 Hz in MID so the low end stays centred.",
        "contrabassoon":   "Keep lows MONO -> high-pass the SIDE @120 Hz; body in MID.",
        "flugelhorn":      "One player = mono -> Stereo/Mid. Do any presence work in MID; leave the Side alone.",
        "french_horn":     "Solo -> MID. Section = stereo -> SIDE +2 dB @8 kHz (room), body in MID.",
        "tuba":            "Keep lows MONO -> high-pass the SIDE @120 Hz; body in MID.",
        "english_horn":    "Mono -> Stereo/Mid. Keep the nasal cut in MID where the honk is.",
        "euphonium":       "Mono -> Stereo/Mid. Keep 100-600 Hz in MID so the low horn stays centred.",
        "bass_clarinet":   "Mostly MID (body). Keep 100-250 Hz in MID so the low end stays centred.",
        "contrabass_clarinet": "Keep lows MONO -> high-pass the SIDE @120 Hz; body in MID.",
        "double_bass_section": "Keep lows MONO -> high-pass the SIDE @150 Hz; the bow/attack air above can go in the SIDE.",
        "piccolo": "Mostly MID. Part of a stereo take? SIDE +2 dB @10 kHz for air.",
        "alto_flute": "Mostly MID (core tone). Stereo take? SIDE +2 dB @10 kHz for air.",
        "bass_flute": "Mostly MID (body and presence). Keep 150-400 Hz in MID.",
        "soprano_sax": "Mono -> work in MID like a vocal. Room take? SIDE +2 dB @8-10 kHz.",
        "alto_sax": "Mono -> work in MID like a vocal. Room take? SIDE +2 dB @8-10 kHz.",
        "tenor_sax": "Mono -> work in MID like a vocal. Room take? SIDE +2 dB @8-10 kHz.",
        "baritone_sax": "Mostly MID (body). Keep 80-250 Hz in MID.",
        "piccolo_trumpet": "One player = mono -> Stereo/Mid. Do the 3-6 kHz blare cut in MID.",
        "alto_trombone": "Mono -> Stereo/Mid. Keep 100-600 Hz in MID.",
        "bass_trombone": "Mono -> Stereo/Mid. Keep 80-250 Hz in MID so the bass stays solid.",
        "double_bass_trombone": "Mono -> Stereo/Mid. Keep 80-250 Hz in MID so the bass stays solid.",
        "violin":          "Solo → MID. Section → SIDE air +2…+3 dB @8–12 kHz (silk/width), body in MID.",
        "viola":           "Solo → MID. Section → SIDE air +2 dB @10 kHz, warmth in MID.",
        "viola_front":     "A melody is a CENTRE part → the 1.5–3 kHz core and the mud cut both go in MID. Keep the SIDE silk to +1 dB at most.",
        "cello":           "Mostly MID (body). Section → SIDE air +2 dB @10 kHz.",
        "string_section":  "WIDE → SIDE high-shelf +3 dB @8–14 kHz (the lush 'silk' width); MID cut −3 dB @400–800 Hz; high-pass SIDE @100 Hz.",
        "hihat":           "Mono-ish → Stereo/Mid. Part of stereo OH? SIDE +2 dB @10 kHz.",
        "ride":            "Mono-ish timekeeper → Stereo/Mid (keep the ping centred). Part of stereo OH? SIDE +2 dB @10 kHz for wash width.",
        "cymbals":         "Overheads = stereo → SIDE high-shelf +3 dB @10–15 kHz (air/space); MID cut −2…−3 dB @1–3 kHz (harsh); high-pass SIDE @300 Hz.",
    }
    STEREO_MODE_DEFAULT = "Mono/centre → work in Stereo or Mid; keep the low end mono."

    # ---- Filename labels for generated Kirchhoff presets --------------------
    # Used in '0---<Label>---Group---<clashers>.keq'. Root bass = "Bass_ground"
    # (not "Bass_x"), per the requested naming.
    KEQ_LABEL = {
        "kick": "Kick", "snare": "Snare", "hihat": "Hihat", "ride": "Ride", "cymbals": "Cymbal",
        "toms": "Toms", "percussion": "Perc",
        "bass_root": "Bass_ground", "bass_loop": "Bass_x", "double_bass": "Double_bass",
        "vocals_lead": "Lead_vocal", "vocals_backing": "Backing_vocal",
        "vocals_choir_pad": "Choir_pad",
        "vocals_extra": "Extra_vocal",
        "guitar_rhythm": "Guitar_rhythm", "guitar_chords": "Guitar_chord",
        "guitar_lead": "Guitar_lead", "guitar_single_low": "Guitar_low",
        "organ": "Organ", "organ_lead": "Organ_lead", "organ_melody": "Organ_melody",
        "accordion": "Accordion",
        "brass_lead": "Brass_lead", "strings_lead": "Strings_lead",
        "accordion_lead": "Accordion_lead",
        "flute_bg": "Flute_bg", "violin_bg": "Violin_bg",
        "piano_bg": "Piano_bg", "piano_riff": "Piano_riff",
        "guitar_acoustic": "Guitar_acoustic",
        "flute": "Flute", "brass": "Brass", "woodwind": "Wood",
        "trumpet": "Trumpet", "trombone": "Trombone", "tenor_trombone": "Tenor_trombone", "tenor_bass_trombone": "Tenor_bass_trombone",
        "saxophone": "Sax",
        "horn_section": "Horns", "harmonica": "Harmonica",
        "synth_pad": "Synth_pad", "synth_pluck": "Plopp", "synth_mallet": "Mallet",
        "violin": "Violin", "viola": "Viola", "viola_front": "Viola_front", "cello": "Cello",
        "string_section": "Strings",
        "clarinet": "Clarinet", "oboe": "Oboe", "bassoon": "Bassoon",
        "contrabassoon": "Contrabassoon", "flugelhorn": "Flugelhorn",
        "french_horn": "Horn", "tuba": "Tuba", "english_horn": "English_horn",
        "euphonium": "Euphonium", "bass_clarinet": "Bass_clarinet",
        "contrabass_clarinet": "Contrabass_clarinet",
        "double_bass_section": "Double_bass_section",
        "piccolo": "Piccolo",
        "alto_flute": "Alto_flute",
        "bass_flute": "Bass_flute",
        "soprano_sax": "Soprano_sax",
        "alto_sax": "Alto_sax",
        "tenor_sax": "Tenor_sax",
        "baritone_sax": "Baritone_sax",
        "piccolo_trumpet": "Piccolo_trumpet",
        "alto_trombone": "Alto_trombone",
        "bass_trombone": "Bass_trombone",
        "double_bass_trombone": "Double_bass_trombone",
    }

    def _mix_recommendations(self, sel):
        """Return {inst_id: {"edits": [...], "notes": [str], "pan": str}}.

        'edits'  = STRUCTURED numeric overrides (new gain and/or new centre freq for a
                   specific band). These are applied to the band list so the summary
                   shows the EFFECTIVE, mix-adjusted values, and each one also auto-
                   generates a 'changed vs base' line.
        'notes'  = advisory changes that aren't a single numeric band move
                   (sidechain, pan-driven tonal split, share-the-hook, gate, ...).
        'pan'    = pan suggestion.
        Each edit: {lo, hi, set_db, set_freq, reason} — it lands on the first band
        whose centre frequency falls in [lo, hi)."""
        rec = {iid: {"edits": [], "notes": [], "pan": "", "stereo": ""} for iid in sel}
        by_id   = {x["id"]: x for x in EQ_DATA}
        id2name = {x["id"]: x["name"] for x in EQ_DATA}

        def note(iid, msg):
            if iid in rec and msg not in rec[iid]["notes"]:
                rec[iid]["notes"].append(msg)

        def edit(iid, lo, hi, set_db=None, set_freq=None, reason=""):
            if iid in rec:
                rec[iid]["edits"].append({"lo": lo, "hi": hi, "set_db": set_db,
                                          "set_freq": set_freq, "reason": reason})

        def edit_band(iid, b, set_db=None, set_freq=None, reason=""):
            """Target the exact band 'b' (a narrow window around its centre)."""
            if b is None:
                return
            c = _parse_hz_midpoint(b.get("hz", ""))
            if not c:
                return
            edit(iid, c - 1.0, c + 1.0, set_db=set_db, set_freq=set_freq, reason=reason)

        def anyof(*ids):
            return any(i in sel for i in ids)

        def band_at(iid, lo, hi):
            inst = by_id.get(iid)
            if not inst:
                return None
            for b in inst.get("bands", []):
                hz = _parse_hz_midpoint(b.get("hz", ""))
                if hz and lo <= hz < hi:
                    return b
            return None

        def boosts_in(iid, lo, hi):
            d = _band_cur_db(band_at(iid, lo, hi))
            return d is not None and d > 0

        # ---- PAN + Kirchhoff stereo mode (always computed) ----
        for i in sel:
            rec[i]["pan"] = self.PAN_BASE.get(i, "Centre")
            rec[i]["stereo"] = self.STEREO_MODE.get(i, self.STEREO_MODE_DEFAULT)
        if "guitar_rhythm" in sel and "guitar_chords" in sel:
            rec["guitar_rhythm"]["pan"] = "Hard LEFT (~80–100% L)"
            rec["guitar_chords"]["pan"] = "Hard RIGHT (~80–100% R)"
        if anyof("guitar_rhythm", "guitar_chords"):
            for c in ("organ", "accordion", "piano_bg", "synth_pad"):
                if c in sel:
                    rec[c]["pan"] = "Centre / mid-side (sit between the guitars)"
        if "piano_riff" in sel and "guitar_lead" in sel:
            rec["piano_riff"]["pan"] = "Opposite the lead guitar (~40% one side)"
            rec["guitar_lead"]["pan"] = "Centre (it's the lead)"
        if "hihat" in sel and "synth_mallet" in sel:
            rec["synth_mallet"]["pan"] = "Off-centre, opposite the hi-hat"

        # Below: cross-instrument CHANGES only matter with 2+ instruments.
        if len(sel) < 2:
            return rec

        # 1) Presence ownership in 2–6 kHz (melodic parts only)
        melodic_pres = [i for i in sel
                        if i not in self.RHYTHM_LOW_IDS and boosts_in(i, 2000, 6000)]
        if len(melodic_pres) >= 2:
            owner = next((i for i in self.LEAD_PRIORITY if i in melodic_pres), melodic_pres[0])
            note(owner, "Owns 3–5 kHz presence — keep it forward (don't dip).")
            for i in melodic_pres:
                if i == owner:
                    continue
                b = band_at(i, 3000, 5500) or band_at(i, 2000, 6000)
                d = _band_cur_db(b)
                if d is None:
                    continue
                edit_band(i, b, set_db=float(max(0, round(d) - 4)),
                          reason=f"yield 3–5 kHz to {id2name[owner]}")

        # 2) Low end: kick vs bass(es)
        basses = [i for i in ("bass_root", "bass_loop") if i in sel]
        if "kick" in sel and basses:
            note("kick", "Keep 60–80 Hz punch; high-pass below ~45 Hz and sidechain the bass to you.")
            for bss in basses:
                bb = band_at(bss, 55, 120)
                if bb is not None:
                    edit_band(bss, bb, set_freq=90.0,
                              reason="let the kick own 60 Hz; sidechain to kick")
                else:
                    note(bss, "Centre the body boost ~90 Hz and sidechain to the kick.")
        if "bass_root" in sel and "bass_loop" in sel:
            note("bass_root", "Foundation — keep < 100 Hz (no change).")
            hp = band_at("bass_loop", 0, 70)
            if hp is not None:
                edit_band("bass_loop", hp, set_freq=100.0, reason="split from Root Bass")
            note("bass_loop", "Lean into 500 Hz–3 kHz so the two basses don't mask.")
        if "double_bass" in sel and basses:
            note("double_bass", "Decide who owns the sub; high-pass the other and split by octave.")

        # 3) Two guitars (tonal split — pan handled above)
        if "guitar_rhythm" in sel and "guitar_chords" in sel:
            note("guitar_rhythm", "Make this the BRIGHTER side (a touch more 3–5 kHz than the other guitar).")
            note("guitar_chords", "Make this the WARMER side (roll a little top off vs the other guitar).")

        # 4) Comping clutter 200–800 Hz — push the 300–500 Hz cut
        comp = [i for i in ("guitar_rhythm", "guitar_chords", "organ", "accordion",
                            "piano_bg", "synth_pad")
                if i in sel]
        if len(comp) >= 2:
            for i in comp:
                rest = ", ".join(id2name[j] for j in comp if j != i)
                b = band_at(i, 280, 520)
                d = _band_cur_db(b)
                target = min(d if d is not None else 0.0, -3.0)
                if b is not None and d is not None and round(d) > round(target):
                    edit_band(i, b, set_db=target,
                              reason=f"carve space, pan apart from {rest}")
                else:
                    note(i, f"300–500 Hz: keep the cut; carve a narrow home band, pan apart from {rest}.")
        if "piano_bg" in sel and anyof("guitar_rhythm", "guitar_chords", "organ",
                                       "accordion", "vocals_lead"):
            b = band_at("piano_bg", 2500, 5200)
            if b is not None:
                edit_band("piano_bg", b, set_db=-5.0,
                          reason="tuck UNDER vocals / guitars / organ")
            else:
                note("piano_bg", "Dip 2–5 kHz to about −5 dB so it tucks under the leads.")

        # 5) Pads / choir / backing vs the lead vocal
        if "vocals_lead" in sel:
            for pad in ("vocals_choir_pad", "vocals_extra", "synth_pad"):
                if pad in sel:
                    b = band_at(pad, 3000, 5500)
                    if b is not None:
                        edit_band(pad, b, set_db=-5.0,
                                  reason="duck under the lead vocal; sidechain")
                    else:
                        note(pad, "Carve 3–5 kHz to ~−5 dB and sidechain to the lead vocal.")
            if "vocals_backing" in sel:
                note("vocals_backing", "High-pass more, cut more mud, and use less 3–5 kHz than the lead.")

        # 6) Drum highs
        if "hihat" in sel and "cymbals" in sel:
            hp = band_at("hihat", 0, 250)
            if hp is not None:
                edit_band("hihat", hp, set_freq=400.0, reason="don't share the cymbal wash")
            note("cymbals", "6–8 kHz: cut 2–3 dB if harsh; high-pass overheads ~300 Hz.")
        if "toms" in sel and ("kick" in sel or basses):
            note("toms", "Gate + high-pass slightly so kick/bass keep the low end.")

        # 7) Bright highs stacking (mallet/bell + cymbals/hats/airy synths)
        highs = [i for i in ("synth_mallet", "cymbals", "hihat", "synth_pluck") if i in sel]
        if "synth_mallet" in sel and len(highs) >= 2:
            b = band_at("synth_mallet", 8000, 15000)
            if b is not None:
                edit_band("synth_mallet", b, set_db=1.0, reason="it stacks with cymbals/hats")
            note("synth_mallet", "High-pass ~200 Hz to keep the lows clear.")
        if "synth_pluck" in sel and anyof("cymbals", "hihat", "synth_mallet"):
            b = band_at("synth_pluck", 8000, 13000)
            d = _band_cur_db(b)
            if b is not None and d is not None and d > 1:
                edit_band("synth_pluck", b, set_db=1.0, reason="avoid harsh high-end pile-up")

        # 8) Strings vs the lead — air delta
        strings = [i for i in ("violin", "viola", "viola_front", "cello", "double_bass", "double_bass_section", "string_section") if i in sel]
        strings += [i for i in ("violin_bg",) if i in sel]
        if strings and anyof("vocals_lead", "guitar_lead", "piano_riff",
                             "organ_lead", "brass_lead", "strings_lead",
                             "accordion_lead", "viola_front"):
            for s in strings:
                b = band_at(s, 8000, 13000)
                d = _band_cur_db(b)
                if b is not None and d is not None and d > 1:
                    edit_band(s, b, set_db=1.0, reason="don't mask the lead's presence")

        # 9b) Bed + lead of the SAME instrument (one player, two opposite jobs)
        for bed, lead, hp_hz, _why in BED_LEAD_PAIRS:
            if bed not in sel or lead not in sel:
                continue
            hp = band_at(lead, 0, 220)
            if hp is not None:
                edit_band(lead, hp, set_freq=hp_hz,
                          reason="the %s already owns the warmth" % id2name[bed])
            else:
                note(lead, "High-pass at %d Hz — the %s owns the warmth."
                           % (int(hp_hz), id2name[bed]))
            b = band_at(bed, 1000, 5000)
            d = _band_cur_db(b)
            if b is not None and d is not None and d > 1:
                edit_band(bed, b, set_db=1.0,
                          reason="leave the presence zone to %s" % id2name[lead])
            else:
                note(bed, "Leave the 1–5 kHz presence zone to %s while it plays the tune."
                          % id2name[lead])

        # 9) Piano riff vs lead guitar (the hook)
        if "piano_riff" in sel and "guitar_lead" in sel:
            note("piano_riff", "Share the hook: split octaves / trade phrases with the lead guitar.")
            note("guitar_lead", "Share the hook with the piano riff — trade phrases, don't play over it.")

        return rec

    def _apply_edits(self, inst, edits):
        """Apply the mix edits to COPIES of an instrument's bands and return
        (effective_bands, change_lines). Each changed band gets a '_changed' flag
        (and '_eff_freq' for a moved centre); change_lines describe base → new."""
        bands = [dict(b) for b in inst["bands"]]
        lines = []
        used = set()
        for e in edits:
            idx = None
            for i, b in enumerate(bands):
                if i in used:
                    continue
                hz = _parse_hz_midpoint(b.get("hz", ""))
                if hz and e["lo"] <= hz < e["hi"]:
                    idx = i
                    break
            if idx is None:
                # No band matched — surface the reason as a plain advisory line.
                if e.get("reason"):
                    r = e["reason"]
                    lines.append(r[:1].upper() + r[1:])
                continue
            b = bands[idx]
            used.add(idx)
            zone    = b.get("note", "")
            base_db = _band_cur_db(b)
            parts = []
            if e.get("set_freq") is not None:
                base_hz = _parse_hz_midpoint(b.get("hz", "")) or 0
                b["_eff_freq"] = e["set_freq"]
                parts.append(f"{_kirch_fmt_freq(base_hz)} → {_kirch_fmt_freq(e['set_freq'])}")
            if e.get("set_db") is not None:
                new = e["set_db"]
                b["db"] = int(round(new))
                b.pop("db_lo", None)
                b.pop("db_hi", None)
                b["type"] = "boost" if new > 0 else "cut" if new < 0 else "neutral"
                if base_db is not None:
                    parts.append(f"{base_db:+.0f} → {new:+.0f} dB")
                else:
                    parts.append(f"→ {new:+.0f} dB")
            b["_changed"] = True
            line = (zone + ": " + ",  ".join(parts)) if parts else zone
            if e.get("reason"):
                line += f"  ({e['reason']})"
            lines.append(line)
        return bands, lines

    def _refresh_summary(self):
        """Rebuild the right panel — either the per-instrument summary or the
        compact effect-sorting view, depending on the current mode."""
        for w in self.summary_inner.winfo_children():
            w.destroy()
        # Those blocks may have held live footnotes — drop the dead holders so
        # the register doesn't grow with every rebuild.
        self._prune_live_notes()

        checked = self._panel_ids()
        if self._list_order() == "pick":
            checked = vocals_last(checked)      # v3.24: singers at the end of the panel
        count = len(checked)
        self.sel_count_lbl.config(text=f"({count})")
        self._sync_room_info(count)
        # A snapshot that does not say it is a snapshot is just a wrong
        # answer, so this is not a why-line and it is never hidden.
        self._pending_banner(self.summary_inner)

        if self._right_mode == "channelplan":
            self._render_channel_plan(self.summary_inner, checked)
            self._bind_wheel(self.summary_inner, self._scroll_summary)
            self.root.after_idle(lambda: self._summary_settle(top_if_none=True))
            return

        if self._right_mode == "effects":
            self._render_effect_view(self.summary_inner, checked)
            self._bind_wheel(self.summary_inner, self._scroll_summary)
            # Always jump back to the top when (re)showing an effect-sorted list, so
            # a freshly picked effect starts at its first section (not mid-scroll).
            self.root.after_idle(lambda: self._summary_settle(top_if_none=True))
            return

        if count == 0:
            tk.Label(self.summary_inner,
                     text="\n  No instruments selected.\n  Check boxes on the left to\n  compare EQ settings here.",
                     bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
                     justify="left").pack(padx=10, pady=20, anchor="w")
            return

        # Section filter (📋 Instruments view only) — empty set = show everything.
        # The ticked BOXES and the SECTION KEYS are no longer the same thing:
        # "⚙ Set & forget" is one box standing for four sections, so expand it
        # before the blocks are built. The header line still names the boxes.
        ticked = {k for k, v in self._instr_filter_vars.items() if v.get()}
        filters = set()
        for k in ticked:
            filters.update(self.INSTR_FILTER_EXPAND.get(k, (k,)))
        if filters:
            names = [lbl for k, lbl in self.INSTR_FILTERS if k in ticked]
            tk.Label(self.summary_inner, text="Showing only: " + ", ".join(names),
                     bg=C_BG2, fg=C_ACCENT, font=FONT_SMALL,
                     justify="left", anchor="w").pack(fill="x", padx=8, pady=(4, 0))

        recs = self._mix_recommendations(set(checked))

        # Grouped by reverb bus, not by EQ_DATA order: the toms belong next to
        # the hi-hat and the ride (all NEAR, all one smart:reverb instance), not
        # under the cymbals, which sit a tier further back. The heading is there
        # so the order explains itself.
        # …but only when the ⇅ button says "per position". On "pick order" the
        # channels stand in picker order instead — all the guitars after each
        # other — and then the bus headings would lie about the order, so they
        # go. Nothing is lost: every block still prints its own reverb line.
        by_position = (self._list_order() == "position")
        last_bus = None
        for iid in self._ordered_ids(checked):
            inst = next((x for x in EQ_DATA if x["id"] == iid), None)
            if not inst:
                continue
            if by_position:
                bus = self._reverb_bus_label(iid)
                if bus != last_bus:
                    last_bus = bus
                    tk.Label(self.summary_inner, text="  ▬  " + bus,
                             bg=C_BG2, fg=C_ACCENT, font=FONT_SMALL,
                             anchor="w", justify="left").pack(fill="x", padx=8, pady=(10, 0))
            self._build_summary_block(self.summary_inner, inst, recs.get(iid), filters=filters)

        # Bind the wheel to every child so scrolling works anywhere in the panel
        # (Tk does not bubble <MouseWheel> up to the parent canvas on its own).
        self._bind_wheel(self.summary_inner, self._scroll_summary)
        self.root.after_idle(self._summary_settle)

    # ---- EFFECT-SORTING VIEW (right panel alternative) ----------------------

    # ---- ⇅ ORDER: pick order vs room position -------------------------------

    def _list_order(self):
        """"pick" | "position" — how the two list views sort their channels."""
        try:
            v = self.list_order_var.get()
        except Exception:
            return "pick"
        return v if v in ("pick", "position") else "pick"

    def _toggle_list_order(self):
        """The ⇅ button: swap pick order ↔ room position and redraw."""
        self.list_order_var.set("position" if self._list_order() == "pick" else "pick")
        self._on_list_order_change()

    def _on_list_order_change(self):
        """Shared by the ⇅ button and the two View-menu radio items."""
        self._sync_order_button()
        self._refresh_summary()
        self._save_current_settings()   # the order you pick is the order you get back

    def _sync_order_button(self):
        """Label + colour of the ⇅ button. Pick order is the plain default, so
        it gets the plain button; the room-position sort is the deviation and
        gets the accent, the same language the View buttons use."""
        btn = getattr(self, "order_btn", None)
        if btn is None:
            return
        if self._list_order() == "position":
            btn.config(text="⇅ Per position", bg=C_ACCENT, fg=C_BG)
        else:
            btn.config(text="⇅ Pick order", bg=C_BTN, fg=C_BTN_FG)

    def _ordered_ids(self, ids):
        """`ids` in the order the current ⇅ setting asks for. "pick" keeps them
        exactly as the picker lists them (EQ_DATA order — all the guitars after
        each other); "position" hands them to the reverb-bus sort."""
        if self._list_order() == "position":
            return self._instruments_by_bus(ids)
        return list(ids)

    def _set_right_mode(self, mode):
        """Switch the right panel to one of: channelplan / instruments / effects."""
        if mode not in ("channelplan", "instruments", "effects"):
            mode = "channelplan"
        self._right_mode = mode
        self._sync_view_buttons()
        self._refresh_summary()
        self._save_current_settings()   # the view you pick is the view you get back

    def _sync_view_buttons(self):
        """Highlight the active view button (accent), dim the others; show the
        section filter row only in the 📋 Instruments view (it has no meaning
        in Channel Plan or Effects)."""
        for mode, btn in getattr(self, "_view_btns", {}).items():
            if mode == self._right_mode:
                btn.config(bg=C_ACCENT, fg=C_BG)        # active
            else:
                btn.config(bg=C_BTN, fg=C_BTN_FG)       # inactive
        # The ⇅ button sorts the two LIST views; in 🔀 Effects it would be a lie
        # (that view is sorted by the effect you picked), so it steps aside.
        self._sync_order_button()
        ob = getattr(self, "order_btn", None)
        if ob is not None:
            ob.config(state=("disabled" if self._right_mode == "effects" else "normal"))
        frame = getattr(self, "instr_filter_frame", None)
        sep   = getattr(self, "_summary_sep", None)
        if frame is not None:
            if self._right_mode == "instruments":
                if sep is not None:
                    frame.pack(fill="x", before=sep)
                else:
                    frame.pack(fill="x")
            else:
                frame.pack_forget()

    def _on_instr_filter_toggle(self):
        """A section filter was ticked/unticked — redraw and remember it."""
        self._refresh_summary()
        self._save_current_settings()

    def _reset_instr_filters(self):
        """Untick every section filter (back to: show everything)."""
        for v in self._instr_filter_vars.values():
            v.set(False)
        self._on_instr_filter_toggle()

    # ---- CHANNEL PLAN (the default combined right-panel view) ----------------

    def _channel_eq_bus(self, iid, id2inst):
        """(bus_name, tier) this channel lands in for smart:EQ. Solo basses get
        their own bus (no sharing). Returns (None, None) if it has no group."""
        inst = id2inst.get(iid)
        g = SMARTEQ_GROUP.get(iid)
        if not inst or not g:
            return None, None
        tier = g[0]
        if iid in self._SMARTEQ_FORCE_SOLO:
            return inst["name"], tier            # own bus — never shared
        fam = self._SMARTEQ_SHORT_FAM.get(inst["group"], inst["group"])
        return f"{fam} · {tier.upper()}", tier

    def _inserts_map_plugins(self):
        """(insert_chain, master_tools) of the plugins you actually use — core +
        favourite + like, disliked/untested excluded. Insert chain sorted by where
        each sits on the strip; master-bus tools (limiter/comp/loudness) separate."""
        use = [p for p in self.plugins if p.get("status") in ("core", "favorite", "like")]
        def on_master(p):
            return p.get("bus") == "master" or p.get("kind") in PLUGIN_MASTER_KINDS
        inserts = sorted([p for p in use if not on_master(p)], key=plugin_chain)
        master = [p for p in use if on_master(p)]
        return inserts, master

    def _plugin_suggest_names(self, kind):
        """Name the user's plugins of a kind for a suggestion (disliked excluded)."""
        liked = self._liked_plugins_of_kind(kind)
        if liked:
            return "you have " + ", ".join(plugin_wrapped_name(p) for p in liked[:4])
        unt = [p for p in self.plugins
               if p.get("kind") == kind and p.get("status") == "untested"]
        if unt:
            return "untested — try one: " + ", ".join(p["name"] for p in unt[:4])
        return "nothing of this kind yet — add one in the 🧩 Plugins tab"

    def _channel_plan_suggestions(self, ids):
        """A few grounded 'try this' ideas based on the selected instruments. Each:
        (kind, reason). The view turns them into range-only guidance + your plugins."""
        s = set(ids)
        out = []
        leads = {"vocals_lead", "guitar_lead", "piano_riff", "organ_lead", "organ_melody",
                 "brass_lead", "strings_lead", "accordion_lead",
                 "synth_pluck", "flute", "violin", "viola_front"}
        pads  = {"synth_pad", "string_section", "vocals_choir_pad", "vocals_extra", "organ",
                 "flute_bg", "violin_bg"}
        if s & leads:
            out.append(("Delay", "give a lead/hook depth, width and movement"))
        if s & pads:
            out.append(("Width", "widen a bed/pad without hollowing the centre"))
        gtr = sum(1 for i in s if i.startswith("guitar_"))
        if gtr >= 1:
            out.append(("Saturation", "add cut/heat so a guitar sits forward without more level"))
        if "vocals_lead" in s:
            out.append(("Vocal", "polish the lead — de-ess, presence or an auto-rider"))
        if {"snare", "kick", "toms"} & s:
            out.append(("Transient", "tighten the punch / tame ringing tails on drums"))
        return out[:4]

    def _render_channel_plan(self, parent, checked):
        """Compact COMBINED planning view (the default right-panel mode): every
        selected channel with its smart:EQ priority, reverb depth, duck source and
        pan in ONE scroll — so you can plan the whole song's routing at a glance.
        Channels that share BOTH the same smart:EQ group AND the same reverb depth
        get a coloured 'stem' badge: they can be bussed together (one smart:EQ
        sub-bus + one reverb send). Low-cut (Lowtility) and the Kirchhoff EQ table
        are per-channel and intentionally LEFT OUT here — use the 📋 Instruments
        view for those. (The separate 🎯 smart:EQ / 🌫 Reverb Group popups still
        exist for the dedicated, single-effect plans.)"""
        used_all = not checked
        ids = checked or [x["id"] for x in EQ_DATA]
        id2inst = {x["id"]: x for x in EQ_DATA}

        # Group channels that share the SAME smart:EQ bus AND the SAME reverb tier
        # (non-dry) → a 'stem' they can be routed through together.
        stem_members = {}
        for iid in ids:
            bus, _t = self._channel_eq_bus(iid, id2inst)
            d = DEPTH.get(iid)
            rev = d[0] if d else None
            if bus and iid not in self._SMARTEQ_FORCE_SOLO and rev and rev != "dry":
                stem_members.setdefault((bus, rev), []).append(iid)

        STEM_PALETTE = ["#e6b85c", "#7fd1e6", "#9fe0a0", "#e69fd1", "#c79fe6",
                        "#e6a07f", "#9fb6e6", "#bfe67f"]
        letters = "ABCDEFGHIJ"
        stems, stem_of, si = [], {}, 0
        for key in sorted(stem_members, key=lambda k: (k[1], k[0])):
            mem = stem_members[key]
            if len(mem) < 2:
                continue
            letter, colour = letters[si % len(letters)], STEM_PALETTE[si % len(STEM_PALETTE)]
            stems.append((letter, colour, key, mem))
            for iid in mem:
                stem_of[iid] = (letter, colour)
            si += 1

        # ---- header / caption ----
        src = "ALL instruments" if used_all else f"{len(ids)} selected channel(s)"
        hd = tk.Frame(parent, bg=C_BG2, padx=8, pady=6)
        hd.pack(fill="x")
        tk.Label(hd, text=f"📐 Channel Plan — {src}", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 11, "bold")).pack(anchor="w")
        tk.Label(hd, text="smart:EQ priority · reverb depth · duck · pan, all in one place. "
                          "Low-cut (Lowtility) and the Kirchhoff EQ table are per-channel — "
                          "switch to the 📋 Instruments view for those.",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL, wraplength=560,
                 justify="left").pack(anchor="w", pady=(2, 0))
        tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x", pady=(4, 0))

        # ---- inserts map (the channel-strip ORDER you asked for) ----
        inserts, master = self._inserts_map_plugins()
        imap = tk.Frame(parent, bg=C_CARD, padx=10, pady=8)
        imap.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(imap, text="🧩 Insert order — channel strip, top → bottom",
                 bg=C_CARD, fg=C_ACCENT, font=("Segoe UI", 10, "bold")).pack(anchor="w")
        tk.Label(imap, text="( ) = on many channels · (( )) = only the odd channel · "
                          "plain = (almost) every channel. Edit names/scope in the 🧩 Plugins tab.",
                 bg=C_CARD, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=540,
                 justify="left").pack(anchor="w", pady=(0, 4))
        last_send = False
        for n, p in enumerate(inserts, 1):
            if (p.get("kind") in PLUGIN_SEND_KINDS) and not last_send:
                sd = tk.Label(imap, text="— sends (aux), not a real insert · ⓘ what's a send? —",
                              bg=C_CARD, fg=C_ACCENT, font=("Segoe UI", 8, "italic"),
                              cursor="hand2")
                sd.pack(anchor="w", pady=(4, 0))
                sd.bind("<Button-1>", lambda e: self._show_explain("insert_send"))
                last_send = True
            r = tk.Frame(imap, bg=C_CARD)
            r.pack(fill="x")
            tk.Label(r, text=f"{n}.", bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     width=3, anchor="w").pack(side="left")
            glyph, gcol, _ = PLUGIN_STATUS.get(p.get("status"), PLUGIN_STATUS["like"])
            tk.Label(r, text=glyph, bg=C_CARD, fg=gcol, font=("Segoe UI", 9),
                     width=2, anchor="w").pack(side="left")
            focused = plugin_is_focus(p, self.focus_plugins)
            tk.Label(r, text=("★" if focused else " "), bg=C_CARD,
                     fg=("#ffd479" if focused else C_CARD),
                     font=("Segoe UI", 9), width=2, anchor="w").pack(side="left")
            tail = "   ← only the channels with a 🦆 above" if p.get("kind") == "Duck" else ""
            tk.Label(r, text=f"{plugin_wrapped_name(p)}  —  {p.get('kind','')}{tail}",
                     bg=C_CARD, fg=(C_FG if focused else C_FG_DIM),
                     font=(("Segoe UI", 8, "bold") if focused else FONT_SMALL),
                     anchor="w", wraplength=520,
                     justify="left").pack(side="left", fill="x", expand=True)
        if master:
            tk.Label(imap, text="— master bus only —", bg=C_CARD, fg=C_FG_DIM,
                     font=("Segoe UI", 8, "italic")).pack(anchor="w", pady=(4, 0))
            tk.Label(imap, text="   " + ", ".join(p["name"] for p in master)
                              + "  (you said: only auto-mastering tools, on the master).",
                     bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, wraplength=520,
                     justify="left").pack(anchor="w")

        # ---- shareable stems ----
        if stems:
            box = tk.Frame(parent, bg=C_CARD, padx=10, pady=8)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="🔗 Shareable stems — route these together",
                     bg=C_CARD, fg=C_ACCENT, font=("Segoe UI", 10, "bold")).pack(anchor="w")
            for letter, colour, (bus, rev), mem in stems:
                line = tk.Frame(box, bg=C_CARD)
                line.pack(fill="x", pady=(4, 0))
                tk.Label(line, text=f"◆ {letter}", bg=C_CARD, fg=colour,
                         font=("Segoe UI", 10, "bold"), width=3, anchor="nw").pack(side="left")
                names = ", ".join(id2inst[i]["name"] for i in mem)
                rl = DEPTH_SPEC.get(rev, {}).get("label", rev.upper())
                tk.Label(line, text=f"{bus}  +  {rl} reverb\n   {names}",
                         bg=C_CARD, fg=C_FG, font=FONT_SMALL, justify="left",
                         wraplength=500, anchor="w").pack(side="left", fill="x", expand=True)
            tk.Label(box, text="A stem = same smart:EQ group AND same reverb depth, so one smart:EQ "
                              "sub-bus + one reverb send covers the whole group. Channels with no "
                              "badge stay on their own.",
                     bg=C_CARD, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=540,
                     justify="left").pack(anchor="w", pady=(6, 0))

        # ---- every channel: three FRONT/MID/BACK boxes, or one list ----------
        # ⇅ "Per position" = the old three boxes, one per smart:EQ tier: right
        # when you are deciding who wins a masking fight. ⇅ "Pick order" (the
        # default) = ONE box in picker order, so the two guitars stand next to
        # each other instead of one landing in FRONT and the other in BACK.
        # The tier is not lost then — every row carries its ▲ ■ ▼ glyph.
        by_position = (self._list_order() == "position")
        if by_position:
            sections = [("▲ FRONT — wins masking", C_BOOST,   "front"),
                        ("■ MID — supporting",     C_ACCENT,  "mid"),
                        ("▼ BACK — yields",        C_NEUTRAL, "back")]
            sections = [(lbl, col,
                         [i for i in ids if SMARTEQ_GROUP.get(i, ("",))[0] == tier])
                        for lbl, col, tier in sections]
        else:
            sections = [("🎛 Channels — picker order  (▲ front · ■ mid · ▼ back)",
                         C_ACCENT, list(ids))]
        for label, col, members in sections:
            if not members:
                continue
            box = tk.Frame(parent, bg=C_CARD, padx=10, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text=label, bg=C_CARD, fg=col,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w")
            for iid in members:
                inst = id2inst[iid]
                # Only print what this channel actually HAS: no reverb line for a
                # dry channel, no duck line for a channel that ducks nothing.
                d = DEPTH.get(iid)
                rev = d[0] if d else None
                # No duck line when the side-chain source isn't in this song.
                duck = ducking_for(iid, set(ids))
                pan = self.PAN_BASE.get(iid, "Centre")
                n_of = self._count_of(iid)
                parts = []
                if n_of > 1:
                    parts.append(f"✖{n_of}")
                if rev and rev != "dry":
                    parts.append("🌫 " + DEPTH_SPEC.get(rev, {}).get("label", rev.upper()))
                if duck:
                    parts.append(f"🦆 {duck['src']}")
                parts.append(f"🎚 {pan}")
                try:
                    st = self._stage()[0].get(iid)
                except Exception:
                    st = None
                if st:
                    parts.append("🎪 " + (
                        ("OFF · " + swam_short(st["swam"]) if st.get("swam") else
                         "OFF ✖N-option" if st.get("option") else "OFF")
                        if st.get("skip")
                        else "%s / D%s" % (st["pos"], stage_dist_text(st))))
                row = tk.Frame(box, bg=C_CARD)
                row.pack(fill="x", pady=1)
                badge = stem_of.get(iid)
                tk.Label(row, text=(f"◆{badge[0]}" if badge else ""), bg=C_CARD,
                         fg=(badge[1] if badge else C_CARD),
                         font=("Segoe UI", 9, "bold"), width=3, anchor="w").pack(side="left")
                if not by_position:
                    # No FRONT/MID/BACK heading in this order, so the tier rides
                    # along on the row. Every row gets the column, so the names
                    # below still line up.
                    g, gc = self._TIER_GLYPH.get(
                        SMARTEQ_GROUP.get(iid, ("",))[0], ("·", C_FG_DIM))
                    tk.Label(row, text=g, bg=C_CARD, fg=gc,
                             font=("Segoe UI", 9, "bold"), width=2,
                             anchor="w").pack(side="left")
                tk.Label(row, text="● " + inst["name"], bg=C_CARD,
                         fg=inst.get("color", C_FG), font=FONT_SMALL,
                         width=20, anchor="w").pack(side="left")
                meta = "   ·   ".join(parts)
                tk.Label(row, text=meta, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                         wraplength=360, justify="left", anchor="w").pack(
                             side="left", fill="x", expand=True)

        # ---- "Try this" suggestions (range-only; never exact numbers) ----
        sugg = self._channel_plan_suggestions(ids)
        if sugg:
            box = tk.Frame(parent, bg=C_CARD, padx=10, pady=8)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="🔎 Try this (optional, by ear)",
                     bg=C_CARD, fg="#ffcf8f", font=("Segoe UI", 10, "bold")).pack(anchor="w")
            for kind, reason in sugg:
                tip = PLUGIN_KIND_TIP.get(kind)
                tk.Label(box, text=f"• {kind} — to {reason}.", bg=C_CARD, fg=C_FG,
                         font=("Segoe UI", 9, "bold"), wraplength=540, justify="left",
                         anchor="w").pack(fill="x", pady=(4, 0))
                if tip:
                    tk.Label(box, text=f"   Try {tip['try']}. Good = {tip['good']}; "
                                      f"too much = {tip['too_much']}.",
                             bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL, wraplength=540,
                             justify="left", anchor="w").pack(fill="x")
                tk.Label(box, text="   → " + self._plugin_suggest_names(kind),
                         bg=C_CARD, fg=C_ACCENT, font=FONT_SMALL, wraplength=540,
                         justify="left", anchor="w").pack(fill="x")
            tk.Label(box, text="These are ideas, never rules — the program won't guess exact "
                              "numbers. Mark plugins 👎 in the 🧩 Plugins tab to stop them being "
                              "suggested.",
                     bg=C_CARD, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=540,
                     justify="left").pack(anchor="w", pady=(6, 0))

        if len(ids) == 0:
            tk.Label(parent, text="\n  No instruments selected.",
                     bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(anchor="w", padx=10)

    def _set_effect_sort(self, key):
        self._effect_sort = key
        self._refresh_summary()

    def _render_effect_view(self, parent, checked):
        """Compact, scannable layout of all instruments sorted by ONE effect:
        duck / pan / smart:EQ / smart:reverb. Uses checked instruments, or ALL
        if none are ticked."""
        used_all = not checked
        ids = checked or [x["id"] for x in EQ_DATA]
        id2inst = {x["id"]: x for x in EQ_DATA}

        # Effect selector buttons
        # Two rows: nine buttons side by side no longer fit the panel width.
        sel = tk.Frame(parent, bg=C_BG2, padx=6, pady=6)
        sel.pack(fill="x")
        sel2 = tk.Frame(parent, bg=C_BG2, padx=6, pady=0)
        sel2.pack(fill="x")
        for key, label in [("lowcut", "🔻 Low cut"), ("duck", "🦆 Duck"),
                           ("pan", "🎚 Pan"), ("stage", "🎪 Stage"),
                           ("smarteq", "🎯 smart:EQ"), ("smartreverb", "🌫 Reverb"),
                           ("corridor", "🌀 Corridor"), ("omega", "🔥 Omega"),
                           ("bandwidth", "↔ Width"), ("cascadia", "≈ Cascadia")]:
            active = (self._effect_sort == key)
            tk.Button(sel2 if key in ("bandwidth", "cascadia") else sel, text=label,
                      bg=(C_ACCENT if active else C_BTN),
                      fg=(C_BG if active else C_BTN_FG),
                      activebackground=C_BG, activeforeground=C_FG,
                      font=FONT_SMALL, relief="flat", padx=6, pady=3, cursor="hand2",
                      command=lambda k=key: self._set_effect_sort(k)).pack(side="left", padx=2)

        src = "ALL instruments" if used_all else f"{len(ids)} selected"
        tk.Label(parent, text=f"  sorting {src} by {self._effect_sort}",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(anchor="w", padx=8)
        tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x", pady=(4, 0))

        names = lambda lst: [id2inst[i]["name"] for i in lst if i in id2inst]

        def section(title, colour, members, extra=None):
            box = tk.Frame(parent, bg=C_CARD, padx=8, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            head = title + (f"   ({extra})" if extra else "")
            tk.Label(box, text=head, bg=C_CARD, fg=colour,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w")
            if not members:
                tk.Label(box, text="—", bg=C_CARD, fg=C_FG_DIM,
                         font=FONT_SMALL).pack(anchor="w")
            for nm in members:
                tk.Label(box, text="• " + nm, bg=C_CARD, fg=C_FG,
                         font=FONT_SMALL, wraplength=300, justify="left",
                         anchor="w").pack(fill="x")

        if self._effect_sort == "smarteq":
            for tier, label, col in [("front", "▲ FRONT — wins masking", C_BOOST),
                                     ("mid", "■ MID — supporting", C_ACCENT),
                                     ("back", "▼ BACK — yields", C_NEUTRAL)]:
                section(label, col, names([i for i in ids
                        if SMARTEQ_GROUP.get(i, ("",))[0] == tier]))

        elif self._effect_sort == "smartreverb":
            for tier in ("front", "near", "mid", "far"):
                spec = DEPTH_SPEC[tier]
                mem = names([i for i in ids if DEPTH.get(i, ("",))[0] == tier])
                if not mem:
                    continue
                section(f"{spec['label']} — {spec['plain']}", DEPTH_COLOUR, mem,
                        extra=f"Distance ~{spec['distance']} · Size ~{spec['size']} · Width ~{spec['width']}")
            # DRY channels are not listed — no reverb section means no reverb.

        elif self._effect_sort == "duck":
            # Group the duckers by the source they sidechain to.
            # Only ducks whose SOURCE is in this song — no kick, no kick-duck.
            sel_ids = set(ids)
            by_src, missing = {}, []
            for i in ids:
                d = DUCKING.get(i)
                if not d:
                    continue
                if duck_source_present(d["src"], sel_ids):
                    by_src.setdefault(d["src"], []).append(id2inst[i]["name"])
                elif d["src"] not in missing:
                    missing.append(d["src"])
            if not by_src:
                section("No ducking needed", C_FG_DIM, [])
            for srcname, members in by_src.items():
                section(f"🦆 Duck under the {srcname}", "#ffcf8f", members,
                        extra="Trackspacer / Kickstart")
            for srcname in missing:
                tk.Label(parent,
                         text=(f"  (No {srcname} in this song — the usual "
                               f"duck-under-the-{srcname.lower()} does not apply.)"),
                         bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL, wraplength=320,
                         justify="left").pack(anchor="w", padx=8, pady=(4, 0))
            tip = ("  Start GENTLE: ~10–15% Amount, raise only until the masked part "
                   "just opens up. If a part disappears or pumps, you went too far.")
            if "vocals_lead" in sel_ids:
                tip = ("  Tip: one Trackspacer on the music bus, side-chain = the dry "
                       "Lead Vocal, Low Cut ~250–300 Hz, ducks the whole backing at once.\n"
                       + tip)
            tk.Label(parent, text=tip,
                     bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL, wraplength=320,
                     justify="left").pack(anchor="w", padx=8, pady=(8, 0))

        elif self._effect_sort == "stage":
            rows_, info_ = self._stage()
            box = tk.Frame(parent, bg=C_CARD, padx=8, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="🎪 Virtual Stage — the band, left to right",
                     bg=C_CARD, fg=VSTAGE_COLOUR,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w")
            tk.Label(box, text="Room %s on EVERY instance." % info_["room"],
                     bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL).pack(anchor="w")
            for i in info_["order"]:
                if i not in ids or i not in id2inst:
                    continue
                r = rows_[i]
                line = tk.Frame(box, bg=C_CARD)
                line.pack(fill="x", pady=1)
                tk.Label(line, text=id2inst[i]["name"], bg=C_CARD, fg=C_FG,
                         font=FONT_SMALL, width=20, anchor="w").pack(side="left")
                if r.get("swam"):
                    txt = "SWAM: " + swam_text(r["swam"])
                elif r.get("skip"):
                    txt = "— leave Virtual Stage OFF"
                    if r.get("option"):
                        txt += "   ·   ✖%d: one option, see the card" % r["option"]["n"]
                else:
                    txt = "%s   ·   Distance %s" % (r["pos"], stage_dist_text(r))
                tk.Label(line, text=txt, bg=C_CARD,
                         fg=(C_FG_DIM if r.get("skip") else VSTAGE_COLOUR),
                         font=FONT_SMALL, wraplength=190, justify="left",
                         anchor="w").pack(side="left", fill="x", expand=True)
            tk.Button(parent, text="🎪  Open the full stage map…",
                      bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                      activeforeground=C_FG, font=FONT_SMALL, relief="flat",
                      padx=10, pady=4, cursor="hand2",
                      command=self._show_stage_map).pack(anchor="w", padx=8,
                                                         pady=(8, 0))

        elif self._effect_sort == "corridor":
            # Grouped BY PRESET, not by instrument: the whole point of a preset
            # bundle is that one preset covers several channels, and seeing the
            # horns share one entry is what stops you loading three.
            groups, order = {}, []
            dry = []
            for i in ids:
                pre, _alts = corridor_for(i)
                if not pre:
                    dry.append(i)
                    continue
                if pre["key"] not in groups:
                    groups[pre["key"]] = []
                    order.append(pre["key"])
                groups[pre["key"]].append(i)
            box = tk.Frame(parent, bg=C_CARD, padx=8, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="🌀 Corridor — one preset per space, not per channel",
                     bg=C_CARD, fg=CORRIDOR_COLOUR,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w")
            for key in order:
                pre = CORRIDOR_BY_KEY[key]
                tk.Label(box, text="  " + corridor_head(pre), bg=C_CARD,
                         fg=CORRIDOR_COLOUR, font=("Segoe UI", 8, "bold"),
                         wraplength=320, justify="left",
                         anchor="w").pack(fill="x", pady=(6, 0))
                tk.Label(box, text="     " + corridor_detail(pre), bg=C_CARD,
                         fg=C_FG_DIM, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
                tk.Label(box,
                         text="     → " + ", ".join(id2inst[i]["name"]
                                                    for i in groups[key]),
                         bg=C_CARD, fg=C_FG, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
            if dry:
                tk.Label(box, text="  No reverb at all (keep these dry):\n     "
                                   + ", ".join(id2inst[i]["name"] for i in dry),
                         bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                         wraplength=320, justify="left",
                         anchor="w").pack(fill="x", pady=(6, 0))
            tk.Button(parent, text="🌀  Write these presets…",
                      bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                      activeforeground=C_FG, font=FONT_SMALL, relief="flat",
                      padx=10, pady=4, cursor="hand2",
                      command=self._generate_corridor_selected).pack(
                          anchor="w", padx=8, pady=(8, 0))

        elif self._effect_sort == "omega":
            # Grouped by preset, like Corridor — but for the opposite reason.
            # Corridor groups because one reverb serves several channels; Omega
            # groups only to keep the list short. Every channel here gets its
            # OWN instance, and the header says so, because saturating six
            # channels through one plug-in is not a thing you can do.
            groups, order = {}, []
            for i in ids:
                pre, _alts = omega_for(i)
                if not pre:
                    continue
                if pre["key"] not in groups:
                    groups[pre["key"]] = []
                    order.append(pre["key"])
                groups[pre["key"]].append(i)
            box = tk.Frame(parent, bg=C_CARD, padx=8, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="🔥 Omega 458a — one instance PER channel; the "
                               "preset is just what they share",
                     bg=C_CARD, fg=OMEGA_COLOUR, font=("Segoe UI", 10, "bold"),
                     wraplength=320, justify="left").pack(anchor="w")
            for key in order:
                pre = OMEGA_BY_KEY[key]
                tk.Label(box, text="  " + omega_head(pre), bg=C_CARD,
                         fg=OMEGA_COLOUR, font=("Segoe UI", 8, "bold"),
                         wraplength=320, justify="left",
                         anchor="w").pack(fill="x", pady=(6, 0))
                tk.Label(box, text="     " + omega_detail(pre), bg=C_CARD,
                         fg=C_FG_DIM, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
                if pre.get("caution"):
                    tk.Label(box, text="     ⚠ " + pre["caution"], bg=C_CARD,
                             fg=C_CUT, font=FONT_SMALL, wraplength=320,
                             justify="left", anchor="w").pack(fill="x")
                tk.Label(box,
                         text="     → " + ", ".join(id2inst[i]["name"]
                                                    for i in groups[key]),
                         bg=C_CARD, fg=C_FG, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
            tk.Button(parent, text="🔥  Write these presets…",
                      bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                      activeforeground=C_FG, font=FONT_SMALL, relief="flat",
                      padx=10, pady=4, cursor="hand2",
                      command=self._generate_omega_selected).pack(
                          anchor="w", padx=8, pady=(8, 0))

        elif self._effect_sort == "bandwidth":
            # Grouped by preset to keep the list short; like Omega, every
            # channel gets its OWN instance (width is per channel, and the
            # Bandwidth bus presets are the only shared ones).
            groups, order = {}, []
            for i in ids:
                pre, _alts = bandwidth_for(i)
                if not pre:
                    continue
                if pre["key"] not in groups:
                    groups[pre["key"]] = []
                    order.append(pre["key"])
                groups[pre["key"]].append(i)
            box = tk.Frame(parent, bg=C_CARD, padx=8, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="↔ Bandwidth — one instance PER channel; the "
                               "preset is just what they share",
                     bg=C_CARD, fg=BANDWIDTH_COLOUR, font=("Segoe UI", 10, "bold"),
                     wraplength=320, justify="left").pack(anchor="w")
            for key in order:
                pre = BANDWIDTH_BY_KEY[key]
                tk.Label(box, text="  " + bandwidth_head(pre), bg=C_CARD,
                         fg=BANDWIDTH_COLOUR, font=("Segoe UI", 8, "bold"),
                         wraplength=320, justify="left",
                         anchor="w").pack(fill="x", pady=(6, 0))
                tk.Label(box, text="     " + bandwidth_detail(pre), bg=C_CARD,
                         fg=C_FG_DIM, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
                if pre.get("caution"):
                    tk.Label(box, text="     ⚠ " + pre["caution"], bg=C_CARD,
                             fg=C_CUT, font=FONT_SMALL, wraplength=320,
                             justify="left", anchor="w").pack(fill="x")
                tk.Label(box,
                         text="     → " + ", ".join(id2inst[i]["name"]
                                                    for i in groups[key]),
                         bg=C_CARD, fg=C_FG, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
            tk.Button(parent, text="↔  Write these presets…",
                      bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                      activeforeground=C_FG, font=FONT_SMALL, relief="flat",
                      padx=10, pady=4, cursor="hand2",
                      command=self._generate_bandwidth_selected).pack(
                          anchor="w", padx=8, pady=(8, 0))

        elif self._effect_sort == "cascadia":
            # Grouped BY PRESET, like Corridor: Cascadia is a SEND, so the point
            # of the list is to see which channels feed the same one - and which
            # channels are kept dry on purpose.
            groups, order, dry = {}, [], []
            for i in ids:
                pre, _alts = cascadia_for(i)
                if not pre:
                    dry.append(i)
                    continue
                if pre["key"] not in groups:
                    groups[pre["key"]] = []
                    order.append(pre["key"])
                groups[pre["key"]].append(i)
            box = tk.Frame(parent, bg=C_CARD, padx=8, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="\u2248 Cascadia \u2014 a SEND at the end of the chain; "
                               "channels under the same preset share ONE instance",
                     bg=C_CARD, fg=CASCADIA_COLOUR, font=("Segoe UI", 10, "bold"),
                     wraplength=320, justify="left").pack(anchor="w")
            for key in order:
                pre = CASCADIA_BY_KEY[key]
                tk.Label(box, text="  " + cascadia_head(pre), bg=C_CARD,
                         fg=CASCADIA_COLOUR, font=("Segoe UI", 8, "bold"),
                         wraplength=320, justify="left",
                         anchor="w").pack(fill="x", pady=(6, 0))
                tk.Label(box, text="     " + cascadia_detail(pre), bg=C_CARD,
                         fg=C_FG_DIM, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
                for msg in cascadia_caution(pre):
                    tk.Label(box, text="     \u26a0 " + msg, bg=C_CARD,
                             fg=C_CUT, font=FONT_SMALL, wraplength=320,
                             justify="left", anchor="w").pack(fill="x")
                tk.Label(box,
                         text="     \u2192 " + ", ".join(id2inst[i]["name"]
                                                    for i in groups[key]),
                         bg=C_CARD, fg=C_FG, font=FONT_SMALL, wraplength=320,
                         justify="left", anchor="w").pack(fill="x")
            if dry:
                tk.Label(box, text="  No delay at all (keep these dry):\n     "
                                   + ", ".join(id2inst[i]["name"] for i in dry),
                         bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                         wraplength=320, justify="left",
                         anchor="w").pack(fill="x", pady=(6, 0))
            tk.Button(parent, text="\u2248  Write these presets\u2026",
                      bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                      activeforeground=C_FG, font=FONT_SMALL, relief="flat",
                      padx=10, pady=4, cursor="hand2",
                      command=self._generate_cascadia_selected).pack(
                          anchor="w", padx=8, pady=(8, 0))

        elif self._effect_sort == "pan":
            box = tk.Frame(parent, bg=C_CARD, padx=8, pady=6)
            box.pack(fill="x", padx=6, pady=(6, 0))
            tk.Label(box, text="🎚 Pan position (DAW)", bg=C_CARD, fg="#9fdcff",
                     font=("Segoe UI", 10, "bold")).pack(anchor="w")
            for i in ids:
                pan = self.PAN_BASE.get(i, "Centre")
                row = tk.Frame(box, bg=C_CARD)
                row.pack(fill="x", pady=1)
                tk.Label(row, text=id2inst[i]["name"], bg=C_CARD, fg=C_FG,
                         font=FONT_SMALL, width=20, anchor="w").pack(side="left")
                tk.Label(row, text=pan, bg=C_CARD, fg="#9fdcff",
                         font=FONT_SMALL, wraplength=180, justify="left",
                         anchor="w").pack(side="left", fill="x", expand=True)
            # Glossary for the two terms that aren't a single L–R position.
            gloss = tk.Frame(parent, bg=C_BG2, padx=8, pady=2)
            gloss.pack(fill="x")
            for term, expl in self.PAN_TERMS:
                line = tk.Frame(gloss, bg=C_BG2)
                line.pack(fill="x", pady=(4, 0))
                tk.Label(line, text=term, bg=C_BG2, fg="#9fdcff",
                         font=("Segoe UI", 8, "bold"), width=10, anchor="nw").pack(side="left")
                tk.Label(line, text=expl, bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
                         wraplength=260, justify="left", anchor="w").pack(side="left",
                         fill="x", expand=True)

        elif self._effect_sort == "lowcut":
            tk.Label(parent, text="  🔻 Low cut (Lowtility) — first in the chain · "
                                  "grouped by identical Hz · dB/oct",
                     bg=C_BG2, fg=LOWCUT_COLOUR, font=FONT_SMALL).pack(anchor="w", padx=8)
            tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x", pady=(4, 0))
            # Group instruments that share the SAME corner Hz AND slope into ONE
            # section, each with its own colour — identical Lowtility settings sit
            # together (one preset / one channel-strip value covers the whole group).
            groups = {}
            for i in ids:
                if i in LOWCUT:
                    groups.setdefault(LOWCUT[i], []).append(i)
            # Distinct colour per setting (cycles if there are many groups).
            palette = ["#e6b85c", "#7fd1e6", "#9fe0a0", "#e69fd1", "#d1c47f",
                       "#c79fe6", "#e6a07f", "#9fb6e6", "#bfe67f", "#e67f9f"]
            for idx, key in enumerate(sorted(groups, key=lambda k: (k[0], k[1]))):
                hz, slope = key
                section(f"🔻 {hz} Hz · {slope} dB/oct", palette[idx % len(palette)],
                        names(groups[key]), extra=f"{len(groups[key])} track"
                        + ("s" if len(groups[key]) != 1 else ""))

    # Highlight colour for a band whose value was changed by the mix.
    C_CHANGED = "#ffd479"

    # ---- "HOW MANY" ON THE SELECTED-INSTRUMENTS ROW -------------------------
    # The count used to be editable only on the instrument card (three tabs
    # away) and in Song Variants, while the panel you actually mix from could
    # only PRINT it as ✖3. Since the count changes real advice — the stacking
    # gain, the pan ladder, the high-pass ladder, and now whether a bass gets a
    # Virtual Stage option at all — it belongs on the row where you read that
    # advice. The Spinbox shares self._vcount_vars[iid] with the card and the
    # Variants tab, so Tk keeps all three in step for free.

    def _reset_count(self, iid):
        """Put one instrument back to a single instance."""
        if self._count_of(iid) == 1:
            return                       # already 1 — don't redraw for nothing
        self._vcount_vars[iid].set("1")
        self._on_count_change(iid)

    def _count_control(self, parent, iid, bg=C_BG3):
        """'✖ [n] ↺' for one instrument, sitting in the block header.

        The ↺ is always there rather than appearing at 2 and vanishing at 1:
        a control that comes and goes moves everything beside it every time
        you spin the number, and this row is read while you work. At a count
        of 1 it is simply a no-op (see _reset_count).

        These widgets live INSIDE the panel that _refresh_summary() destroys,
        so the count handler is told where the edit came from and skips the
        rebuild — see _on_count_change."""
        box = tk.Frame(parent, bg=bg)
        box.pack(side="left", padx=(8, 0))
        tk.Label(box, text="✖", bg=bg, fg=MULTI_COLOUR,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        spin = tk.Spinbox(box, from_=1, to=MAX_INSTRUMENT_COUNT, width=2,
                          textvariable=self._vcount_vars[iid], justify="center",
                          bg=C_BG2, fg=MULTI_COLOUR,
                          buttonbackground=C_BG2,
                          insertofftime=0, insertontime=9999999,   # no blinking cursor
                          relief="flat", highlightthickness=0,
                          font=FONT_SMALL, wrap=False,
                          command=lambda i=iid: self._on_count_change(i, from_summary=True))
        spin.pack(side="left", padx=(2, 0))
        spin.bind("<Return>",
                  lambda e, i=iid: self._on_count_change(i, from_summary=True))
        spin.bind("<FocusOut>",
                  lambda e, i=iid: self._on_count_change(i, from_summary=True))
        tk.Button(box, text="↺", bg=bg, fg=C_ACCENT,
                  activebackground=bg, activeforeground=C_FG,
                  font=("Segoe UI", 8, "bold"), relief="flat", bd=0,
                  padx=3, pady=0, cursor="hand2",
                  command=lambda i=iid: self._reset_count(i)).pack(side="left")
        return box

    def _header_tags(self, hdr, iid):
        """v3.32: the three things he looks for first, on the name row of a Selected Instruments
        block: smart:EQ tier - reverb depth - duck source, e.g. 'MID - NEAR - Duck vocal'.
        EQ comes first because that is the first plug-in in the chain. Same sources as the
        footnotes below (SMARTEQ_GROUP, DEPTH, ducking_for), so pairs and the line-up count.
        Packed AFTER the More button, so a narrow panel clips these first, never the button."""
        parts = []                                    # (text, colour)
        g = SMARTEQ_GROUP.get(iid)
        if g:
            tier = g[0]
            parts.append((tier.upper(), self._TIER_GLYPH.get(tier, ("", C_FG_DIM))[1]))
        d = DEPTH.get(iid)
        if d:
            parts.append((DEPTH_SPEC.get(d[0], {}).get("label", str(d[0]).upper()), DEPTH_COLOUR))
        raw = DUCKING.get(iid)
        if raw:
            try:
                sel = set(self._checked_ids())
            except Exception:
                sel = set()
            if not (iid in sel and not duck_source_present(raw["src"], sel)):
                who = {"Lead Vocal": "vocal"}.get(raw["src"], str(raw["src"]).lower())
                parts.append(("Duck " + who,
                              DUCK_SRC_COLOURS.get(raw["src"], DUCK_SRC_DEFAULT)))
        if not parts:
            return
        box = tk.Frame(hdr, bg=C_BG3)
        box.pack(side="left", padx=(12, 0))
        for k, (txt, col) in enumerate(parts):
            if k:
                tk.Label(box, text=" - ", bg=C_BG3, fg=C_FG_DIM,
                         font=("Segoe UI", 8, "bold")).pack(side="left")
            tk.Label(box, text=txt, bg=C_BG3, fg=col,
                     font=("Segoe UI", 8, "bold")).pack(side="left")

    def _toggle_block_expand(self, iid):
        if iid in self._expanded_blocks:
            self._expanded_blocks.discard(iid)
        else:
            self._expanded_blocks.add(iid)
        self._refresh_summary()

    def _build_summary_block(self, parent, inst, rec=None, filters=None):
        """One instrument block, laid out TOP→BOTTOM in Cubase insert order
        (Low cut → Kirchhoff → smart:EQ → Duck → Pan/M/S → reverb). Collapsed by
        default (short, factual — just the orders); the expand button reveals the
        explanations, 'Changed vs base', settings and the static tip.

        `filters` is the set of ticked keys from the 📋 Instruments-view filter
        row (lowcut/eq/eqgroup/comp/submass/pan/duck/reverb). Empty/None = show every
        section (the old, unfiltered behaviour); otherwise ONLY the matching
        section(s) are built, so you can scan e.g. just Comp. across channels."""
        rec = rec or {}
        filters = filters or set()
        show_all = not filters
        iid = inst["id"]
        exp = iid in self._expanded_blocks
        eff_bands, change_lines = self._apply_edits(inst, rec.get("edits", []))
        notes = rec.get("notes", [])
        pan   = rec.get("pan", "")
        adjusted = any(b.get("_changed") for b in eff_bands)
        kirch = (self.eq_mode.get() == "kirchhoff")
        stereo = rec.get("stereo", "") if kirch else ""

        # The whole block shares ONE background (C_CARD) so related lines never
        # look like they sit in different boxes.
        block = tk.Frame(parent, bg=C_CARD, relief="flat", bd=0)
        block.pack(fill="x", padx=6, pady=(6, 0))

        # ---- Name header (with the expand/collapse toggle) ----
        hdr = tk.Frame(block, bg=C_BG3, padx=8, pady=4)
        hdr.pack(fill="x")
        dot_color = inst.get("color", C_FG)
        tk.Label(hdr, text="●", fg=dot_color, bg=C_BG3, font=("Segoe UI", 10)).pack(side="left")
        tk.Label(hdr, text=f"  {inst['name']}", bg=C_BG3, fg=C_FG,
                 font=FONT_HEADER).pack(side="left")
        n_of = self._count_of(iid)
        self._count_control(hdr, iid, bg=C_BG3)
        if adjusted:
            tk.Label(hdr, text="  ✎", bg=C_BG3, fg=self.C_CHANGED,
                     font=("Segoe UI", 8, "bold")).pack(side="left")
        tk.Button(hdr, text=("▼ Less" if exp else "▶ More"),
                  bg=C_BG3, fg=C_ACCENT, activebackground=C_BG3, activeforeground=C_FG,
                  font=("Segoe UI", 8, "bold"), relief="flat", bd=0, padx=4, pady=0,
                  cursor="hand2", command=lambda i=iid: self._toggle_block_expand(i)
                  ).pack(side="right")
        if exp:
            tk.Label(hdr, text=f"({inst['sub']})", bg=C_BG3, fg=C_FG_DIM,
                     font=FONT_SMALL).pack(side="right", padx=(0, 6))
        self._header_tags(hdr, iid)       # v3.32: 'MID - NEAR - Duck vocal' on the name row

        # ---- 0. The low-end channels get ONE permanent row ----
        has_lowend_row = bool(submass_for(iid))
        # Only the four channels that have a SubMass entry (kick and the
        # basses). Outside the filter row on purpose: he asked for a
        # PERMANENT row, and these are the three or four settings he wants
        # to see together without hunting for which box reveals them. The
        # footnotes below still carry the reasons - this replaces the
        # hunting, not the explanations.
        # Live, because the Double Bass's Stage field and the ✖N line both
        # move with the line-up.
        if has_lowend_row:
            self._live_note(
                block, C_CARD,
                lambda h, i=iid, e=exp: self._fill_lowend_row(
                    h, i, C_CARD, 600, e))

        # ---- 1. Low cut (Lowtility) — first in the chain ----
        # Skipped on the four low-end channels: the permanent row above
        # already states the corner and the slope, and this footnote is a
        # head line with nothing under it, so there is nothing else in it
        # to keep.
        if (show_all or "lowcut" in filters) and not has_lowend_row:
            self._build_lowcut_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp)

        # ---- 1b. 🔥 Omega 458a — the input stage, before the EQ ----
        if show_all or "omega" in filters:
            self._build_omega_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp)

        # ---- 2. Kirchhoff EQ (effective bands) ----
        if show_all or "eq" in filters:
            bands_frame = tk.Frame(block, bg=C_CARD, padx=8, pady=4)
            bands_frame.pack(fill="x")
            tk.Label(bands_frame, text="🎛 Kirchhoff EQ", bg=C_CARD, fg=C_ACCENT,
                     font=("Segoe UI", 8, "bold"), anchor="w").pack(fill="x")
            for band in eff_bands:
                btype = band["type"]
                tcol  = TYPE_COLOR.get(btype, C_NEUTRAL)
                changed = bool(band.get("_changed"))
                first_fg = self.C_CHANGED if changed else C_FG
                mark = "✎" if changed else " "
                is_hp = band.get("filter") == "High-pass"
                note  = band["note"]
                if is_hp:
                    note = f"({note} — exclude, Lowtility does it)"
                note_fg = "#8a93a8" if is_hp else C_FG_DIM
                row = tk.Frame(bands_frame, bg=C_CARD)
                row.pack(fill="x", pady=1)
                tk.Label(row, text=mark, bg=C_CARD, fg=self.C_CHANGED,
                         font=("Segoe UI", 8, "bold"), width=1, anchor="w").pack(side="left")
                self._hearing_cell(row, band, bg=C_CARD)
                if kirch:
                    k = kirchhoff_band(band)
                    tk.Label(row, text=k["freq"], bg=C_CARD, fg=(note_fg if is_hp else first_fg),
                             font=FONT_MONO, width=8, anchor="w").pack(side="left")
                    tk.Label(row, text=KTYPE_SHORT.get(k["ktype"], "Bell"),
                             bg=C_CARD, fg=(note_fg if is_hp else C_ACCENT),
                             font=("Segoe UI", 8, "bold"), width=6, anchor="w").pack(side="left")
                    tk.Label(row, text=k["gain"], bg=C_CARD, fg=(note_fg if is_hp else tcol),
                             font=("Consolas", 8, "bold"), width=9, anchor="w").pack(side="left")
                    tk.Label(row, text="Q" + k["q"], bg=C_CARD, fg=note_fg,
                             font=FONT_MONO, width=6, anchor="w").pack(side="left")
                    tk.Label(row, text=k["slope"], bg=C_CARD, fg=note_fg,
                             font=FONT_SMALL, width=9, anchor="w").pack(side="left")
                    tk.Label(row, text=note, bg=C_CARD, fg=note_fg,
                             font=FONT_SMALL, anchor="w").pack(side="left", fill="x", expand=True)
                else:
                    tlbl = TYPE_LABEL.get(btype, "—")
                    db   = band["db"]
                    if btype == "char":
                        lo, hi = band.get("db_lo"), band.get("db_hi")
                        if lo is not None and hi is not None:
                            db_str = f"{('+'+str(lo)) if lo>0 else lo}→{('+'+str(hi)) if hi>0 else hi}"
                        else:
                            db_str = f"±{abs(db)}" if db != 0 else "±?"
                    else:
                        db_str = f"+{db} dB" if db > 0 else f"{db} dB" if db != 0 else "—"
                    tk.Label(row, text=band["hz"], bg=C_CARD, fg=(note_fg if is_hp else first_fg),
                             font=FONT_MONO, width=11, anchor="w").pack(side="left")
                    tk.Label(row, text=tlbl, bg=C_CARD, fg=(note_fg if is_hp else tcol),
                             font=("Segoe UI", 8, "bold"), width=7, anchor="w").pack(side="left")
                    tk.Label(row, text=db_str, bg=C_CARD, fg=(note_fg if is_hp else tcol),
                             font=("Consolas", 8, "bold"), width=7, anchor="w").pack(side="left")
                    tk.Label(row, text=note, bg=C_CARD, fg=note_fg,
                             font=FONT_SMALL, anchor="w").pack(side="left", fill="x", expand=True)
                if not is_hp:
                    self._hearing_band_note(bands_frame, band, bg=C_CARD, wrap=290)

            # ---- 'Changed vs base' (EXPANDED only) ----
            if exp and change_lines:
                cf = tk.Frame(block, bg=C_CARD, padx=8, pady=2)
                cf.pack(fill="x")
                tk.Label(cf, text="▶ Changed vs base settings:", bg=C_CARD, fg=C_ACCENT,
                         font=("Segoe UI", 8, "bold"), anchor="w").pack(fill="x")
                for line in change_lines:
                    tk.Label(cf, text="• " + line, bg=C_CARD, fg=self.C_CHANGED,
                             font=FONT_SMALL, wraplength=300, justify="left",
                             anchor="w").pack(fill="x")

            # ---- 'Also do' (visible in DEFAULT) ----
            if notes:
                nf = tk.Frame(block, bg=C_CARD, padx=8, pady=2)
                nf.pack(fill="x")
                tk.Label(nf, text="▶ Also do (for this mix):", bg=C_CARD, fg=C_ACCENT,
                         font=("Segoe UI", 8, "bold"), anchor="w").pack(fill="x")
                for n in notes:
                    tk.Label(nf, text="• " + n, bg=C_CARD, fg="#cdd6e6",
                             font=FONT_SMALL, wraplength=300, justify="left",
                             anchor="w").pack(fill="x")

        # ---- 3. smart:EQ group ----
        if show_all or "eqgroup" in filters:
            self._build_smarteq_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp)

        # ---- 4. Compressor (after EQ, before reverb — chain order) ----
        if show_all or "comp" in filters:
            self._build_comp_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp)

        # ---- 4a. SubMass (tracked sub 'feel') ----
        # Skipped whenever the permanent row is there, which is exactly the
        # channels this footnote would have printed on. Its note moved into
        # the row; its head line was the duplicate.
        if (show_all or "submass" in filters) and not has_lowend_row:
            self._build_submass_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp)

        # ---- 4a2. KNOCK (drum / punch processor). Opt-in: the '\U0001f94a Knock' box in the Filter row. ----
        if show_all or "knock" in filters:
            self._build_knock_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp)

        # ---- 4b. Duck ----
        if show_all or "duck" in filters:
            self._build_ducking_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp,
                                         explain_missing=False)

        # ---- 5. Pan (default) + Kirchhoff M/S (expanded) ----
        if show_all or "pan" in filters:
            if pan:
                tk.Label(block, text="🎚 Pan (DAW):  " + pan, bg=C_CARD, fg="#9fdcff",
                         font=("Segoe UI", 8, "bold"), wraplength=300, justify="left",
                         anchor="w").pack(fill="x", padx=10, pady=(6, 0))
            if exp and stereo:
                tk.Label(block, text="🎛 Kirchhoff M/S:  " + stereo, bg=C_CARD, fg="#b9a6ff",
                         font=("Segoe UI", 8, "bold"), wraplength=300, justify="left",
                         anchor="w").pack(fill="x", padx=10, pady=(2, 0))

        # ---- 5b. 🎪 Virtual Stage — replaces the pan AND the reverb send
        # on this channel (see VSTAGE_CHAIN), so it sits between the two ----
        if show_all or "stage" in filters:
            # head=False on the low-end channels - the permanent row at the
            # top of the block already prints that line. The footnote itself
            # still builds: the ✖N bass option, the `because` lines and the
            # `why` are all only here.
            self._build_vstage_footnote(block, iid, bg=C_CARD, wrap=600,
                                        expanded=exp,
                                        head=not has_lowend_row)
        elif iid in self._swam_for_engines():
            self._build_swam_footnote(block, iid, bg=C_CARD, wrap=600)     # v3.29: never filtered out

        # ---- 5c. ↔ Bandwidth — stereo width, after pan / Stage, before reverb ----
        if show_all or "bandwidth" in filters:
            self._build_bandwidth_footnote(block, iid, bg=C_CARD, wrap=600,
                                           expanded=exp)

        # ---- 6. Depth (reverb) ----
        if show_all or "reverb" in filters:
            self._build_depth_footnote(block, iid, bg=C_CARD, wrap=600, expanded=exp,
                                       sel=self._checked_ids())

        # ---- 6b. 🌀 Corridor — the named preset for this channel ----
        if show_all or "corridor" in filters:
            self._build_corridor_footnote(block, iid, bg=C_CARD, wrap=600,
                                          expanded=exp, sel=self._checked_ids())

        # ---- 6c. ≈ Cascadia — the delay send, last in the chain ----
        if show_all or "cascadia" in filters:
            self._build_cascadia_footnote(block, iid, bg=C_CARD, wrap=600,
                                          expanded=exp, sel=self._checked_ids())

        # ---- 7. ✖N Multiples — only when the count is above 1 ----
        if show_all or "multi" in filters:
            self._live_multi(block, C_CARD,
                             lambda h, i=iid, e=exp:
                                 self._fill_multi(h, i, bg=C_CARD, wrap=300,
                                                  expanded=e),
                             iid=iid)

        # ---- Static tip (EXPANDED only, and only in the unfiltered view — it's
        # general mix advice, not tied to any one filtered section) ----
        if exp and show_all and self._show_extra():
            tip_txt = partner_note("tip", iid, inst["tip"], self._checked_ids())
            tk.Label(block, text="💡 " + tip_txt, bg=C_CARD, fg=C_FG_DIM,
                     font=FONT_SMALL, wraplength=300, justify="left",
                     anchor="w").pack(fill="x", padx=10, pady=(6, 6))

        # ---- Nothing under the ticked filter(s)? Then do not print a whole
        # header block with a hole under it - one slim, dim line says it. ----
        if filters and len(block.winfo_children()) <= 1:
            for w in block.winfo_children():
                w.destroy()
            row = tk.Frame(block, bg=C_CARD, padx=8, pady=2)
            row.pack(fill="x")
            tk.Label(row, text="\u25cf", fg=dot_color, bg=C_CARD,
                     font=("Segoe UI", 8)).pack(side="left")
            tk.Label(row, text=f"  {inst['name']}  \u2014  nothing under this filter",
                     bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left")

        tk.Frame(parent, bg=C_SEP, height=1).pack(fill="x", padx=6)

    # ---- KIRCHHOFF PRESET GENERATION ----------------------------------------

    def _keq_target_dir(self):
        """Resolve the Kirchhoff /presets folder (setting, or %APPDATA% default)."""
        d = (self.settings.get("keq_dir", "") or "").strip()
        if d:
            return d
        appdata = os.environ.get("APPDATA", "")
        if appdata:
            return os.path.join(appdata, "ThreeBodyTech", "KirchhoffEQ", "presets")
        return ""

    def _keq_registry_path(self):
        return os.path.join(get_helpfiles_dir(PRESETS_KIRCHHOFF), "registry.json")

    def _keq_load_registry(self):
        try:
            with open(self._keq_registry_path(), "r", encoding="utf-8") as f:
                r = json.load(f)
            if isinstance(r, dict) and isinstance(r.get("presets"), list):
                return r
        except Exception:
            pass
        return {"presets": []}

    def _keq_save_registry(self, reg):
        try:
            with open(self._keq_registry_path(), "w", encoding="utf-8") as f:
                json.dump(reg, f, indent=2, ensure_ascii=False)
        except Exception:
            pass

    def _keq_signature(self, iid, params):
        """A stable fingerprint of an instrument's effective EQ — identical EQ
        (even from a different song) dedups to the SAME preset."""
        parts = [iid]
        for p in params:
            g = "hp" if p["gain_db"] is None else f"{p['gain_db']:+.1f}"
            parts.append("%s|%d|%s|%.2f|%.3f|%.2f" % (
                p["ktype"][:2], round(p["freq_hz"]), g,
                p["q_val"], p["slope_norm"], p["sp_norm"]))
        return ";".join(parts)

    def _keq_preset_name(self, iid, clashers, reg, nohp=False):
        label = self.KEQ_LABEL.get(iid, iid)
        if nohp:                       # Lowtility does the high-pass → tag it
            label = f"{label}_(lowtility)"
        # NO date in the name (his call, 2026-10-31; DEL 02s): the name says what the
        # preset IS. An EQ that changes later takes over the same name - the old file is
        # backed up as '.bak' by write_preset_file(), and the registry entry is replaced.
        if clashers:
            tags = "_".join(sorted(self.KEQ_LABEL.get(c, c).lower() for c in clashers))
            return f"{label}---Group---{tags}"
        return f"{label}---Solo"

    def _put(self, path, data, label=""):
        """write_preset_file(), remembering what it replaced for the report window."""
        state, bak = write_preset_file(path, data)
        if bak:
            if not hasattr(self, "_replaced"):
                self._replaced = []
            self._replaced.append((label or os.path.basename(path), bak))
        return state

    def _replaced_section(self, txt):
        """Report block: the files this run replaced and where their old versions went.
        Does nothing when nothing was replaced."""
        rep = getattr(self, "_replaced", [])
        if not rep:
            return
        txt.insert("end", f"\nREPLACED - the old version of {len(rep)} file(s) is kept "
                          "beside it as '.bak':\n", "h")
        for label, bak in rep:
            txt.insert("end", f"  ~ {label}\n", "warn")
            txt.insert("end", f"      {os.path.basename(bak)}\n", "re")
        txt.insert("end", "  (Plug-ins and Cubase only list the real presets - a .bak is never "
                          "shown in a preset list.\n   Delete the .bak files whenever you "
                          "are happy with the new versions.)\n", "re")

    def _keq_sp_for(self, iid, k):
        """Stereo Placement code for a band (only when 'Bake M/S' is ON).
        Air/high-shelf boost → Side (only for genuinely WIDE sources — a mono/centre
        track has no Side signal); a low-mid mud cut → Mid; else Stereo."""
        if not self.keq_ms_var.get():
            return KEQ_SP["stereo"]
        ktype, hz, g = k["ktype"], k["freq_hz"], k["gain_db"]
        if ktype == KTYPE_HSHELF and (g or 0) > 0 and iid in KEQ_WIDE_IDS:
            return KEQ_SP["side"]
        if ktype == KTYPE_BELL and g is not None and g < 0 and 150 <= hz <= 600:
            return KEQ_SP["mid"]
        return KEQ_SP["stereo"]

    def _generate_presets_selected(self):
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        self._generate_presets(checked, constellation=True,
                               source_label=(self.current_variant or "selected"))

    def _generate_presets_all(self):
        self._generate_presets([x["id"] for x in EQ_DATA], constellation=False,
                               source_label="ALL_solo")

    def _on_keq_ms_toggle(self):
        self.settings["keq_bake_ms"] = bool(self.keq_ms_var.get())
        save_settings(self.settings)

    def _on_keq_nohp_toggle(self):
        self.settings["keq_no_hp"] = bool(self.keq_nohp_var.get())
        save_settings(self.settings)

    def _on_keq_vst3_toggle(self):
        self.settings["keq_make_vst3"] = bool(self.keq_vst3_var.get())
        save_settings(self.settings)

    def _keq_vst3_target_dir(self):
        """Resolve the Kirchhoff .vstpreset (Cubase) folder (setting, or default)."""
        d = (self.settings.get("keq_vst3_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets",
                            "Plugin Alliance", "TBTECH Kirchhoff-EQ")

    def _keq_vst3_template(self):
        """Bytes of an existing .vstpreset in the Cubase folder, used as the wrapper
        template (any user/factory one; skips the ones this program generated)."""
        folder = self._keq_vst3_target_dir()
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")]
        except Exception:
            return None
        # Prefer the user's OWN presets as the template, not our generated ones
        # (see is_generated_name); any valid one works as a fallback.
        pref = [f for f in files if not is_generated_name(f)]
        for f in (pref or files):
            try:
                with open(f, "rb") as fh:
                    return fh.read()
            except Exception:
                continue
        return None

    def _set_keq_vst3_folder(self):
        cur = self._keq_vst3_target_dir()
        val = self._ask_string("Kirchhoff .vstpreset (Cubase) folder",
                               "Full path to the Cubase Kirchhoff preset folder\n"
                               "(…\\VST3 Presets\\Plugin Alliance\\TBTECH Kirchhoff-EQ):",
                               initial=cur)
        if val is None:
            return
        self.settings["keq_vst3_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Kirchhoff .vstpreset folder.")

    def _set_keq_folder(self):
        cur = self._keq_target_dir()
        val = self._ask_string("Kirchhoff preset folder",
                               "Full path to Kirchhoff's  …\\KirchhoffEQ\\presets  folder:",
                               initial=cur)
        if val is None:
            return
        self.settings["keq_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Kirchhoff preset folder.")

    # ---- SONIBLE smart:reverb / smart:EQ PRESETS ----------------------------

    def _sonible_reverb_dir(self):
        """Resolve the smart:reverb 2 preset folder (setting, or Documents default)."""
        d = (self.settings.get("smartreverb_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets", "sonible", "smartReverb2")

    def _sonible_seed(self, folder):
        """Pick a reference .vstpreset in `folder` to use as the patch/clone seed.
        Prefers a name containing 'lead'/'vocal' (the user's reference preset),
        else the most-recently-modified .vstpreset. Returns a path or None."""
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")
                     and not f.startswith("0---")]   # skip our own generated slots
        except Exception:
            return None
        if not files:
            return None
        pref = [f for f in files if any(k in os.path.basename(f).lower()
                                        for k in ("lead", "vocal"))]
        return max(pref or files, key=lambda f: os.path.getmtime(f))

    def _set_smartreverb_folder(self):
        cur = self._sonible_reverb_dir()
        val = self._ask_string("smart:reverb preset folder",
                               "Full path to the sonible  …\\sonible\\smartReverb2  folder:",
                               initial=cur)
        if val is None:
            return
        self.settings["smartreverb_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved smart:reverb preset folder.")

    # ---- VENOMODE LOWTILITY 2 (high-pass) PRESETS ---------------------------

    def _lowtility_dir(self):
        """Resolve the Lowtility 2 preset folder (setting, or Documents default)."""
        d = (self.settings.get("lowtility_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets", "Venomode", "Lowtility 2")

    def _lowtility_template(self):
        """Bytes of an existing Lowtility .vstpreset to use as the wrapper template
        (prefers the user's own; skips the ones this program generated)."""
        folder = self._lowtility_dir()
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")]
        except Exception:
            return None
        pref = [f for f in files if not is_generated_name(f)]
        for f in (pref or files):
            try:
                with open(f, "rb") as fh:
                    return fh.read()
            except Exception:
                continue
        return None

    def _set_lowtility_folder(self):
        cur = self._lowtility_dir()
        val = self._ask_string("Lowtility preset folder",
                               "Full path to the Venomode  …\\Venomode\\Lowtility 2  folder:",
                               initial=cur)
        if val is None:
            return
        self.settings["lowtility_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Lowtility preset folder.")

    def _generate_lowtility_selected(self):
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        self._generate_lowtility_presets(checked)

    def _generate_lowtility_all(self):
        self._generate_lowtility_presets([x["id"] for x in EQ_DATA])

    def _generate_lowtility_presets(self, ids):
        """One Lowtility 2 .vstpreset per instrument with the EXACT low-cut corner
        Hz + slope from the LOWCUT chart, patched into a template the user already
        has. Name: '<Label>---Lowcut.vstpreset' (no date; a replaced file is kept as
        '.bak', DEL 02s)."""
        by_id = {x["id"]: x for x in EQ_DATA}
        ids = [i for i in ids if i in by_id and i in LOWCUT]
        folder = self._lowtility_dir()
        ok = os.path.isdir(folder)
        tpl = self._lowtility_template() if ok else None
        overwrite = self._ow("Lowtility")
        help_dir = get_helpfiles_dir(PRESETS_LOWTILITY)
        self._replaced = []

        made, skip, errors = [], [], []
        if tpl:
            for iid in ids:
                hz, slope = LOWCUT[iid]
                fn = f"{self.KEQ_LABEL.get(iid, iid)}---Lowcut.vstpreset"
                dst = os.path.join(folder, fn)
                if os.path.exists(dst) and not overwrite:
                    skip.append((iid, fn))
                    continue
                try:
                    vp = make_lowtility_preset(tpl, hz, slope)
                    if not vp:
                        errors.append((iid, "build failed"))
                        continue
                    self._put(dst, vp, fn)
                    try:
                        self._put(os.path.join(help_dir, fn), vp, fn + "  [Helpfiles copy]")
                    except Exception:
                        pass                    # the Helpfiles copy is only a backup
                    made.append((iid, fn, hz, slope))
                except Exception as e:
                    errors.append((iid, str(e)))
        self._lowtility_report(made, skip, errors, folder, ok, tpl is not None, help_dir)

    def _lowtility_report(self, made, skip, errors, folder, ok, had_tpl, help_dir):
        id2name = {x["id"]: x["name"] for x in EQ_DATA}
        top = tk.Toplevel(self.root)
        top.title("Lowtility presets")
        top.configure(bg=C_BG)
        top.geometry("640x520")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🔻  Lowtility (high-pass) presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999, padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"{len(made)} created · {len(skip)} kept\n\n", "h")
        if not ok:
            txt.insert("end", f"Folder not found:\n  {folder}\n"
                              "  Set it via  File ▸ Set Lowtility preset folder…\n\n", "warn")
        elif not had_tpl:
            txt.insert("end", "No template .vstpreset found. Save ONE Lowtility preset from "
                              f"Cubase into:\n  {folder}\n  then run this again.\n\n", "warn")
        if made:
            txt.insert("end", "Created (corner Hz · slope dB/oct):\n", "h")
            for iid, fn, hz, slope in made:
                txt.insert("end", f"  + {id2name.get(iid, iid):22s} {hz} Hz · {slope} dB/oct → {fn}\n", "ok")
            txt.insert("end", "\n")
        if skip:
            txt.insert("end", "Kept (already exist — generate again and answer Overwrite to replace):\n", "h")
            for iid, fn in skip:
                txt.insert("end", f"  · {id2name.get(iid, iid):22s} {fn}\n", "re")
            txt.insert("end", "\n")
        if errors:
            txt.insert("end", "Problems:\n", "warn")
            for iid, msg in errors:
                txt.insert("end", f"  ! {id2name.get(iid, iid)}: {msg}\n", "warn")
            txt.insert("end", "\n")
        if made:
            txt.insert("end", "These show in CUBASE's preset selector (Lowtility).\n"
                              f"Backups in:\n  {help_dir}\n", "re")
        self._replaced_section(txt)
        txt.configure(state="disabled")
        top.bind("<Escape>", lambda e: top.destroy())
        top.grab_set()
        top.focus_force()

    # ---- DSPTONE SUBMASS (tracked sub-harmonic 'feel') ----------------------

    def _submass_dir(self):
        """Resolve the SubMass preset folder (setting, or Documents default —
        matches c:\\Users\\<you>\\Documents\\VST3 Presets\\DSPTone\\SubMass)."""
        d = (self.settings.get("submass_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets", "DSPTone", "SubMass")

    def _submass_template(self):
        """Bytes of an existing SubMass .vstpreset to use as the seed (prefers
        the user's own; skips the ones this program generated, see is_generated_name)."""
        folder = self._submass_dir()
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")]
        except Exception:
            return None
        pref = [f for f in files if not is_generated_name(f)]
        for f in (pref or files):
            try:
                with open(f, "rb") as fh:
                    return fh.read()
            except Exception:
                continue
        return None

    # ---- 🌀 CORRIDOR (Quantastical Sound) -----------------------------------
    # Unlike the sonible engines, Corridor's state is readable XML, so these are
    # REAL presets built from the chart — not a seed cloned under a new name.
    # A seed is still needed, but only as a container: the class id, the JUCE
    # trailer and the <RoomPans> listening positions are carried across from it
    # so the file is guaranteed to be one this exact build already accepts.

    def _corridor_dir(self):
        d = (self.settings.get("corridor_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets",
                            CORRIDOR_VENDOR, CORRIDOR_NAME)

    def _corridor_template(self):
        """Bytes of a Corridor preset to use as the container. Prefers one the
        user made himself over anything this program generated (see
        is_generated_name), because his own is the one proven to load."""
        folder = self._corridor_dir()
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")]
        except Exception:
            return None
        pref = [f for f in files if not is_generated_name(f)]
        for f in (pref or files):
            try:
                with open(f, "rb") as fh:
                    data = fh.read()
                if b"CorridorParameters" in data:
                    return data
            except Exception:
                continue
        return None

    def _set_corridor_folder(self):
        cur = self._corridor_dir()
        val = self._ask_string("Corridor preset folder",
                               "Full path to the  …\\VST3 Presets\\Quantastical "
                               "Sound\\Corridor  folder:",
                               initial=cur)
        if val is None:
            return
        self.settings["corridor_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Corridor preset folder.")

    def _generate_corridor_selected(self):
        """Only the presets the ticked instruments actually call for."""
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        keys, seen = [], set()
        for iid in checked:
            pre, alts = corridor_for(iid, set(checked))
            for pr in ([pre] if pre else []) + alts:
                if pr["key"] not in seen:
                    seen.add(pr["key"])
                    keys.append(pr["key"])
        if not keys:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME,
                                "None of the ticked channels takes a reverb — "
                                "the kick and the basses stay dry, so Corridor "
                                "has nothing to write for them.",
                                parent=self.root)
            return
        self._generate_corridor_presets(keys)

    def _generate_corridor_all(self):
        self._generate_corridor_presets([p["key"] for p in CORRIDOR_PRESETS])

    def _generate_corridor_presets(self, keys):
        """Write one .vstpreset per named Corridor preset.
        Name: 'Corridor---<Preset Name>.vstpreset' (no date; a replaced file is kept as
        '.bak', DEL 02s)."""
        folder = self._corridor_dir()
        ok = os.path.isdir(folder)
        tpl = self._corridor_template() if ok else None
        overwrite = self._ow("Corridor")
        help_dir = get_helpfiles_dir(PRESETS_CORRIDOR)
        self._replaced = []

        made, skip, errors = [], [], []
        if tpl:
            for key in keys:
                pr = CORRIDOR_BY_KEY.get(key)
                if not pr:
                    continue
                safe = _re.sub(r"[^A-Za-z0-9 ·&_-]", "", pr["name"]).strip()
                fn = f"Corridor---{safe}.vstpreset"
                dst = os.path.join(folder, fn)
                if os.path.exists(dst) and not overwrite:
                    skip.append((pr, fn))
                    continue
                try:
                    vp = make_corridor_preset(tpl, corridor_params(pr))
                    # Read it straight back: a preset that does not survive its
                    # own round trip must never reach the plug-in folder.
                    back = read_corridor_values(vp)
                    if not back:
                        errors.append((pr["name"], "could not be read back"))
                        continue
                    self._put(dst, vp, fn)
                    try:
                        self._put(os.path.join(help_dir, fn), vp, fn + "  [Helpfiles copy]")
                    except Exception:
                        pass                    # the Helpfiles copy is only a backup
                    made.append((pr, fn))
                except Exception as e:
                    errors.append((pr["name"], str(e)))
        self._corridor_report(made, skip, errors, folder, ok, tpl is not None,
                              help_dir)

    def _corridor_report(self, made, skip, errors, folder, ok, had_tpl, help_dir):
        top = tk.Toplevel(self.root)
        top.title("Corridor presets")
        top.configure(bg=C_BG)
        top.geometry("760x600")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🌀  Corridor reverb presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999,
                      padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"{len(made)} created · {len(skip)} kept\n\n", "h")
        if not ok:
            txt.insert("end", f"Folder not found:\n  {folder}\n"
                              "  Set it via  File ▸ Set Corridor preset folder…\n\n",
                       "warn")
        elif not had_tpl:
            txt.insert("end",
                       "No Corridor preset found to use as the container. Save ONE "
                       f"preset out of Corridor into:\n  {folder}\n"
                       "  then run this again. (Your 'corridor-test' is exactly "
                       "what it needs.)\n\n", "warn")
        if made:
            txt.insert("end", "Created:\n", "h")
            for pr, fn in made:
                p = pr["params"]
                txt.insert("end", f"  + {pr['name']}\n", "ok")
                txt.insert("end", f"      Mix {p.get('mix', 0):g} %  ·  Decay "
                                  f"{p.get('decay', 0):g}  ·  Pre-Delay "
                                  f"{p.get('predelay', 0):g} ms  ·  Size "
                                  f"{p.get('size', 0):g}\n", "re")
                txt.insert("end", f"      {fn}\n", "re")
            txt.insert("end", "\n")
        if skip:
            txt.insert("end", "Kept (already exist — generate again and answer Overwrite to replace):\n", "h")
            for pr, fn in skip:
                txt.insert("end", f"  · {fn}\n", "re")
            txt.insert("end", "\n")
        if errors:
            txt.insert("end", "Problems:\n", "warn")
            for name, msg in errors:
                txt.insert("end", f"  ! {name}: {msg}\n", "warn")
            txt.insert("end", "\n")
        if made:
            txt.insert("end",
                       "In Cubase these appear in Corridor's own preset browser.\n"
                       f"A copy of each is kept in:\n  {help_dir}\n\n", "re")
        txt.insert("end",
                   "About the numbers: Corridor publishes no ranges anywhere, so "
                   "these are built inside the span your own 'corridor-test' "
                   "preset proves is legal, and every file is read back after it "
                   "is written. The room MODEL is left on the one your test "
                   "preset uses — see CORRIDOR_USE_ROOM_MODELS in the source if "
                   "you want the per-preset rooms instead.\n", "re")
        self._replaced_section(txt)
        txt.config(state="disabled")
        top.bind("<Escape>", lambda e: top.destroy())
        top.focus_set()

    def _build_corridor_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True,
                                 sel=None):
        """A compact '🌀 Corridor' footnote: which preset to load and the
        numbers that make it. Dry channels print nothing — no entry means no
        line, the same rule the depth engine uses."""
        pre, alts = corridor_for(iid, sel)
        if not pre:
            return None
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        self._head_line(frame, "corridor", iid, engine_bits("corridor", iid, sel),
                        bg=bg, fg=CORRIDOR_COLOUR, wrap=wrap)
        # The rest of the knobs are SETTINGS, so they are never hidden — but
        # they are also fields, so they grey out one by one like the head does.
        self._head_line(frame, "corridor", iid,
                        engine_detail_bits("corridor", iid, sel), bg=bg, fg=C_FG_DIM,
                        wrap=wrap, bold=False, detail=True)
        if expanded:
            self._note_label(frame, pre["role"], bg=bg, wrap=wrap, extra=True)
            self._note_label(frame, pre["note"], bg=bg, wrap=wrap, extra=True)
            if alts:
                # The alternatives never change with the song either, so under
                # Δ they go grey with the rest of the section instead of being
                # the one coloured line in an otherwise finished block.
                self._note_label(
                    frame,
                    "Also worth trying:  " + "  ·  ".join(a["name"] for a in alts),
                    bg=bg, fg=(C_DEFAULT if self._diff_on() else CORRIDOR_COLOUR),
                    wrap=wrap, extra=False)
        return self._tighten(frame, True)

    # ---- 🔥 OMEGA 458a (Kush Audio) -----------------------------------------
    # Like Corridor, and unlike the sonible engines, these are REAL presets
    # built from the chart. Better than Corridor, in fact: the plug-in ships its
    # own parameter table, so every value written here is inside a range the
    # plug-in itself declares rather than one inferred from a seed. A seed is
    # still wanted as the CONTAINER (class id, the JUCE trailer, the Info
    # chunk) so the file is one this exact build has already accepted.

    def _omega_dir(self):
        d = (self.settings.get("omega_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets",
                            OMEGA_VENDOR, OMEGA_NAME)

    def _omega_template(self):
        """Bytes of an Omega preset to use as the container. Prefers one the
        user made himself over anything this program generated (see
        is_generated_name), because his own is the one proven to load."""
        folder = self._omega_dir()
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")]
        except Exception:
            return None
        pref = [f for f in files if not is_generated_name(f)]
        for f in (pref or files):
            try:
                with open(f, "rb") as fh:
                    data = fh.read()
                if b"StateInformation" in data and b"INTENSITY" in data:
                    return data
            except Exception:
                continue
        return None

    def _set_omega_folder(self):
        cur = self._omega_dir()
        val = self._ask_string("Omega 458a preset folder",
                               "Full path to the  …\\VST3 Presets\\Kush Audio\\"
                               "Omega 2 458a  folder:",
                               initial=cur)
        if val is None:
            return
        self.settings["omega_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Omega preset folder.")

    def _generate_omega_selected(self):
        """Only the presets the ticked instruments actually call for."""
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        keys, seen = [], set()
        for iid in checked:
            pre, alts = omega_for(iid)
            for pr in ([pre] if pre else []) + alts:
                if pr["key"] not in seen:
                    seen.add(pr["key"])
                    keys.append(pr["key"])
        # Anything with a bus under it wants the bus setting too — that is the
        # one preset no single channel asks for and the one most worth having.
        if "bus_glue" not in seen and len(checked) > 2:
            keys.append("bus_glue")
        self._generate_omega_presets(keys)

    def _generate_omega_all(self):
        self._generate_omega_presets([p["key"] for p in OMEGA_PRESETS])

    def _generate_omega_presets(self, keys):
        """Write one .vstpreset per named Omega preset.
        Name: 'Omega---<Preset Name>.vstpreset' (no date; a replaced file is kept as
        '.bak', DEL 02s)."""
        folder = self._omega_dir()
        ok = os.path.isdir(folder)
        tpl = self._omega_template() if ok else None
        overwrite = self._ow("Omega 458a")
        help_dir = get_helpfiles_dir(PRESETS_OMEGA)
        self._replaced = []

        made, skip, errors = [], [], []
        if tpl:
            for key in keys:
                pr = OMEGA_BY_KEY.get(key)
                if not pr:
                    continue
                safe = _re.sub(r"[^A-Za-z0-9 ·&_-]", "", pr["name"]).strip()
                fn = f"Omega---{safe}.vstpreset"
                dst = os.path.join(folder, fn)
                if os.path.exists(dst) and not overwrite:
                    skip.append((pr, fn))
                    continue
                try:
                    want = omega_params(pr)
                    vp = make_omega_preset(tpl, want)
                    # Read it straight back and compare against what we asked
                    # for. A preset that does not survive its own round trip
                    # must never reach the plug-in folder.
                    back = read_omega_values(vp)
                    if not back:
                        errors.append((pr["name"], "could not be read back"))
                        continue
                    off = [k for k, v in want.items()
                           if abs(back.get(k, 1e9) - float(v)) > 1e-4]
                    if off:
                        errors.append((pr["name"],
                                       "read back wrong: " + ", ".join(sorted(off))))
                        continue
                    self._put(dst, vp, fn)
                    try:
                        self._put(os.path.join(help_dir, fn), vp, fn + "  [Helpfiles copy]")
                    except Exception:
                        pass                    # the Helpfiles copy is only a backup
                    made.append((pr, fn))
                except Exception as e:
                    errors.append((pr["name"], str(e)))
        self._omega_report(made, skip, errors, folder, ok, tpl is not None,
                           help_dir)

    def _omega_report(self, made, skip, errors, folder, ok, had_tpl, help_dir):
        top = tk.Toplevel(self.root)
        top.title("Omega 458a presets")
        top.configure(bg=C_BG)
        top.geometry("780x620")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🔥  Omega 458a saturation presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999,
                      padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"{len(made)} created · {len(skip)} kept\n\n", "h")
        if not ok:
            txt.insert("end", f"Folder not found:\n  {folder}\n"
                              "  Set it via  File ▸ Set Omega 458a preset folder…\n\n",
                       "warn")
        elif not had_tpl:
            txt.insert("end",
                       "No Omega preset found to use as the container. Save ONE "
                       f"preset out of Omega into:\n  {folder}\n"
                       "  then run this again. (Your 'Kush-omega' is exactly "
                       "what it needs.)\n\n", "warn")
        if made:
            txt.insert("end", "Created:\n", "h")
            for pr, fn in made:
                p = omega_params(pr)
                txt.insert("end", f"  + {pr['name']}\n", "ok")
                txt.insert("end", "      Intensity %g %%  ·  Blend %g %%  ·  "
                                  "HPF %s  ·  LPF %s\n"
                           % (round(p["INTENSITY"] * 100), round(p["BLEND"] * 100),
                              _omega_hz(p["HPFFREQ"]), _omega_hz(p["LPFFREQ"])), "re")
                if p.get("20DBPAD"):
                    txt.insert("end", "      -20 dB Pad ENGAGED\n", "re")
                txt.insert("end", f"      {fn}\n", "re")
            txt.insert("end", "\n")
        if skip:
            txt.insert("end", "Kept (already exist — generate again and answer Overwrite to replace):\n", "h")
            for pr, fn in skip:
                txt.insert("end", f"  · {fn}\n", "re")
            txt.insert("end", "\n")
        if errors:
            txt.insert("end", "Problems:\n", "warn")
            for name, msg in errors:
                txt.insert("end", f"  ! {name}: {msg}\n", "warn")
            txt.insert("end", "\n")
        if made:
            txt.insert("end",
                       "In Cubase these appear in Omega's own preset browser.\n"
                       f"A copy of each is kept in:\n  {help_dir}\n\n", "re")
        txt.insert("end",
                   "About the numbers: unlike every other plug-in in this "
                   "program, Omega publishes its own parameter table — name, "
                   "range, step and default for all of them — so every value "
                   "written here is inside a range the plug-in itself declares, "
                   "and each file is read back and compared field by field "
                   "before it is kept.\n\n", "re")
        txt.insert("end",
                   "Two switches are NOT stored in a preset, because the "
                   "plug-in marks them as global: OVERSAMPLING (the LOW LATENCY "
                   "/ ANALOG HIGHS button) and BYPASS. Set those once and they "
                   "stay where you put them, whichever preset you load.\n", "re")
        self._replaced_section(txt)
        txt.config(state="disabled")
        top.bind("<Escape>", lambda e: top.destroy())
        top.focus_set()

    def _build_omega_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True):
        """A compact '🔥 Omega 458a' footnote: which preset, its numbers, and —
        only when it applies — a warning that the Kirchhoff chart is about to
        boost a band the model has already boosted for free."""
        pre, alts = omega_for(iid)
        if not pre:
            return None
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        self._head_line(frame, "omega", iid, engine_bits("omega", iid),
                        bg=bg, fg=OMEGA_COLOUR, wrap=wrap)
        # The rest of the panel is SETTINGS, so it is never hidden — and it is
        # the longest all-grey block in the program once the preset is saved.
        body = self._head_line(frame, "omega", iid,
                               engine_detail_bits("omega", iid), bg=bg,
                               fg=C_FG_DIM, wrap=wrap, bold=False, detail=True)
        # A caution is a warning, so it is never hidden either.
        if pre.get("caution"):
            self._note_label(frame, "⚠ " + pre["caution"], bg=bg, fg=C_CUT,
                             wrap=wrap, extra=False)
            body = True
        if expanded:
            self._note_label(frame, pre["role"], bg=bg, wrap=wrap, extra=True)
            self._note_label(frame, pre["note"], bg=bg, wrap=wrap, extra=True)
            inst = next((x for x in EQ_DATA if x["id"] == iid), None)
            for line in (omega_overlap(inst) if inst else []):
                self._note_label(frame, "↔ " + line, bg=bg, fg=OMEGA_COLOUR,
                                 wrap=wrap, extra=True)
            if alts:
                self._note_label(
                    frame,
                    "Also worth trying:  " + "  ·  ".join(a["name"] for a in alts),
                    bg=bg, fg=(C_DEFAULT if self._diff_on() else OMEGA_COLOUR),
                    wrap=wrap, extra=False)
        return self._tighten(frame, bool(body))

    # ---- ↔ BANDWIDTH (In The Mix) -------------------------------------------
    # A user preset is a ~640-byte plain-text file (DEL 02q), so unlike every
    # other preset writer in this program there is no template/seed to find
    # first - only a folder to put the files in. Every file is read straight
    # back and compared before it is kept.

    def _bandwidth_dir(self):
        d = (self.settings.get("bandwidth_dir", "") or "").strip()
        return d if d else BANDWIDTH_DEFAULT_DIR

    def _set_bandwidth_folder(self):
        cur = self._bandwidth_dir()
        val = self._ask_string("Bandwidth preset folder",
                               "Full path to Bandwidth's  …\\Bandwidth\\Presets\\User  "
                               "folder:", initial=cur)
        if val is None:
            return
        self.settings["bandwidth_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Bandwidth preset folder.")

    def _generate_bandwidth_selected(self):
        """Only the presets the ticked instruments actually call for."""
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        keys, seen = [], set()
        for iid in checked:
            pre, alts = bandwidth_for(iid)
            for pr in ([pre] if pre else []) + alts:
                if pr["key"] not in seen:
                    seen.add(pr["key"])
                    keys.append(pr["key"])
        # A song with several channels also wants the bus setting.
        if len(checked) > 2 and "mix_bus_subtle" not in seen:
            keys.append("mix_bus_subtle")
        self._generate_bandwidth_presets(keys)

    def _generate_bandwidth_all(self):
        self._generate_bandwidth_presets([p["key"] for p in BANDWIDTH_PRESETS])

    def _generate_bandwidth_presets(self, keys):
        """Write one .itmpreset per named Bandwidth preset into the plug-in's
        user preset folder (created if the plug-in is installed but has no User
        folder yet - which is the state a fresh install is in)."""
        folder = self._bandwidth_dir()
        ok = os.path.isdir(folder)
        if not ok:
            parent = os.path.dirname(folder)
            if os.path.isdir(parent):
                try:
                    os.makedirs(folder, exist_ok=True)
                    ok = True
                except Exception:
                    ok = False
        overwrite = self._ow("Bandwidth")
        help_dir = get_helpfiles_dir(PRESETS_BANDWIDTH)
        self._replaced = []

        made, same, differ, errors = [], [], [], []
        if ok:
            for key in keys:
                pr = BANDWIDTH_BY_KEY.get(key)
                if not pr:
                    continue
                fn = pr["file"] + ".itmpreset"
                dst = os.path.join(folder, fn)
                try:
                    want = bandwidth_params(pr)
                    data = make_bandwidth_preset(want)
                    # Read it straight back and compare against what we asked
                    # for. A preset that does not survive its own round trip
                    # must never reach the plug-in folder.
                    back = read_bandwidth_values(data)
                    if not back:
                        errors.append((pr["name"], "could not be read back"))
                        continue
                    off = [k for k, v in want.items()
                           if abs(back.get(k, 1e9) - float(v)) > 1e-4]
                    if off:
                        errors.append((pr["name"],
                                       "read back wrong: " + ", ".join(sorted(off))))
                        continue
                    # The backup copy is always written: it is OURS (a changed one
                    # replaces the old one, which is kept as '.bak').
                    try:
                        self._put(os.path.join(help_dir, fn), data, fn + "  [Helpfiles copy]")
                    except Exception:
                        pass
                    if os.path.exists(dst) and not overwrite:
                        try:
                            with open(dst, "rb") as f:
                                (same if f.read() == data else differ).append((pr, fn))
                        except Exception:
                            differ.append((pr, fn))
                        continue
                    self._put(dst, data, fn)
                    made.append((pr, fn))
                except PermissionError:
                    errors.append((pr["name"],
                                   "Windows refused to write there (needs admin "
                                   "rights?) - copy it from the backup folder"))
                except Exception as e:
                    errors.append((pr["name"], str(e)))
        self._bandwidth_report(made, same, differ, errors, folder, ok, help_dir)

    def _bandwidth_report(self, made, same, differ, errors, folder, ok, help_dir):
        top = tk.Toplevel(self.root)
        top.title("Bandwidth presets")
        top.configure(bg=C_BG)
        top.geometry("780x620")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="↔  Bandwidth stereo-width presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999,
                      padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"{len(made)} created · {len(same)} already there · "
                          f"{len(differ)} kept\n\n", "h")
        if not ok:
            txt.insert("end", f"Folder not found (and could not be created):\n  {folder}\n"
                              "  Is Bandwidth installed?  If its presets live somewhere "
                              "else, set it via  File ▸ Set Bandwidth preset folder…\n\n",
                       "warn")
        if made:
            txt.insert("end", "Created:\n", "h")
            for pr, fn in made:
                p = pr["p"]
                txt.insert("end", f"  + {pr['name']}\n", "ok")
                txt.insert("end", "      Low %g %%  ·  Mid %g %%  ·  High %g %%  ·  "
                                  "Strength %g  ·  %s / %s\n"
                           % (p["low"], p["mid"], p["high"], p["strength"],
                              _bw_hz(p["x1"]), _bw_hz(p["x2"])), "re")
                txt.insert("end", f"      {fn}\n", "re")
            txt.insert("end", "\n")
        if same:
            txt.insert("end", "Already there, identical:\n", "h")
            for pr, fn in same:
                txt.insert("end", f"  · {fn}\n", "re")
            txt.insert("end", "\n")
        if differ:
            txt.insert("end", "Kept - a file with this name exists and its numbers "
                              "differ (generate again and answer Overwrite to replace):\n", "h")
            for pr, fn in differ:
                txt.insert("end", f"  · {fn}\n", "re")
            txt.insert("end", "\n")
        if errors:
            txt.insert("end", "Problems:\n", "warn")
            for name, msg in errors:
                txt.insert("end", f"  ! {name}: {msg}\n", "warn")
            txt.insert("end", "\n")
        old = [p["old_file"] + ".itmpreset" for p in BANDWIDTH_PRESETS
               if p["old_file"] != p["file"]
               and os.path.exists(os.path.join(folder, p["old_file"] + ".itmpreset"))]
        if old:
            txt.insert("end", "Old file names of the SAME presets are still in this "
                              "folder - you will see each preset twice until you delete "
                              "them (the new names match what this program shows):\n", "h")
            for fn in old:
                txt.insert("end", f"  \u00b7 {fn}\n", "re")
            txt.insert("end", "\n")
        if made or same or differ:
            txt.insert("end",
                       "In Bandwidth, open the preset browser (or the folder button "
                       "beside it) - these appear under User.\n"
                       f"A copy of every preset is also kept in:\n  {help_dir}\n\n", "re")
        txt.insert("end",
                   "About the numbers: the file format is exact (checked against "
                   "your own 13 presets, which this program reproduces byte for "
                   "byte). The width figures in the NEW presets are starting points "
                   "chosen from the manual's own advice - Low band 0 on bass and "
                   "kick, Strength under 6 on low sources, leads barely widened - "
                   "not measurements. Set the Monitor to MID once to confirm the "
                   "centre of the part is still intact.\n", "re")
        self._replaced_section(txt)
        txt.config(state="disabled")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _build_bandwidth_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True):
        """A compact '↔ Bandwidth' footnote: which preset, its numbers, a caution
        where the manual has one, and the alternatives."""
        pre, alts = bandwidth_for(iid)
        if not pre:
            return None
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        self._head_line(frame, "bandwidth", iid, engine_bits("bandwidth", iid),
                        bg=bg, fg=BANDWIDTH_COLOUR, wrap=wrap)
        # The rest of the panel is SETTINGS, so it is never hidden.
        body = self._head_line(frame, "bandwidth", iid,
                               engine_detail_bits("bandwidth", iid), bg=bg,
                               fg=C_FG_DIM, wrap=wrap, bold=False, detail=True)
        if pre.get("caution"):
            self._note_label(frame, "⚠ " + pre["caution"], bg=bg, fg=C_CUT,
                             wrap=wrap, extra=False)
            body = True
        if expanded:
            self._note_label(frame, pre["role"], bg=bg, wrap=wrap, extra=True)
            self._note_label(frame, pre["note"], bg=bg, wrap=wrap, extra=True)
            if alts:
                self._note_label(
                    frame,
                    "Also worth trying:  " + "  ·  ".join(a["name"] for a in alts),
                    bg=bg, fg=(C_DEFAULT if self._diff_on() else BANDWIDTH_COLOUR),
                    wrap=wrap, extra=False)
        return self._tighten(frame, bool(body))

    # ---- ≈ CASCADIA (iZotope) -------------------------------------------------
    # Real .vstpreset files, built from a Cascadia preset the user saved himself
    # (the container: class id, MetaInfo XML, his own analytics block). The
    # parameter names and the whole file layout are exact (DEL 02r); the file is
    # read back and compared before it is kept. These go to the Cubase VST3
    # preset folder - Documents\VST3 Presets\iZotope\Cascadia.

    def _cascadia_dir(self):
        d = (self.settings.get("cascadia_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets", CASCADIA_VENDOR,
                            CASCADIA_NAME)

    def _cascadia_template(self):
        """Bytes of a Cascadia .vstpreset to use as the container. Prefers one the
        user saved himself over any this program wrote (those carry the names in
        CASCADIA_PRESETS), because his own is the one proven to load."""
        folder = self._cascadia_dir()
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")]
        except Exception:
            return None
        ours = {p[k] + ".vstpreset" for p in CASCADIA_PRESETS for k in ("file", "old_file")}
        pref = [f for f in files if os.path.basename(f) not in ours]
        for f in (pref or files):
            try:
                with open(f, "rb") as fh:
                    data = fh.read()
                _h, _i, obj = _cascadia_parse(data)
                _cascadia_element(obj)
                return data
            except Exception:
                continue
        return None

    def _set_cascadia_folder(self):
        cur = self._cascadia_dir()
        val = self._ask_string("Cascadia preset folder",
                               "Full path to the  …\\VST3 Presets\\iZotope\\Cascadia  "
                               "folder:", initial=cur)
        if val is None:
            return
        self.settings["cascadia_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Cascadia preset folder.")

    def _generate_cascadia_selected(self):
        """Only the presets the ticked instruments actually call for."""
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        keys, seen = [], set()
        for iid in checked:
            pre, alts = cascadia_for(iid, set(checked))
            for pr in ([pre] if pre else []) + alts:
                if pr["key"] not in seen:
                    seen.add(pr["key"])
                    keys.append(pr["key"])
        # A song with several channels also wants the all-round send.
        if len(checked) > 2 and "all_subtle_depth" not in seen:
            keys.append("all_subtle_depth")
        self._generate_cascadia_presets(keys)

    def _generate_cascadia_all(self):
        self._generate_cascadia_presets([p["key"] for p in CASCADIA_PRESETS])

    def _cascadia_native_dir(self):
        d = (self.settings.get("cascadia_native_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), CASCADIA_VENDOR, CASCADIA_NAME, "Presets")

    def _set_cascadia_native_folder(self):
        cur = self._cascadia_native_dir()
        val = self._ask_string("Cascadia browser preset folder",
                               "Full path to  …\\Documents\\iZotope\\Cascadia\\Presets  "
                               "(the folder Cascadia's own preset browser reads):",
                               initial=cur)
        if val is None:
            return
        self.settings["cascadia_native_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Cascadia browser preset folder.")

    def _cascadia_write_set(self, keys, folder, ext, build, read, help_dir, overwrite):
        """Write one file per preset into `folder`. Returns (made, same, differ,
        errors). Every file is read back and compared before it is kept; an
        existing file is left alone unless Overwrite is ticked."""
        made, same, differ, errors = [], [], [], []
        for key in keys:
            pr = CASCADIA_BY_KEY.get(key)
            if not pr:
                continue
            fn = pr["file"] + ext
            dst = os.path.join(folder, fn)
            try:
                want = cascadia_params(pr)
                data = build(want)
                if not cascadia_same(read(data), want):
                    errors.append((pr["name"], "read back wrong"))
                    continue
                try:
                    os.makedirs(help_dir, exist_ok=True)
                    # backup copy: always OURS (a changed one keeps the old as '.bak')
                    self._put(os.path.join(help_dir, fn), data, fn + "  [Helpfiles copy]")
                except Exception:
                    pass
                if os.path.exists(dst) and not overwrite:
                    try:
                        with open(dst, "rb") as f:
                            have = read(f.read())
                    except Exception:
                        have = None
                    (same if cascadia_same(have, want) else differ).append((pr, fn))
                    continue
                self._put(dst, data, fn)
                made.append((pr, fn))
            except PermissionError:
                errors.append((pr["name"], "Windows refused to write there"))
            except Exception as e:
                errors.append((pr["name"], str(e)))
        return made, same, differ, errors

    def _generate_cascadia_presets(self, keys):
        """Write every named preset in BOTH formats:
          * .preset    -> Documents\\iZotope\\Cascadia\\Presets   (Cascadia's own
                          browser: User presets). Needs no template.
          * .vstpreset -> Documents\\VST3 Presets\\iZotope\\Cascadia (Cubase's
                          preset list). Needs one Cascadia .vstpreset as container."""
        overwrite = self._ow("Cascadia")
        help_dir = get_helpfiles_dir(PRESETS_CASCADIA)
        self._replaced = []
        results = []

        nfolder = self._cascadia_native_dir()
        nok = os.path.isdir(nfolder)
        if not nok and os.path.isdir(os.path.dirname(nfolder)):
            try:
                os.makedirs(nfolder, exist_ok=True)
                nok = True
            except Exception:
                nok = False
        res = (self._cascadia_write_set(keys, nfolder, ".preset", make_cascadia_native,
                                        read_cascadia_native, help_dir, overwrite)
               if nok else ([], [], [], []))
        results.append(("Cascadia's own browser  (.preset)", nfolder, nok, True, res))

        vfolder = self._cascadia_dir()
        vok = os.path.isdir(vfolder)
        tpl = self._cascadia_template() if vok else None
        res = (self._cascadia_write_set(keys, vfolder, ".vstpreset",
                                        lambda w: make_cascadia_preset(tpl, w),
                                        read_cascadia_values, help_dir, overwrite)
               if tpl else ([], [], [], []))
        results.append(("Cubase VST3 preset list  (.vstpreset)", vfolder, vok,
                        tpl is not None, res))
        self._cascadia_report(results, help_dir)

    def _cascadia_report(self, results, help_dir):
        top = tk.Toplevel(self.root)
        top.title("Cascadia presets")
        top.configure(bg=C_BG)
        top.geometry("780x640")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="≈  Cascadia delay presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999,
                      padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        for label, folder, ok, usable, (made, same, differ, errors) in results:
            txt.insert("end", f"{label}\n", "h")
            txt.insert("end", f"  {folder}\n", "re")
            txt.insert("end", f"  {len(made)} created · {len(same)} already there · "
                              f"{len(differ)} kept\n\n", "h")
            if not ok:
                txt.insert("end", "  Folder not found. Set it via the File menu "
                                  "(Set Cascadia … folder).\n\n", "warn")
            elif not usable:
                txt.insert("end",
                           "  No Cascadia preset found to use as the container. In "
                           "Cubase, save ONE preset out of Cascadia with the VST3 "
                           "preset 'Save' button into this folder, then run this "
                           "again. (Your 'radera-cascadia' is exactly what it "
                           "needs.)\n\n", "warn")
            for pr, fn in made:
                txt.insert("end", f"  + {pr['name']}\n", "ok")
                txt.insert("end", "      " + cascadia_head(pr).split("  —  ", 1)[-1]
                           + "\n", "re")
                for msg in cascadia_caution(pr):
                    txt.insert("end", f"      ⚠ {msg}\n", "warn")
                txt.insert("end", f"      {fn}\n", "re")
            if same:
                txt.insert("end", "  Already there, same settings:\n", "h")
                for pr, fn in same:
                    txt.insert("end", f"    · {fn}\n", "re")
            if differ:
                txt.insert("end", "  ⚠ NOT REPLACED - a file with this name exists and its settings "
                                  "differ, so the plug-in still loads the OLD sound from this folder "
                                  "(only the Helpfiles copy is new). Generate again and answer "
                                  "Overwrite to the question (the old file is kept as .bak):\n",
                           "warn")
                for pr, fn in differ:
                    txt.insert("end", f"    · {fn}\n", "re")
            for name, msg in errors:
                txt.insert("end", f"  ! {name}: {msg}\n", "warn")
            ext = ".preset" if label.endswith("(.preset)") else ".vstpreset"
            old = [p["old_file"] + ext for p in CASCADIA_PRESETS
                   if p["old_file"] != p["file"]
                   and os.path.exists(os.path.join(folder, p["old_file"] + ext))]
            if old:
                txt.insert("end", "  Old (Swedish / underscore) file names of the SAME "
                                  "presets are still here - you will see each one twice "
                                  "until you delete them:\n", "h")
                for fn in old:
                    txt.insert("end", f"    \u00b7 {fn}\n", "re")
            txt.insert("end", "\n")
        txt.insert("end",
                   "Where to look:  in Cascadia's own preset browser the new ones are "
                   "under User presets (close and re-open the preset list, or reload "
                   "the plug-in, if they do not show at once). In Cubase they are in "
                   "the plug-in's VST3 preset list.\n"
                   f"A copy of every preset is also kept in:\n  {help_dir}\n\n"
                   "A .vstpreset copied into the Cascadia-browser folder is NOT shown "
                   "by Cascadia - that browser only reads .preset files.\n\n"
                   "About the numbers: both file layouts and every parameter name are "
                   "exact (checked against your own files). Ranges are not published "
                   "by the plug-in; they stay inside what its 57 factory presets use. "
                   "The .preset files carry the note value as text; presets whose "
                   "original Tempo Sync index is unconfirmed get the note their "
                   "stored time implies at 120 BPM (1/16, 1/16., 1/4 ...).\n", "re")
        self._replaced_section(txt)
        txt.config(state="disabled")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _build_cascadia_footnote(self, parent, iid, bg=C_BG2, wrap=700, expanded=True,
                                 sel=None):
        """A compact '≈ Cascadia' footnote: which preset, its numbers, any caution,
        and the alternatives. Dry channels print nothing - no entry means no line,
        the same rule the depth and Corridor engines use."""
        pre, alts = cascadia_for(iid, sel)
        if not pre:
            return None
        frame = tk.Frame(parent, bg=bg, padx=10, pady=5)
        frame.pack(fill="x", pady=(6, 0))
        self._head_line(frame, "cascadia", iid, engine_bits("cascadia", iid, sel),
                        bg=bg, fg=CASCADIA_COLOUR, wrap=wrap)
        body = self._head_line(frame, "cascadia", iid,
                               engine_detail_bits("cascadia", iid, sel), bg=bg,
                               fg=C_FG_DIM, wrap=wrap, bold=False, detail=True)
        for msg in cascadia_caution(pre):
            self._note_label(frame, "⚠ " + msg, bg=bg, fg=C_CUT, wrap=wrap,
                             extra=False)
            body = True
        if expanded:
            self._note_label(frame, pre["role"], bg=bg, wrap=wrap, extra=True)
            if pre.get("note"):
                self._note_label(frame, pre["note"], bg=bg, wrap=wrap, extra=True)
            self._note_label(frame, "A SEND at the end of the chain - one shared "
                                    "instance, not one per channel.", bg=bg,
                             wrap=wrap, extra=True)
            if alts:
                self._note_label(
                    frame,
                    "Also worth trying:  " + "  ·  ".join(a["name"] for a in alts),
                    bg=bg, fg=(C_DEFAULT if self._diff_on() else CASCADIA_COLOUR),
                    wrap=wrap, extra=False)
        return self._tighten(frame, bool(body))

    # ---- 🎪 VIRTUAL STAGE PRESETS (DEL 02t) ---------------------------------
    def _vstage_dir(self):
        d = (self.settings.get("vstage_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets", VSTAGE_VENDOR, VSTAGE_NAME)

    def _set_vstage_folder(self):
        cur = self._vstage_dir()
        val = self._ask_string("Virtual Stage preset folder",
                               "Full path to the  …\\VST3 Presets\\EVA Instruments\\Virtual Stage  "
                               "folder:", initial=cur)
        if val is None:
            return
        self.settings["vstage_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved Virtual Stage preset folder.")

    def _generate_vstage_selected(self):
        """One preset per row of the stage plan for the ticked channels (DEL 02t)."""
        from tkinter import messagebox
        if not self._checked_ids():
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        rows, info = self._stage()
        presets = vstage_presets_for(rows)
        if not presets:
            messagebox.showinfo(APP_NAME, "None of the ticked channels is meant to go through "
                                "Virtual Stage (the kick and the basses stay off it).",
                                parent=self.root)
            return
        self._generate_vstage_presets(presets, info)

    def _generate_vstage_all(self):
        """The whole library (see DEL 02t): hundreds of files, so ask first."""
        from tkinter import messagebox
        presets = vstage_library(self._stage_perspective())
        if not presets:
            return
        n_rooms = len(VSTAGE_ROOMS)
        if not messagebox.askyesno(
                APP_NAME,
                "Write %d Virtual Stage presets (a set for each of the %d rooms) into\n%s ?\n\n"
                "If files already exist you are asked whether to overwrite them."
                % (len(presets), n_rooms, self._vstage_dir()), parent=self.root):
            return
        self._generate_vstage_presets(
            presets, {"room": "all %d - a set of presets for each" % n_rooms})

    def _generate_vstage_presets(self, presets, info):
        """Write every preset, read each one back, keep an existing file unless Overwrite."""
        overwrite = self._ow("Virtual Stage")
        help_dir = get_helpfiles_dir(PRESETS_VSTAGE)
        folder = self._vstage_dir()
        self._replaced = []
        made, same, differ, errors = [], [], [], []
        ok = os.path.isdir(folder)
        if not ok and os.path.isdir(os.path.dirname(folder)):
            try:
                os.makedirs(folder, exist_ok=True)
                ok = True
            except Exception:
                ok = False
        for pr in (presets if ok else []):
            fn = pr["name"] + ".vstpreset"
            dst = os.path.join(folder, fn)
            try:
                data = make_vstage_preset(pr["dist"], pr["pos"], pr["room"])
                if read_vstage_values(data) != (float(pr["dist"]), float(pr["pos"]),
                                                pr["room"], True):
                    errors.append((pr["name"], "read back wrong"))
                    continue
                try:
                    os.makedirs(help_dir, exist_ok=True)
                    self._put(os.path.join(help_dir, fn), data, fn + "  [Helpfiles copy]")
                except Exception:
                    pass
                if os.path.exists(dst) and not overwrite:
                    try:
                        with open(dst, "rb") as f:
                            have = f.read()
                    except Exception:
                        have = None
                    (same if have == data else differ).append((pr, fn))
                    continue
                state = self._put(dst, data, fn)
                (same if state == "same" else made).append((pr, fn))
            except PermissionError:
                errors.append((pr["name"], "Windows refused to write there"))
            except Exception as e:
                errors.append((pr["name"], str(e)))
        self._vstage_report(made, same, differ, errors, folder, ok, help_dir, info)

    def _vstage_report(self, made, same, differ, errors, folder, ok, help_dir, info):
        top = tk.Toplevel(self.root)
        top.title("Virtual Stage presets")
        top.configure(bg=C_BG)
        top.geometry("780x600")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🎪  Virtual Stage presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999,
                      padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"{folder}\n", "re")
        txt.insert("end", f"  {len(made)} created · {len(same)} already there · "
                          f"{len(differ)} kept\n", "h")
        txt.insert("end", "  ONE room for the song: %s\n\n" % (info or {}).get("room", "?"), "re")
        if not ok:
            txt.insert("end", "  Folder not found. Set it via File > Set Virtual Stage "
                              "preset folder.\n\n", "warn")
        group = None
        for pr, fn in made:
            if pr.get("group") and pr["group"] != group:
                group = pr["group"]
                txt.insert("end", f"\n  {group}\n", "h")
            txt.insert("end", f"  + {fn}\n", "ok")
            txt.insert("end", "      %s · Room %s · Distance %d · %s · Lock Position ON\n"
                       % (_stage_name(pr["iid"]) + (" (copy %d)" % pr["copy"] if pr["copy"] else ""),
                          pr["room"], pr["dist"], vstage_pos_tag(pr["pos"])), "re")
        if same:
            txt.insert("end", "  Already there, identical:\n", "h")
            for pr, fn in same:
                txt.insert("end", f"    · {fn}\n", "re")
        if differ:
            txt.insert("end", "  Kept - a file with this name exists and its contents differ "
                              "(generate again and answer Overwrite; the old one is kept as .bak):\n", "h")
            for pr, fn in differ:
                txt.insert("end", f"    · {fn}\n", "re")
        for name, msg in errors:
            txt.insert("end", f"  ! {name}: {msg}\n", "warn")
        txt.insert("end",
                   "\nThe name IS the content: room digit (1 Small, 2 Medium, 3 Large), "
                   "instrument, Distance, Position. A different line-up gives different "
                   "names, so nothing from another song is overwritten - delete the ones "
                   "you no longer use.\n"
                   "In Cubase they show in Virtual Stage's VST3 preset list (reopen the "
                   "list if they do not appear at once). Lock Position is ON in every "
                   "preset. The kick and the basses get none - the plug-in stays off them.\n"
                   f"A copy of every preset is also kept in:\n  {help_dir}\n", "re")
        self._replaced_section(txt)
        txt.config(state="disabled")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    # ---- 🎻 SWAM ROOM PRESETS (v3.27) ---------------------------------------------
    def _swam_dir(self):
        d = (self.settings.get("swam_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets", "Audio Modeling")

    def _set_swam_folder(self):
        val = self._ask_string("SWAM preset folder",
                               "Full path to the  …\\VST3 Presets\\Audio Modeling  folder "
                               "(it holds one sub-folder per SWAM instrument):",
                               initial=self._swam_dir())
        if val is None:
            return
        self.settings["swam_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved SWAM preset folder.")

    def _swam_seed_dialog(self):
        """Per SWAM instrument: which of YOUR presets in its folder the generated ones are
        built from (the sound: bowing, vibrato, EQ, reverb). Automatic = Claude, Default, else
        the shortest name."""
        folders = swam_find_folders(self._swam_dir())
        top = tk.Toplevel(self.root)
        top.title("SWAM: the sound to build from")
        top.configure(bg=C_BG)
        top.transient(self.root)
        tk.Label(top, text="Pick the preset each instrument's generated presets are built from.\n"
                           "Only the room position is changed; the sound stays as in this preset.",
                 bg=C_BG, fg=C_FG, font=FONT_NORMAL, justify="left").pack(anchor="w", padx=14, pady=(12, 6))
        chosen = dict(self.settings.get("swam_seeds") or {})
        vars_ = {}
        AUTO = "(automatic)"
        found = False
        for key, path in sorted(folders.items()):
            names = swam_seed_files(path)
            if not names:
                continue
            found = True
            base = os.path.basename(path)
            row = tk.Frame(top, bg=C_BG)
            row.pack(fill="x", padx=14, pady=2)
            tk.Label(row, text=base, bg=C_BG, fg=C_FG, font=FONT_NORMAL, width=24, anchor="w").pack(side="left")
            v = tk.StringVar(value=chosen.get(base) if chosen.get(base) in names else AUTO)
            vars_[base] = v
            om = tk.OptionMenu(row, v, AUTO, *names)
            om.config(bg=C_BG2, fg=C_FG, activebackground=C_BG3, activeforeground=C_FG,
                      highlightthickness=0, relief="flat", font=FONT_SMALL, anchor="w", width=48)
            om["menu"].config(bg=C_BG2, fg=C_FG, font=FONT_SMALL)
            om.pack(side="left", padx=4)
        if not found:
            tk.Label(top, text="No SWAM presets of yours were found under\n%s\n(File > Set SWAM preset folder)."
                     % self._swam_dir(), bg=C_BG, fg=C_CUT, font=FONT_NORMAL, justify="left").pack(padx=14, pady=8)

        def _ok():
            new = {b: v.get() for b, v in vars_.items() if v.get() != AUTO}
            self.settings["swam_seeds"] = new
            save_settings(self.settings)
            self._toast("Saved the SWAM sound choices.")
            top.destroy()
        bar = tk.Frame(top, bg=C_BG)
        bar.pack(fill="x", padx=14, pady=10)
        tk.Button(bar, text="OK", bg=C_BTN, fg=C_BTN_FG, relief="flat", padx=14, pady=3,
                  font=FONT_SMALL, command=_ok).pack(side="right")
        tk.Button(bar, text="Cancel (Esc)", bg=C_BTN, fg=C_BTN_FG, relief="flat", padx=10, pady=3,
                  font=FONT_SMALL, command=top.destroy).pack(side="right", padx=6)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _generate_swam_button(self):
        """The SWAM button in Song Variants: take in whatever is waiting first (the files must
        say what the panel says), then generate."""
        if self._pending_bits():
            self._commit_left(persist=False)
        self._generate_swam_presets()

    def _generate_swam_presets(self):
        """One preset per SWAM instrument of THIS song, into that instrument's own folder."""
        from tkinter import messagebox
        if not self._checked_ids():
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.", parent=self.root)
            return
        rows, info = self._stage()
        jobs = swam_jobs(rows, info)
        if not jobs:
            messagebox.showinfo(
                APP_NAME, "No instrument is marked SWAM. Tick the SWAM box (right-hand end of the row in "
                "Song Variants) on the strings, brass and winds you play as SWAM.", parent=self.root)
            return
        root = self._swam_dir()
        folders = swam_find_folders(root)
        song = self.current_variant or "Song"
        help_dir = get_helpfiles_dir(PRESETS_SWAM)
        self._replaced = []
        made, same, errors, seeds = [], [], [], {}
        native_dirs, native_n, native_miss = None, 0, []
        for j in jobs:
            iid = j["iid"]
            sect = bool(j.get("section"))
            folder = swam_folder_for(iid, folders, sect)
            if not folder:
                names = swam_folder_names(iid, sect)
                if names:
                    want = "SWAM " + names[0].title()
                    errors.append((_stage_name(iid) + (" (Section)" if sect else ""),
                                   "no folder '%s ...' under %s. Open the %s plug-in, set it up and SAVE "
                                   "ONE PRESET there (the plug-in then creates the folder). It has to be "
                                   "saved inside that very plug-in: a preset from the solo plug-in is another "
                                   "format and does not load in the Section plug-in. Folders found: %s"
                                   % (want, root, want,
                                      ", ".join(sorted(os.path.basename(p) for p in folders.values())) or "none")))
                else:
                    errors.append((_stage_name(iid), "a generic card with no single SWAM instrument "
                                   "behind it - tick the real instrument instead (e.g. Trumpet, "
                                   "Saxophone Alto) and mark that one SWAM"))
                continue
            if folder not in seeds:
                seeds[folder] = swam_pick_seed(
                    folder, (self.settings.get("swam_seeds") or {}).get(os.path.basename(folder), ""))
            seed = seeds[folder]
            if not seed:
                errors.append((_stage_name(iid), "no preset of yours in %s - open the instrument in "
                               "SWAM, set it up, and save ONE preset there; it is the sound this "
                               "program builds from" % folder))
                continue
            fn = swam_preset_filename(song, j["label"], j["copy"])
            try:
                data = make_swam_preset(seed[1], j["angle"], j["metres"],
                                        self.settings.get("swam_expression", 1.0),
                                        self.settings.get("swam_vibrato"))
                back = swam_preset_values(data)
                if back is None or round(back[0]) != round(j["angle"]) or abs(back[1] - j["metres"]) > 0.06:
                    errors.append((fn, "read back wrong"))
                    continue
                dst = os.path.join(folder, fn)
                state = self._put(dst, data, fn)
                try:
                    os.makedirs(help_dir, exist_ok=True)
                    self._put(os.path.join(help_dir, fn), data, fn + "  [Helpfiles copy]")
                except Exception:
                    pass
                # v3.33: the same preset for SWAM's OWN browser (no Cubase rescan needed there)
                if self.settings.get("swam_native", True):
                    try:
                        if native_dirs is None:
                            native_dirs = swam_native_dirs()
                        nd = swam_native_dir_for(iid, sect, native_dirs)
                        if nd:
                            pname = os.path.splitext(fn)[0]
                            self._put(os.path.join(nd, pname + ".swam"), swam_native_text(data, pname),
                                      pname + ".swam  [SWAM's own list]")
                            native_n += 1
                        else:
                            native_miss.append(_stage_name(iid) + (" (Section)" if sect else ""))
                    except Exception as e:
                        native_miss.append("%s (%s)" % (_stage_name(iid), e))
                (same if state == "same" else made).append((j, fn, folder, seed[0], state))
            except PermissionError:
                errors.append((fn, "Windows refused to write there"))
            except Exception as e:
                errors.append((fn, str(e)))
        self._swam_report(made, same, errors, info, root, help_dir, song, seeds,
                          (native_n, native_miss))

    def _swam_report(self, made, same, errors, info, root, help_dir, song, seeds, native=(0, [])):
        top = tk.Toplevel(self.root)
        top.title("SWAM room presets")
        top.configure(bg=C_BG)
        top.geometry("820x640")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="\U0001f3bb  SWAM room presets \u2014 " + song, bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                  activeforeground=C_FG, font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0, wrap="word",
                      insertofftime=0, insertontime=9999999, padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h", foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)
        txt.insert("end", "%d written / changed  \u00b7  %d already up to date  \u00b7  %d problem(s)\n\n"
                   % (len(made), len(same), len(errors)), "h")
        room = ((info or {}).get("swam") or {}).get("room")
        if room:
            txt.insert("end", "Room for the whole song (set it ONCE in any SWAM window; Room Type never changes): "
                       "Room Sizes %s  \u00b7  Absorption %s  \u00b7  Mic %s\n  %s\n\n"
                       % (room["size"], room["material"], room["mic"], room["why"]), "re")
        for j, fn, folder, seed_path, state in made + same:
            txt.insert("end", ("  + " if state != "same" else "  = ") + fn + "\n",
                       "ok" if state != "same" else "re")
            txt.insert("end", "      %s  \u00b7  Angle %d\u00b0  \u00b7  Distance %.1f m\n"
                       % (_stage_name(j["iid"]) + (" (copy %d)" % j["copy"] if j["copy"] else ""),
                          j["angle"], j["metres"]), "re")
            _gen = os.path.splitext(seed_path)[0].endswith(SWAM_SUFFIX)
            txt.insert("end", "      in %s\n      sound from: %s%s\n"
                       % (folder, os.path.basename(seed_path),
                          "   (none of yours left in the folder - built from an earlier generated "
                          "file: same sound)" if _gen else ""), "re")
        for folder, seed in seeds.items():
            if seed:
                rm = swam_seed_room(seed[1])
                if rm:
                    txt.insert("end", "\nRoom stored in %s: %s, size no. %s%s, material no. %s\n"
                               % (os.path.basename(seed[0]), rm[0], rm[1],
                                  " (%s)" % SWAM_SIZE_NAMES[rm[1]] if rm[1] in SWAM_SIZE_NAMES else "", rm[2]), "re")
                    break
        for name, msg in errors:
            txt.insert("end", "  ! %s: %s\n" % (name, msg), "warn")
        if made or same:
            run = cubase_running()
            txt.insert("end", "\nWHY A NEW PRESET MAY NOT SHOW UP IN CUBASE\n", "h")
            txt.insert("end",
                       "Cubase builds its preset list when it STARTS (MediaBay) and does not look at the folder "
                       "again by itself - files written afterwards are on disk but missing from the list.%s\n"
                       "  1. Quickest: close and start Cubase again, or\n"
                       "  2. In Cubase open MediaBay (F5), right-click  VST3 Presets  (under User Content) and "
                       "choose  Rescan Disk  (do it again if the instrument's sub-folder still does not appear).\n"
                       % ("  (Cubase IS running right now.)" if run else
                          ("  (Cubase is not running - the list will be right when it starts.)" if run is False else "")),
                       "warn" if run else "re")
            if native[0]:
                txt.insert("end",
                           "  3. Or skip Cubase's list: %d preset(s) were ALSO saved as '.swam' in SWAM's own User "
                           "folders. Open the preset browser INSIDE the SWAM plug-in (User tab) - it reads its "
                           "folder itself. (Not verified yet - tell me if it works.)\n" % native[0], "re")
            if native[1]:
                txt.insert("end", "  (No SWAM-own folder found for: %s)\n" % ", ".join(native[1]), "re")
        txt.insert("end",
                   "\nHow to use: in each SWAM instrument open the preset list and load '%s---<instrument>%s'. "
                   "The preset places THAT instrument in the shared Ambiente room (tested with SWAM Viola 3); "
                   "the sources are spaced so none stands on another.\n"
                   "Added or removed an instrument, or changed the line-up? Run Generate again: the same "
                   "file names are rewritten and the old files are kept beside them as .bak.\n"
                   "Only the room position is changed - the sound is whatever the preset you saved in that "
                   "instrument holds.\nA copy of every file is also kept in:\n  %s\n"
                   % (swam_safe_song(song), SWAM_SUFFIX, help_dir), "re")
        self._replaced_section(txt)
        txt.config(state="disabled")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _set_submass_folder(self):
        cur = self._submass_dir()
        val = self._ask_string("SubMass preset folder",
                               "Full path to the DSPTone  …\\DSPTone\\SubMass  folder:",
                               initial=cur)
        if val is None:
            return
        self.settings["submass_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved SubMass preset folder.")

    def _generate_submass_selected(self):
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        self._generate_submass_presets(checked)

    def _generate_submass_all(self):
        self._generate_submass_presets([x["id"] for x in EQ_DATA])

    def _generate_submass_presets(self, ids):
        """One SubMass .vstpreset per SubMass-eligible instrument, with the
        Amp/Freq/Center from the SUBMASS chart patched into a seed the user
        already exported (e.g. 'Feel a 100'). Only instruments with a SUBMASS
        entry (kick, basses) generate anything — everything else is skipped;
        this is on purpose, not every sound wants a tracked sub layer.
        Name: '<Label>---SubMass_Amp<a>_Freq<f>Hz_Center<c>.vstpreset' (no date: the
        numbers in the name ARE the version; a replaced file is kept as '.bak', DEL 02s)."""
        by_id = {x["id"]: x for x in EQ_DATA}
        elig = [i for i in ids if i in by_id and i in SUBMASS]
        skipped_ineligible = [i for i in ids if i in by_id and i not in SUBMASS]
        folder = self._submass_dir()
        ok = os.path.isdir(folder)
        tpl = self._submass_template() if ok else None
        overwrite = self._ow("SubMass")
        help_dir = get_helpfiles_dir(PRESETS_SUBMASS)
        self._replaced = []

        made, skip, errors = [], [], []
        if tpl:
            for iid in elig:
                amp, freq_hz, center_pct, _note = SUBMASS[iid]
                fn = (f"{self.KEQ_LABEL.get(iid, iid)}---SubMass_"
                      f"Amp{amp}_Freq{freq_hz}Hz_Center{center_pct}.vstpreset")
                dst = os.path.join(folder, fn)
                if os.path.exists(dst) and not overwrite:
                    skip.append((iid, fn))
                    continue
                try:
                    vp = make_submass_preset(tpl, amp=amp, freq_hz=freq_hz,
                                             center_pct=center_pct)
                    if not vp:
                        errors.append((iid, "build failed"))
                        continue
                    self._put(dst, vp, fn)
                    try:
                        self._put(os.path.join(help_dir, fn), vp, fn + "  [Helpfiles copy]")
                    except Exception:
                        pass                    # the Helpfiles copy is only a backup
                    made.append((iid, fn, amp, freq_hz, center_pct))
                except Exception as e:
                    errors.append((iid, str(e)))
        self._submass_report(made, skip, errors, skipped_ineligible, folder,
                             ok, tpl is not None, help_dir)

    def _submass_report(self, made, skip, errors, ineligible, folder, ok,
                        had_tpl, help_dir):
        id2name = {x["id"]: x["name"] for x in EQ_DATA}
        top = tk.Toplevel(self.root)
        top.title("SubMass presets")
        top.configure(bg=C_BG)
        top.geometry("660x540")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🌑  SubMass (tracked sub) presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999, padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"{len(made)} created · {len(skip)} kept\n\n", "h")
        if not ok:
            txt.insert("end", f"Folder not found:\n  {folder}\n"
                              "  Set it via  File ▸ Set SubMass preset folder…\n\n", "warn")
        elif not had_tpl:
            txt.insert("end", "No seed .vstpreset found. Export ONE SubMass preset "
                              f"(e.g. 'Feel a 100') from Cubase into:\n  {folder}\n"
                              "  then run this again.\n\n", "warn")
        if made:
            txt.insert("end", "Created (Amp/12 · Freq Hz · Center %):\n", "h")
            for iid, fn, amp, freq_hz, center_pct in made:
                txt.insert("end", f"  + {id2name.get(iid, iid):22s} "
                                  f"Amp {amp}/12 · {freq_hz} Hz · {center_pct}% → {fn}\n", "ok")
            txt.insert("end", "\n")
        if skip:
            txt.insert("end", "Kept (already exist — generate again and answer Overwrite to replace):\n", "h")
            for iid, fn in skip:
                txt.insert("end", f"  · {id2name.get(iid, iid):22s} {fn}\n", "re")
            txt.insert("end", "\n")
        if ineligible:
            txt.insert("end", "Skipped (not a SubMass candidate — no tracked-sub entry):\n", "re")
            txt.insert("end", "  " + ", ".join(id2name.get(i, i) for i in ineligible) + "\n\n", "re")
        if errors:
            txt.insert("end", "Problems:\n", "warn")
            for iid, msg in errors:
                txt.insert("end", f"  ! {id2name.get(iid, iid)}: {msg}\n", "warn")
            txt.insert("end", "\n")
        if made:
            txt.insert("end", "Level and the Mono-below-Hz threshold are left at the seed's own "
                              "values (no verified mapping yet) — dial those two by ear in the "
                              "plugin itself. Chain position: insert LAST among the static EQ/"
                              "dynamics processors — after Comp and Duck, before Width/Chorus and "
                              "well before any Delay/Reverb send.\n"
                              f"Backups in:\n  {help_dir}\n", "re")
        self._replaced_section(txt)
        txt.configure(state="disabled")
        top.bind("<Escape>", lambda e: top.destroy())
        top.grab_set()
        top.focus_force()

    # ---- KNOCK (Plugins That Knock: KNOCK 1 and KNOCK 2, DEL 02e3) ----------

    def _knock_version(self):
        return knock_version_of({"knock_version": self.knock_version_var.get()})

    def _knock_dir(self, version=None):
        """The folder for a KNOCK version (setting, or the Documents default)."""
        version = version or self._knock_version()
        d = (self.settings.get("knock%s_dir" % version, "") or "").strip()
        if d:
            return d
        if version == "2":
            return os.path.join(_documents_dir(), "VST3 Presets", "Knock Audio", "KNOCK 2")
        return os.path.join(_documents_dir(), "VST3 Presets", "Plugins That Knock", "KNOCK")

    def _knock2_user_dir(self):
        """Folder of KNOCK 2's own '.k2p' browser (User tab)."""
        d = (self.settings.get("knock2_user_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(os.environ.get("ProgramData", r"C:\ProgramData"), "Knock Audio", "KNOCK 2", "Presets", "User")

    def _on_knock_version(self):
        self.settings["knock_version"] = self._knock_version()
        save_settings(self.settings)
        self._toast("Knock presets: KNOCK %s" % self._knock_version())
        try:
            self._on_filter_change()   # left-hand cards
            self._refresh_summary()    # right-hand panel (the footnote follows the version)
        except Exception:
            pass

    def _set_knock_folders(self):
        for ver, title in (("1", "KNOCK 1 (Plugins That Knock)"), ("2", "KNOCK 2 (Knock Audio)")):
            val = self._ask_string("%s preset folder" % title,
                                   "Full path to the %s .vstpreset folder\n(empty = the Documents default):" % title,
                                   initial=self._knock_dir(ver))
            if val is None:
                return
            self.settings["knock%s_dir" % ver] = val.strip()
        val = self._ask_string("KNOCK 2 own browser (.k2p) folder",
                               "Full path to the folder KNOCK 2's own preset browser reads (User tab)\n"
                               "(empty = C:\\ProgramData\\Knock Audio\\KNOCK 2\\Presets\\User):",
                               initial=self._knock2_user_dir())
        if val is None:
            return
        self.settings["knock2_user_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved the KNOCK preset folders.")

    def _generate_knock_selected(self):
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.", parent=self.root)
            return
        self._generate_knock_presets(checked, buses=False)

    def _generate_knock_all(self):
        self._generate_knock_presets([x["id"] for x in EQ_DATA], buses=True)

    def _generate_knock_presets(self, ids, buses=False):
        """One KNOCK preset (plus its alternatives) per instrument that has an entry in KNOCK_FOR, written in
        the chosen version. 'All' also writes Drum_Bus and Mix_Bus. Name: '<Label>---Knock<v>_<Name>.vstpreset'
        (no date; a replaced file is kept as '.bak', DEL 02s)."""
        ver = self._knock_version()
        by_id = {x["id"]: x for x in EQ_DATA}
        jobs, no_entry = [], []
        for iid in ids:
            if iid not in by_id:
                continue
            ps = knock_for(iid)
            if not ps:
                no_entry.append(iid)
            for p in ps:
                jobs.append((iid, self.KEQ_LABEL.get(iid, iid), p))
        if buses:
            for label, key in KNOCK_BUS:
                jobs.append((None, label, KNOCK_BY_KEY[key]))
        folder = self._knock_dir(ver)
        ok = os.path.isdir(folder) or os.path.isdir(os.path.dirname(folder.rstrip("\\/")))
        overwrite = self._ow("Knock")
        help_dir = get_helpfiles_dir(os.path.join(PRESETS_KNOCK, "Knock" + ver))
        self._replaced = []
        made, skip, errors = [], [], []
        self._k2p_made = []
        k2p_dir = self._knock2_user_dir() if ver == "2" else ""
        if ok:
            os.makedirs(folder, exist_ok=True)
            for iid, label, p in jobs:
                fn = knock_file_name(label, p, ver)
                dst = os.path.join(folder, fn)
                if ver == "2" and k2p_dir:
                    # KNOCK 2's own browser (User tab) only lists native .k2p files
                    kn = fn[:-len(".vstpreset")] + ".k2p"
                    try:
                        os.makedirs(k2p_dir, exist_ok=True)
                        if not os.path.exists(os.path.join(k2p_dir, kn)) or overwrite:
                            self._put(os.path.join(k2p_dir, kn), knock2_k2p(dict(p["k2"])), kn)
                            self._k2p_made.append(kn)
                    except Exception as e:
                        errors.append((label, ".k2p: %s" % e))
                if os.path.exists(dst) and not overwrite:
                    skip.append((label, fn))
                    continue
                try:
                    data = knock_preset_bytes(p, ver)
                    self._put(dst, data, fn)
                    try:
                        self._put(os.path.join(help_dir, fn), data, fn + "  [Helpfiles copy]")
                    except Exception:
                        pass                    # the Helpfiles copy is only a backup
                    made.append((label, fn, p))
                except Exception as e:
                    errors.append((label, str(e)))
        self._knock_report(ver, made, skip, errors, no_entry, folder, ok, help_dir)

    def _knock_report(self, ver, made, skip, errors, no_entry, folder, ok, help_dir):
        id2name = {x["id"]: x["name"] for x in EQ_DATA}
        top = tk.Toplevel(self.root)
        top.title("KNOCK %s presets" % ver)
        top.configure(bg=C_BG)
        top.geometry("720x560")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="\U0001f94a  KNOCK %s presets" % ver, bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG, activebackground=C_BG,
                  activeforeground=C_FG, font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999, padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h", foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)
        txt.insert("end", "%d created \u00b7 %d kept\n\n" % (len(made), len(skip)), "h")
        if not ok:
            txt.insert("end", "Folder not found:\n  %s\n  Set it via  File \u25b8 Set KNOCK 1 / KNOCK 2 preset folders\u2026\n\n"
                       % folder, "warn")
        if made:
            txt.insert("end", "Created in  %s :\n" % folder, "h")
            for label, fn, p in made:
                txt.insert("end", "  + %s\n" % fn, "ok")
                txt.insert("end", "      %s\n" % "  \u00b7  ".join(knock_bits(p, ver)), "re")
            txt.insert("end", "\n")
        if skip:
            txt.insert("end", "Kept (already exist \u2014 generate again and answer Overwrite to replace):\n", "h")
            for label, fn in skip:
                txt.insert("end", "  \u00b7 %s\n" % fn, "re")
            txt.insert("end", "\n")
        if no_entry:
            txt.insert("end", "No KNOCK entry (not a punch / drum / bass / vocal sound): ", "re")
            txt.insert("end", ", ".join(id2name.get(i, i) for i in no_entry) + "\n\n", "re")
        if errors:
            txt.insert("end", "Problems:\n", "warn")
            for label, msg in errors:
                txt.insert("end", "  ! %s: %s\n" % (label, msg), "warn")
            txt.insert("end", "\n")
        if made or getattr(self, "_k2p_made", []):
            if ver == "2":
                k2n = getattr(self, "_k2p_made", [])
                txt.insert("end", "Where to load them from:\n"
                                  "  • Cubase's preset list (the .vstpreset files above) - restart Cubase / rescan the plug-in "
                                  "preset list if they are not shown yet.\n"
                                  "  • KNOCK 2's own browser, User tab: %d native .k2p files in\n      %s\n"
                                  "    (reopen the plug-in window to refresh)\n\n" % (len(k2n), self._knock2_user_dir()), "h")
                txt.insert("end", "KNOCK 2 reports 64 ms of latency in its default 'Mixed' phase mode (0 ms in 'Minimum', 232 ms in "
                                  "'Linear'); Cubase compensates, but remember it on a live-monitored track. These presets are "
                                  "sound-alikes of the KNOCK 1 ones (matched on test signals), not copies - the modes (Tube, Tape, "
                                  "Velvet ...) are there to try on top.\n", "re")
            else:
                txt.insert("end", "KNOCK 1 clamps TILT beyond \u00b13 dB, SATURATION beyond 30 dB and every saturation colour above 2 "
                                  "is 'Hard'; Sub is off at -30 dB. The numbers above are what the plug-in really uses.\n", "re")
            txt.insert("end", "Backups in:\n  %s\n" % help_dir, "re")
        self._replaced_section(txt)
        txt.configure(state="disabled")
        top.bind("<Escape>", lambda e: top.destroy())
        top.grab_set()
        top.focus_force()

    # ---- BLUE CAT'S PATCHWORK (full channel-strip chain) -------------------

    def _patchwork_dir(self):
        """Resolve the PatchWork preset folder (setting, or Documents default)."""
        d = (self.settings.get("patchwork_dir", "") or "").strip()
        if d:
            return d
        return os.path.join(_documents_dir(), "VST3 Presets", "Blue Cat Audio",
                            "Blue Cat's PatchWork")

    def _patchwork_seed(self, folder):
        """Pick the seed PatchWork preset = the one hosting the MOST plug-ins we can
        configure (so we get the fullest chain), preferring a hand-made seed over our
        own generated '<Label>---Chain' / '0---…' files. Returns (path, bytes,
        slots:set) or (None, None, set())."""
        try:
            files = [os.path.join(folder, f) for f in os.listdir(folder)
                     if f.lower().endswith(".vstpreset")]
        except Exception:
            return None, None, set()
        # Prefer files that are NOT our own output (those are seeds we made).
        hand = [f for f in files if not is_generated_name(f)]
        best = None
        for f in (hand or files):
            try:
                with open(f, "rb") as fh:
                    b = fh.read()
            except Exception:
                continue
            slots = pw_recognised_slots(b)
            if not slots:
                continue
            score = (len(slots), os.path.getmtime(f))
            if best is None or score > best[0]:
                best = (score, f, b, slots)
        if not best:
            return None, None, set()
        return best[1], best[2], best[3]

    def _set_patchwork_folder(self):
        cur = self._patchwork_dir()
        val = self._ask_string(
            "PatchWork preset folder",
            "Full path to the  …\\Blue Cat Audio\\Blue Cat's PatchWork  folder:",
            initial=cur)
        if val is None:
            return
        self.settings["patchwork_dir"] = val.strip()
        save_settings(self.settings)
        self._toast("Saved PatchWork preset folder.")

    def _pw_keq_json_for(self, iid, ids, constellation, nohp):
        """Build the instrument's Kirchhoff .keq JSON bytes (same band logic as the
        standalone Kirchhoff generator), ready to drop into a PatchWork chunk."""
        by_id = {x["id"]: x for x in EQ_DATA}
        inst = by_id[iid]
        if constellation:
            recs = self._mix_recommendations(set(ids))
            eff, _ = self._apply_edits(inst, recs[iid]["edits"])
        else:
            eff = inst["bands"]
        params = []
        for b in eff:
            if nohp and b.get("filter") == "High-pass":
                continue                       # Lowtility (in the chain) does the HP
            k = kirchhoff_band(b)
            params.append({
                "ktype": k["ktype"], "freq_hz": k["freq_hz"],
                "gain_db": k["gain_db"], "q_val": k["q_val"],
                "slope_norm": k["slope_norm"], "sp_norm": self._keq_sp_for(iid, k),
            })
        d = build_keq_dict(params)
        return json.dumps(d, indent=4, ensure_ascii=False).encode("utf-8")

    def _generate_patchwork_selected(self):
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        self._generate_patchwork_presets(
            checked, constellation=True,
            source_label=(self.current_variant or "selected"))

    def _generate_patchwork_all(self):
        self._generate_patchwork_presets([x["id"] for x in EQ_DATA],
                                         constellation=False, source_label="ALL")

    def _generate_patchwork_presets(self, ids, constellation, source_label=""):
        """One Blue Cat's PatchWork .vstpreset per instrument carrying the WHOLE
        channel strip at once: Lowtility (low-cut) + Kirchhoff (.keq) + smart:reverb
        (Distance/Size/Width, or bypassed when DRY) + smart:EQ (copied from the seed —
        re-Learn per track). The chain itself is whatever your seed PatchWork preset
        contains. Name: '<Label>---Chain.vstpreset' (no date; a replaced file is kept as
        '.bak', DEL 02s)."""
        by_id = {x["id"]: x for x in EQ_DATA}
        ids = [i for i in ids if i in by_id]
        if not ids:
            self._toast("No instruments selected.")
            return

        folder = self._patchwork_dir()
        ok = os.path.isdir(folder)
        seed_path, seed_bytes, slots = self._patchwork_seed(folder) if ok else (None, None, set())
        overwrite = self._ow("PatchWork")
        nohp = bool(self.keq_nohp_var.get())
        help_dir = get_helpfiles_dir(PRESETS_PATCHWORK)
        self._replaced = []

        made, skip, errors = [], [], []
        if seed_bytes:
            for iid in ids:
                fn = f"{self.KEQ_LABEL.get(iid, iid)}---Chain.vstpreset"
                dst = os.path.join(folder, fn)
                if os.path.exists(dst) and not overwrite:
                    skip.append((iid, fn))
                    continue
                try:
                    lc = lowcut_for(iid)                    # (hz, slope) or None
                    kj = self._pw_keq_json_for(iid, ids, constellation, nohp)
                    dp = depth_for(iid)                     # (tier, spec, note) or None
                    srev = bypass_rev = None
                    if dp:
                        tier, spec, _ = dp
                        if tier == "dry" or spec.get("distance") is None:
                            bypass_rev = True
                        else:
                            srev = (spec["distance"], spec["size"], spec["width"])
                    else:
                        bypass_rev = True
                    vp, touched = assemble_patchwork(
                        seed_bytes,
                        lowtility=lc,
                        kirchhoff_json=kj,
                        smartreverb=srev,
                        bypass_reverb=bool(bypass_rev),
                        progname=self.KEQ_LABEL.get(iid, iid))
                    self._put(dst, vp, fn)
                    try:                                    # backup (survives wipes)
                        self._put(os.path.join(help_dir, fn), vp, fn + "  [Helpfiles copy]")
                    except Exception:
                        pass
                    made.append((iid, fn, touched))
                except Exception as e:
                    errors.append((iid, str(e)))

        self._patchwork_report(made, skip, errors, folder, ok, seed_path, slots,
                               nohp, help_dir)

    def _patchwork_report(self, made, skip, errors, folder, ok, seed_path, slots,
                          nohp, help_dir):
        id2name = {x["id"]: x["name"] for x in EQ_DATA}
        top = tk.Toplevel(self.root)
        top.title("PatchWork presets")
        top.configure(bg=C_BG)
        top.geometry("700x600")
        top.transient(self.root)
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🧩  PatchWork full-chain presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999, padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"{len(made)} created · {len(skip)} kept\n\n", "h")
        if not ok:
            txt.insert("end", f"Folder not found:\n  {folder}\n"
                              "  Set it via  File ▸ Set PatchWork preset folder…\n\n", "warn")
        elif not seed_path:
            txt.insert("end",
                       "No SEED PatchWork preset found. In Cubase, load Blue Cat's "
                       "PatchWork, build the chain you want (e.g. Lowtility → Kirchhoff "
                       "→ smart:EQ → smart:reverb) and SAVE it as a .vstpreset into:\n"
                       f"  {folder}\n"
                       "Then run this again — the chain/order comes from your seed; only "
                       "each plug-in's settings get patched per instrument.\n\n", "warn")
        else:
            names = ", ".join(PW_PLUGIN_NAMES[c] for c in
                              (PW_CLS_LOWTILITY, PW_CLS_KIRCHHOFF, PW_CLS_SMARTEQ,
                               PW_CLS_SMARTREVERB) if c in slots)
            txt.insert("end", f"seed: {os.path.basename(seed_path)}\n", "re")
            txt.insert("end", f"chain in seed: {names}\n", "re")
            txt.insert("end", f"→ written to: {folder}\n\n", "re")

        if made:
            txt.insert("end", "Created (one .vstpreset = the whole channel strip):\n", "h")
            for iid, fn, touched in made:
                txt.insert("end", f"  + {id2name.get(iid, iid):22s} → {fn}\n", "ok")
                txt.insert("end", f"        patched: {', '.join(touched) or '(nothing matched)'}\n", "re")
            txt.insert("end", "\n")
        if skip:
            txt.insert("end", "Kept (already exist — generate again and answer Overwrite to replace):\n", "h")
            for iid, fn in skip:
                txt.insert("end", f"  · {id2name.get(iid, iid):22s} {fn}\n", "re")
            txt.insert("end", "\n")
        if errors:
            txt.insert("end", "Problems:\n", "warn")
            for iid, msg in errors:
                txt.insert("end", f"  ! {id2name.get(iid, iid)}: {msg}\n", "warn")
            txt.insert("end", "\n")

        if made:
            txt.insert("end", "How to use:\n", "h")
            txt.insert("end",
                       "  Load ONE of these on a track's Blue Cat's PatchWork and the\n"
                       "  whole strip is set at once — no need to load each plug-in.\n", "re")
            if PW_CLS_SMARTEQ in slots:
                txt.insert("end",
                           "  smart:EQ is COPIED from your seed (its learned curve). It is an\n"
                           "  AI black box — re-run smart:EQ's Learn on each track for a correct\n"
                           "  curve, or rank competitors by the Front/Mid/Back tier.\n", "warn")
            if not nohp:
                txt.insert("end",
                           "  TIP: Lowtility already does the high-pass in this chain, so you may\n"
                           "  want Generate ▸ Options ▸ 'Kirchhoff: no high-pass' ON to avoid a\n"
                           "  double HP (Lowtility + Kirchhoff).\n", "warn")
            txt.insert("end", f"\nBackups in:\n  {help_dir}\n", "re")
        self._replaced_section(txt)
        txt.configure(state="disabled")
        top.bind("<Escape>", lambda e: top.destroy())
        top.grab_set()
        top.focus_force()

    def _on_sonible_pertier_toggle(self):
        self.settings["sonible_per_tier"] = bool(self.sonible_pertier_var.get())
        save_settings(self.settings)

    def _generate_sonible_selected(self):
        checked = self._panel_ids()
        if not checked:
            from tkinter import messagebox
            messagebox.showinfo(APP_NAME, "Tick some instruments on the left first.",
                                parent=self.root)
            return
        self._generate_sonible_presets(checked,
                                       source_label=(self.current_variant or "selected"))

    def _generate_sonible_all(self):
        self._generate_sonible_presets([x["id"] for x in EQ_DATA], source_label="ALL")

    def _generate_sonible_presets(self, ids, source_label=""):
        """smart:reverb ONLY. Patch EXACT Distance/Size/Width (from DEPTH_SPEC) into
        your seed preset; everything else (the learned profile, character) is copied
        byte-for-byte. DRY parts (kick/bass) are skipped.

        Two layouts (the 'Per tier (buses)' checkbox):
          • per instrument (default): '0---<Label>.vstpreset' each.
          • per tier (recommended for the bus workflow): one '0---Reverb-FRONT/NEAR/
            MID/FAR.vstpreset' — load each on a depth bus and send tracks to it.
        smart:EQ is intentionally NOT generated (see _build_summary comment / Help).
        A text recipe + Helpfiles backups are written so a wipe can't lose them."""
        by_id = {x["id"]: x for x in EQ_DATA}
        ids = [i for i in ids if i in by_id]
        if not ids:
            self._toast("No instruments selected.")
            return

        overwrite = self._ow("smart:reverb")
        per_tier  = bool(self.sonible_pertier_var.get())

        rev_dir  = self._sonible_reverb_dir()
        rev_ok   = os.path.isdir(rev_dir)
        rev_seed_path = self._sonible_seed(rev_dir) if rev_ok else None
        rev_seed = rev_seed_vals = None
        if rev_seed_path:
            try:
                with open(rev_seed_path, "rb") as f:
                    rev_seed = f.read()
                rev_seed_vals = read_smartreverb_values(rev_seed)
            except Exception:
                rev_seed = None

        help_dir = get_helpfiles_dir(PRESETS_SMARTREVERB)
        self._replaced = []
        rev_made, rev_skip, errors, manifest = [], [], [], []

        def _write(fn, spec):
            dst = os.path.join(rev_dir, fn)
            if os.path.exists(dst) and not overwrite:
                rev_skip.append(fn)
                return
            try:
                patched = patch_smartreverb(rev_seed, spec["distance"],
                                            spec["size"], spec["width"])
                self._put(dst, patched, fn)
                try:                              # backup copy (survives wipes)
                    self._put(os.path.join(help_dir, fn), patched, fn + "  [Helpfiles copy]")
                except Exception:
                    pass
                rev_made.append((fn, spec))
            except Exception as e:
                errors.append((fn, str(e)))

        # Build the instrument→tier manifest (for the recipe + per-tier de-dup).
        tiers_used = {}                                  # tier -> spec
        for iid in ids:
            d = depth_for(iid)                           # (tier, spec, note) or None
            tier = d[0] if d else None
            spec = d[1] if d else None
            manifest.append((iid, tier, spec))
            if spec and tier != "dry" and spec.get("distance") is not None:
                tiers_used[tier] = spec

        if rev_seed:
            if per_tier:
                for tier in ("front", "near", "mid", "far"):
                    if tier in tiers_used:
                        spec = tiers_used[tier]
                        _write(f"0---Reverb-{spec['label']}.vstpreset", spec)
            else:
                for iid, tier, spec in manifest:
                    if spec and tier != "dry" and spec.get("distance") is not None:
                        _write(f"0---{self.KEQ_LABEL.get(iid, iid)}.vstpreset", spec)

        self._sonible_write_recipe(source_label, manifest, help_dir,
                                   rev_seed_path, rev_seed_vals, per_tier)
        self._sonible_report(rev_made, rev_skip, errors, rev_dir, rev_ok,
                             rev_seed_path, rev_seed_vals, per_tier, help_dir)

    def _sonible_write_recipe(self, label, manifest, help_dir, seed_path, seed_vals,
                              per_tier):
        """Plain-text recipe: per instrument the reverb numbers + smart:EQ group
        tier. So even if a .vstpreset vanishes you can re-dial it in seconds."""
        try:
            ts = datetime.now().strftime("%Y%m%d_%H%M%S")
            safe = _re.sub(r"[^A-Za-z0-9_-]+", "_", label or "song") or "song"
            path = os.path.join(help_dir, f"sonible_{safe}_{ts}.txt")
            id2name = {x["id"]: x["name"] for x in EQ_DATA}
            with open(path, "w", encoding="utf-8") as f:
                f.write(f"Sonible recipe - {label}\nGenerated: {ts}\n")
                if seed_path:
                    f.write(f"smart:reverb seed: {os.path.basename(seed_path)}")
                    if seed_vals:
                        f.write(f"  (seed D/Size/Width = "
                                f"{seed_vals[0]:g}/{seed_vals[1]:g}/{seed_vals[2]:g})")
                    f.write("\n")
                f.write("\nsmart:REVERB (the .vstpreset files):\n")
                if per_tier:
                    f.write("  Bus workflow: put one smart:reverb on each depth BUS, load the\n"
                            "  matching '0---Reverb-<TIER>' preset, and send each track to its bus.\n")
                else:
                    f.write("  Load '0---<name>' on each track's reverb. Distance/Size/Width are\n"
                            "  pre-set; lean the character puck toward the corner shown.\n")
                f.write("  Do NOT use smart:reverb's internal GROUP with these (they are clones of\n"
                        "  one instance, so the plugin can't tell them apart). Use depth buses.\n\n")
                f.write("smart:EQ: NOT a preset. Add it MANUALLY (right name + flat EQ), run Learn,\n"
                        "  and rank competing tracks by the GROUP tier below (Front beats Mid beats\n"
                        "  Back). Keep your Kirchhoff EQ as the tonal/corrective layer.\n\n")
                f.write(f"  {'Instrument':24s} {'Reverb (D/Size/Width . char)':34s} smart:EQ group\n")
                f.write(f"  {'-'*24} {'-'*34} {'-'*14}\n")
                for iid, tier, spec in manifest:
                    if spec and tier != "dry" and spec.get("distance") is not None:
                        rv = f"{spec['label']}: {spec['distance']}/{spec['size']}/{spec['width']} . {spec['char']}"
                    elif tier == "dry":
                        rv = "DRY - no reverb"
                    else:
                        rv = "-"
                    grp = smarteq_group_for(iid)
                    gl = grp[2] if grp else "-"
                    f.write(f"  {id2name.get(iid, iid):24s} {rv:34s} {gl}\n")
        except Exception:
            pass

    def _sonible_report(self, rev_made, rev_skip, errors, rev_dir, rev_ok,
                        rev_seed_path, rev_seed_vals, per_tier, help_dir):
        """Informational dialog: what was created, the seed used, where, how to
        verify, and the grouping/bus advice. ESC / grab_set / focus_force."""
        top = tk.Toplevel(self.root)
        top.title("smart:reverb presets")
        top.configure(bg=C_BG)
        top.geometry("680x580")
        top.transient(self.root)

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🌫  smart:reverb presets",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999, padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        mode = "per depth tier (bus workflow)" if per_tier else "per instrument"
        txt.insert("end", f"{len(rev_made)} created · {len(rev_skip)} kept   ({mode})\n\n", "h")

        if not rev_ok:
            txt.insert("end", f"smart:reverb folder not found:\n  {rev_dir}\n"
                              "  Set it via  File ▸ Set smart:reverb preset folder…\n\n", "warn")
        elif not rev_seed_path:
            txt.insert("end", "No SEED preset found. Make ONE reverb preset by ear in the plugin "
                              "(e.g. 'Lead vocal') and save it into:\n"
                              f"  {rev_dir}\n"
                              "Then run this again — only Distance/Size/Width get patched; "
                              "everything else is copied from your seed.\n\n", "warn")
        else:
            sv = (f"  (D/Size/Width = {rev_seed_vals[0]:g}/{rev_seed_vals[1]:g}/"
                  f"{rev_seed_vals[2]:g})" if rev_seed_vals else "")
            txt.insert("end", f"seed: {os.path.basename(rev_seed_path)}{sv}\n", "re")
            txt.insert("end", f"→ written to: {rev_dir}\n\n", "re")

        if rev_made:
            txt.insert("end", "created (exact Distance / Size / Width):\n", "h")
            for fn, spec in rev_made:
                txt.insert("end", f"  + D{spec['distance']}/S{spec['size']}/W{spec['width']} "
                                  f"· {spec['char']:9s} → {fn}\n", "ok")
            txt.insert("end", "\n")
        if rev_skip:
            txt.insert("end", "kept (already exist — generate again and answer Overwrite to replace):\n", "h")
            for fn in rev_skip:
                txt.insert("end", f"  · {fn}\n", "re")
            txt.insert("end", "\n")
        if errors:
            txt.insert("end", "problems:\n", "warn")
            for fn, msg in errors:
                txt.insert("end", f"  ! {fn}: {msg}\n", "warn")
            txt.insert("end", "\n")

        txt.insert("end", "GROUPS: don't add these to a smart:reverb GROUP — they are clones of one "
                          "instance, so the plugin can't tell them apart (the group flickers / "
                          "'add to group' is empty). You don't need groups: put smart:reverb on 2–3 "
                          "depth BUSES (Near/Mid/Far) and send each track to its bus. Tick "
                          "'Per tier (buses)' to get exactly those few presets.\n\n", "warn")
        txt.insert("end", "VERIFY ONCE: open one preset and confirm the Distance / Size / Width knobs "
                          "read the numbers above (Width is the one value I inferred — tell me if it "
                          "looks off).\n\n", "re")
        txt.insert("end", f"A text recipe + backups were written to:\n  {help_dir}\n", "re")
        self._replaced_section(txt)
        txt.config(state="disabled")

        top.bind("<Escape>", lambda e: top.destroy())
        top.grab_set()
        top.focus_force()

    def _generate_presets(self, ids, constellation, source_label=""):
        """Create one Kirchhoff .keq per instrument. Constellation=True applies the
        mix (clash) adjustments; False writes the solo baseline. Identical EQ is
        de-duplicated via the registry so 500 songs need only a handful of presets.
        Names carry NO date (DEL 02s): a changed EQ takes over the same name and the
        file it replaces is kept beside it as '.bak'."""
        by_id = {x["id"]: x for x in EQ_DATA}
        ids = [i for i in ids if i in by_id]
        if not ids:
            self._toast("No instruments selected.")
            return

        help_dir  = get_helpfiles_dir(PRESETS_KIRCHHOFF)
        target    = self._keq_target_dir()
        target_ok = bool(target) and os.path.isdir(target)
        copy_fail = False
        overwrite = False        # v3.37: an identical Kirchhoff EQ is reused (same signature); nothing to ask
        nohp      = bool(self.keq_nohp_var.get())   # omit High-Pass band (Lowtility does it)
        reg = self._keq_load_registry()
        recs = self._mix_recommendations(set(ids)) if constellation else None

        # Optional: also write a Cubase .vstpreset (wraps the same .keq JSON) so the
        # presets show up in CUBASE's own preset browser, not only Kirchhoff's.
        vst3_dir = self._keq_vst3_target_dir() if self.keq_vst3_var.get() else ""
        vst3_tpl = self._keq_vst3_template() if vst3_dir else None
        vst3_made = 0

        created, reused, overwritten, migrated, manifest = [], [], [], [], []
        restored = []                     # in the registry, but a file was missing -> written again
        self._replaced = []
        for iid in ids:
            inst = by_id[iid]
            if constellation and recs:
                eff, _ = self._apply_edits(inst, recs[iid]["edits"])
                changed  = any(b.get("_changed") for b in eff)
                clashers = [j for j in ids if j != iid] if changed else []
            else:
                eff, clashers = inst["bands"], []

            params = []
            for b in eff:
                if nohp and b.get("filter") == "High-pass":
                    continue            # skip the high-pass — Lowtility handles it
                k = kirchhoff_band(b)
                params.append({
                    "ktype": k["ktype"], "freq_hz": k["freq_hz"],
                    "gain_db": k["gain_db"], "q_val": k["q_val"],
                    "slope_norm": k["slope_norm"], "sp_norm": self._keq_sp_for(iid, k),
                })

            sig = self._keq_signature(iid, params)
            if nohp:                      # keep the 'no-HP' set distinct in the registry
                sig = "noHP;" + sig
            hit = next((p for p in reg["presets"] if p["sig"] == sig), None)
            legacy_hit = bool(hit) and strip_legacy_prefix(hit["name"]) != hit["name"]
            gone = False
            if hit:
                # The registry only REMEMBERS a preset - trust it only while its files are
                # really there (Helpfiles copy + the Kirchhoff folder), else write them again.
                fn0 = hit.get("file") or hit["name"] + ".keq"
                gone = (not os.path.isfile(os.path.join(help_dir, fn0))
                        or (target_ok and not os.path.isfile(os.path.join(target, fn0))))
            if hit and not overwrite and not legacy_hit and not gone:
                reused.append((iid, hit["name"]))
                manifest.append((iid, hit["name"]))
                continue

            was_migrated = False
            if hit:                       # overwrite / rename / restore an existing preset
                name, is_new = hit["name"], False
                plain = strip_legacy_prefix(name)
                if plain != name:
                    # A legacy '0---X' / '2026-06---X' name moves to the plain 'X' (no
                    # date, DEL 02s). We write the new file and update the registry; the
                    # old file is LEFT on disk (delete it once the songs use the new one -
                    # FxChainChecker repoints the chains). Never auto-delete here.
                    name = plain
                    hit["name"] = name
                    hit["file"] = name + ".keq"
                    was_migrated = True
            else:
                name, is_new = self._keq_preset_name(iid, clashers, reg, nohp=nohp), True
            # An older entry with the SAME name but another EQ: this preset takes the
            # name over (the old file is backed up below), so the registry must not
            # list two presets under one name.
            taken = [p for p in reg["presets"] if p["name"] == name and p is not hit]
            if taken:
                reg["presets"] = [p for p in reg["presets"]
                                  if not any(p is t for t in taken)]
            fn = name + ".keq"
            d  = build_keq_dict(params)
            data = keq_bytes(d)
            try:
                self._put(os.path.join(help_dir, fn), data, fn + "  [Helpfiles copy]")
            except Exception:
                continue
            if target_ok:
                try:
                    self._put(os.path.join(target, fn), data, fn + "  [Kirchhoff folder]")
                except Exception:
                    copy_fail = True
            if vst3_tpl:
                try:
                    json_bytes = json.dumps(d, indent=4, ensure_ascii=False).encode("utf-8")
                    vp = keq_json_to_vstpreset(json_bytes, vst3_tpl)
                    if vp:
                        self._put(os.path.join(vst3_dir, name + ".vstpreset"), vp,
                                  name + ".vstpreset  [Cubase folder]")
                        vst3_made += 1
                except Exception:
                    pass
            if is_new:
                reg["presets"].append({"sig": sig, "name": name, "file": fn, "inst": iid})
                (overwritten if taken else created).append((iid, name))
            elif was_migrated:
                migrated.append((iid, name))
            elif gone and not overwrite:
                restored.append((iid, name))
            else:
                overwritten.append((iid, name))
            manifest.append((iid, name))

        self._keq_save_registry(reg)
        self._keq_write_manifest(source_label, manifest)
        vst3_info = None
        if self.keq_vst3_var.get():
            vst3_info = (vst3_made, vst3_dir, vst3_tpl is not None)
        self._keq_report(created, reused, overwritten, help_dir, target, target_ok,
                         copy_fail, vst3_info, migrated, restored)

    def _keq_write_manifest(self, label, manifest):
        """A plain-text 'which preset for which track' list for this song."""
        try:
            ts = datetime.now().strftime("%Y%m%d_%H%M%S")
            safe = _re.sub(r"[^A-Za-z0-9_-]+", "_", label or "song") or "song"
            path = os.path.join(get_helpfiles_dir(PRESETS_KIRCHHOFF),
                                f"song_{safe}_{ts}.txt")
            id2name = {x["id"]: x["name"] for x in EQ_DATA}
            with open(path, "w", encoding="utf-8") as f:
                f.write(f"Song / set : {label}\nGenerated  : {ts}\n\n")
                f.write("Load this Kirchhoff preset on each track:\n\n")
                for iid, name in manifest:
                    f.write(f"  {id2name.get(iid, iid):26s} ->  {name}.keq\n")
        except Exception:
            pass

    def _keq_report(self, created, reused, overwritten, help_dir, target,
                    target_ok, copy_fail, vst3_info=None, migrated=None, restored=None):
        """Informational dialog: what was created / reused / overwritten and where.
        vst3_info = (count_written, folder, template_found) or None when not making
        Cubase .vstpreset files. migrated = legacy '0---' / dated presets moved to the
        plain name (no date)."""
        migrated = migrated or []
        restored = restored or []
        id2name = {x["id"]: x["name"] for x in EQ_DATA}
        top = tk.Toplevel(self.root)
        top.title("Kirchhoff presets")
        top.configure(bg=C_BG)
        top.geometry("640x520")
        top.transient(self.root)

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🎛  Kirchhoff preset generation",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        txt = tk.Text(top, bg=C_BG2, fg=C_FG, font=FONT_MONO, relief="flat", bd=0,
                      wrap="word", insertofftime=0, insertontime=9999999, padx=10, pady=8)
        no_blink(txt)
        vsb = tk.Scrollbar(top, command=txt.yview, bg=C_BG2,
                           troughcolor=C_BG, activebackground=C_ACCENT)
        txt.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.tag_configure("h",  foreground=C_ACCENT, font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok", foreground=C_BOOST)
        txt.tag_configure("re", foreground=C_FG_DIM)
        txt.tag_configure("warn", foreground=C_CUT)

        txt.insert("end", f"Created {len(created)} · renamed {len(migrated)} · "
                          f"restored {len(restored)} · "
                          f"overwritten {len(overwritten)} · reused {len(reused)}.\n\n", "h")
        if restored:
            txt.insert("end", "RESTORED (known preset, but a file was missing - written again):\n", "h")
            for iid, name in restored:
                txt.insert("end", f"  ↻ {id2name.get(iid, iid):24s} {name}.keq\n", "ok")
            txt.insert("end", "\n")
        if migrated:
            txt.insert("end", "RENAMED to the plain name, no date (new file written):\n", "h")
            for iid, name in migrated:
                txt.insert("end", f"  → {id2name.get(iid, iid):24s} {name}.keq\n", "ok")
            txt.insert("end", "  The old '0---…' / dated files are LEFT in place — delete them\n"
                              "  yourself once your songs use the new names (FxChainChecker\n"
                              "  → Fix missing... repoints the chains).\n\n", "re")
        if created:
            txt.insert("end", "NEW presets:\n", "h")
            for iid, name in created:
                txt.insert("end", f"  + {id2name.get(iid, iid):24s} {name}.keq\n", "ok")
            txt.insert("end", "\n")
        if overwritten:
            txt.insert("end", "OVERWRITTEN (existing files replaced, old ones kept as .bak):\n", "h")
            for iid, name in overwritten:
                txt.insert("end", f"  ~ {id2name.get(iid, iid):24s} {name}.keq\n", "warn")
            txt.insert("end", "\n")
        if reused:
            txt.insert("end", "Reused (identical EQ already existed):\n", "h")
            for iid, name in reused:
                txt.insert("end", f"  = {id2name.get(iid, iid):24s} {name}.keq\n", "re")
            txt.insert("end", "\n")
        txt.insert("end", "Saved to Helpfiles:\n", "h")
        txt.insert("end", f"  {help_dir}\n\n")
        txt.insert("end", "Copied to Kirchhoff presets folder:\n", "h")
        if target_ok and not copy_fail:
            txt.insert("end", f"  {target}\n", "ok")
        elif target_ok and copy_fail:
            txt.insert("end", f"  {target}\n  (some copies FAILED — is Kirchhoff/Cubase locking the folder?)\n", "warn")
        else:
            txt.insert("end", f"  NOT copied — folder not found:\n  {target or '(unset)'}\n"
                              f"  Set it via  File ▸ Set Kirchhoff preset folder…\n", "warn")

        # Cubase .vstpreset (so the presets show in CUBASE's own preset browser).
        if vst3_info is not None:
            made, vdir, had_tpl = vst3_info
            txt.insert("end", "\nAlso written as Cubase .vstpreset:\n", "h")
            if not had_tpl:
                txt.insert("end", f"  NONE — no template .vstpreset found in:\n  {vdir}\n"
                                  "  Save ONE Kirchhoff preset from Cubase into that folder first\n"
                                  "  (or set the folder via File ▸ Set Kirchhoff .vstpreset folder…),\n"
                                  "  then re-generate. These are what show in Cubase's preset list.\n", "warn")
            else:
                txt.insert("end", f"  {made} file(s) → {vdir}\n", "ok")
                txt.insert("end", "  (open Cubase's OWN preset selector — the field by the\n"
                                  "   sidechain button — and they'll be there.)\n", "re")
        self._replaced_section(txt)
        txt.configure(state="disabled")

        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    # ---- OVERVIEW WINDOWS ---------------------------------------------------

    def _show_overview_selected(self):
        checked = self._panel_ids()
        instruments = [x for x in EQ_DATA if x["id"] in checked]
        if not instruments:
            import tkinter.messagebox as mb
            mb.showinfo("Overview: Selected",
                        "No instruments are checked.\nTick checkboxes on the left first.",
                        parent=self.root)
            return
        self._build_overview_window(
            f"EQ Overview \u2014 Selected ({len(instruments)})", instruments)

    def _show_overview_all(self):
        self._build_overview_window(
            f"EQ Overview \u2014 All Instruments ({len(EQ_DATA)})", EQ_DATA)

    # ---- PLANNER (one-screen overview: buses + dynamics + chain) ------------
    def _show_planner_selected(self):
        checked = self._panel_ids()
        instruments = [x for x in EQ_DATA if x["id"] in checked]
        if not instruments:
            import tkinter.messagebox as mb
            mb.showinfo("Planner: Selected",
                        "No instruments are checked.\nTick checkboxes on the left first.",
                        parent=self.root)
            return
        self._build_planner_window(
            f"Mix Planner \u2014 Selected ({len(instruments)})", instruments)

    def _show_planner_all(self):
        self._build_planner_window(
            f"Mix Planner \u2014 All Instruments ({len(EQ_DATA)})", EQ_DATA)

    def _build_planner_window(self, title, instruments):
        """One-screen planning table: every instrument as a row with its whole
        channel plan (low-cut \u00b7 compressor \u00b7 smart:EQ tier \u00b7 reverb \u00b7 duck), so
        you can decide which GROUP BUSES to create without paging back and forth
        between instrument cards."""
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=C_BG)
        top.geometry("1080x720")
        top.transient(self.root)
        top.bind("<Escape>", lambda e: top.destroy())

        # Header
        hdr = tk.Frame(top, bg=C_BG3, pady=7, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text=f"\U0001f9ed  {title}", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 12, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")
        tk.Label(top,
                 text="Read left\u2192right = the channel strip order.  Group buses are "
                      "suggested per family at the bottom and as each group heading.",
                 bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL).pack(anchor="w", padx=14, pady=(4, 0))

        # Scrollable area
        outer = tk.Frame(top, bg=C_BG); outer.pack(fill="both", expand=True)
        canv = tk.Canvas(outer, bg=C_BG, bd=0, highlightthickness=0)
        vsb  = tk.Scrollbar(outer, orient="vertical", command=canv.yview,
                            bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canv.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y"); canv.pack(side="left", fill="both", expand=True)
        inner = tk.Frame(canv, bg=C_BG)
        win_id = canv.create_window((0, 0), window=inner, anchor="nw")
        canv.bind("<Configure>", lambda e: canv.itemconfig(win_id, width=e.width))
        inner.bind("<Configure>", lambda e: canv.configure(scrollregion=canv.bbox("all")))
        def _wheel(e):
            canv.yview_scroll(max(1, abs(round(e.delta / 40))) * (-1 if e.delta > 0 else 1), "units")
        canv.bind("<MouseWheel>", _wheel); inner.bind("<MouseWheel>", _wheel)

        COLS = ["Instrument", "\ud83d\udd3b Low cut", "\ud83d\udddc Compressor", "\ud83c\udfaf smart:EQ", "\ud83c\udf2b Reverb", "\ud83e\udd86 Duck"]
        CW   = [200, 130, 250, 110, 150, 150]

        # Group instruments by family (preserve EQ_DATA order)
        groups_seen, group_insts = [], {}
        for inst in instruments:
            g = inst["group"]
            if g not in group_insts:
                groups_seen.append(g); group_insts[g] = []
            group_insts[g].append(inst)

        def _cell(parent, text, col, fg=C_FG, bold=False, r=0):
            lab = tk.Label(parent, text=text, bg=parent["bg"], fg=fg,
                           font=("Segoe UI", 8, "bold") if bold else FONT_SMALL,
                           wraplength=CW[col] - 8, justify="left", anchor="nw")
            lab.grid(row=r, column=col, sticky="nw", padx=4, pady=2)
            lab.bind("<MouseWheel>", _wheel)
            return lab

        for g in groups_seen:
            fam = self._SMARTEQ_SHORT_FAM.get(g, g)
            gh = tk.Frame(inner, bg=C_BG3, padx=10, pady=4); gh.pack(fill="x", padx=10, pady=(10, 0))
            gh.bind("<MouseWheel>", _wheel)
            tk.Label(gh, text=f"{g}", bg=C_BG3, fg=C_ACCENT,
                     font=("Segoe UI", 10, "bold")).pack(side="left")
            tk.Label(gh, text=f"   \u2192 bus: \u201c{fam}\u201d  (glue 2:1, 1\u20133 dB)",
                     bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left")

            tbl = tk.Frame(inner, bg=C_CARD, padx=8, pady=4); tbl.pack(fill="x", padx=10, pady=(0, 2))
            tbl.bind("<MouseWheel>", _wheel)
            for c, head in enumerate(COLS):
                _cell(tbl, head, c, fg=C_FG_DIM, bold=True, r=0)
            for ri, inst in enumerate(group_insts[g], start=1):
                iid = inst["id"]
                n_of = self._count_of(iid)
                _cell(tbl, inst["name"] + (f"  ✖{n_of}" if n_of > 1 else ""),
                      0, fg=inst.get("color", C_FG), bold=True, r=ri)
                lc = lowcut_for(iid)
                lctxt = f"{lc[0]} Hz \u00b7 {lc[1]} dB/oct" if lc else "\u2014"
                if lc and n_of > 1:
                    # Only ONE copy keeps the low end; the rest are cut higher.
                    ladder = [str(int(round(lc[0] * (1.0 + 0.30 * k) / 5.0) * 5))
                              for k in range(1, n_of)]
                    lctxt += "  (then " + "/".join(ladder) + " Hz)"
                _cell(tbl, lctxt, 1, fg=LOWCUT_COLOUR, r=ri)
                ci = compression_for(iid)
                if ci:
                    _t, sp, _n = ci
                    ctxt = "NONE" if _t == "none" else f"{sp['label']} \u00b7 {sp['ratio']} \u00b7 GR {sp['gr']}"
                else:
                    ctxt = "\u2014"
                _cell(tbl, ctxt, 2, fg=COMP_COLOUR, r=ri)
                se = smarteq_group_for(iid)
                _cell(tbl, (f"{se[0]} {se[2]}" if se else "\u2014"), 3, fg=C_BOOST, r=ri)
                dp = depth_for(iid)
                # Blank = no reverb on this channel. We do not spell out "DRY".
                if dp and dp[0] != "dry":
                    dtxt = dp[1]["label"]
                else:
                    dtxt = ""
                _cell(tbl, dtxt, 4, fg=DEPTH_COLOUR, r=ri)
                # Gated on the plan itself: a duck whose source isn't in this
                # plan is not printed (no kick -> no "under Kick" on the bass).
                dk = ducking_for(iid, {x["id"] for x in instruments})
                _cell(tbl, (f"under {dk['src']}" if dk else "\u2014"), 5, fg="#ffcf8f", r=ri)

        # \u2500\u2500 Suggested bus plan (reuse the smart:EQ sub-bus grouping) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
        plan, slots, merges = self._smarteq_busplan([i["id"] for i in instruments])
        bp = tk.Frame(inner, bg=C_BG2, padx=12, pady=8); bp.pack(fill="x", padx=10, pady=(12, 12))
        bp.bind("<MouseWheel>", _wheel)
        tk.Label(bp, text=f"\ud83d\ude8c Suggested group buses  ({slots} of "
                          f"{self.SMARTEQ_MAX_SLOTS} smart:EQ slots)",
                 bg=C_BG2, fg=C_ACCENT, font=("Segoe UI", 10, "bold")).pack(anchor="w")
        for b in plan:
            line = (f"\u2022 {b['bus']}" + ("  (own bus)" if b["solo"] else "")
                    + f"  \u2014  {', '.join(b['members'])}")
            tk.Label(bp, text=line, bg=C_BG2, fg=(b.get("colour") or C_FG),
                     font=FONT_SMALL, wraplength=1000, justify="left",
                     anchor="w").pack(fill="x")
        for m in merges:
            tk.Label(bp, text=("   \u25c6 merged: " if m["applied"] else "   \u25c7 could merge: ")
                              + " + ".join(m["buses"]) + f"  \u2192  \u201c{m['name']}\u201d",
                     bg=C_BG2, fg=m["colour"], font=("Segoe UI", 8, "bold"),
                     wraplength=1000, justify="left", anchor="w").pack(fill="x")
        tk.Label(bp, text="Master: limiter / loudness tool LAST (not on individual "
                          "channels). A clipper on single drum hits is the only "
                          "per-channel 'limiter'.",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL, wraplength=1000,
                 justify="left", anchor="w").pack(fill="x", pady=(6, 0))

    def _build_overview_window(self, title, instruments):
        """Pop-up window: combined overlay curve + per-instrument EQ curves."""
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=C_BG)
        top.geometry("900x680")
        top.transient(self.root)
        top.bind("<Escape>", lambda e: top.destroy())

        # Header
        hdr = tk.Frame(top, bg=C_BG3, pady=7, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text=f"\U0001f4ca  {title}",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 12, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)",
                  bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")

        # Legend
        leg = tk.Frame(top, bg=C_BG2, padx=10, pady=4)
        leg.pack(fill="x")
        for label, color in [("BOOST", C_BOOST), ("CUT", C_CUT),
                              ("TRY", C_CHAR), ("NEUTRAL", C_NEUTRAL)]:
            tk.Label(leg, text="\u25cf", fg=color, bg=C_BG2,
                     font=("Segoe UI", 10)).pack(side="left")
            tk.Label(leg, text=label, fg=color, bg=C_BG2,
                     font=FONT_SMALL).pack(side="left", padx=(0, 10))
        tk.Label(leg, text="   20 Hz \u2192 20 kHz  (log scale)",
                 fg=C_FG_DIM, bg=C_BG2, font=FONT_SMALL).pack(side="left")

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        # Scrollable area
        outer = tk.Frame(top, bg=C_BG)
        outer.pack(fill="both", expand=True)
        canv = tk.Canvas(outer, bg=C_BG, bd=0, highlightthickness=0)
        vsb  = tk.Scrollbar(outer, orient="vertical", command=canv.yview,
                            bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canv.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canv.pack(side="left", fill="both", expand=True)

        inner = tk.Frame(canv, bg=C_BG)
        win_id = canv.create_window((0, 0), window=inner, anchor="nw")

        def _cfg(e):   canv.configure(scrollregion=canv.bbox("all"))
        def _rsz(e):   canv.itemconfig(win_id, width=e.width)
        def _wheel(e): canv.yview_scroll(max(1, abs(round(e.delta / 40))) * (-1 if e.delta > 0 else 1), "units")

        inner.bind("<Configure>", _cfg)
        canv.bind("<Configure>", _rsz)
        canv.bind("<MouseWheel>", _wheel)
        inner.bind("<MouseWheel>", _wheel)

        CURVE_H = 80
        COMBO_H = 120

        # Combined overlay
        tk.Label(inner, text="Combined overlay \u2014 all shown instruments",
                 bg=C_BG, fg=C_ACCENT, font=FONT_HEADER
                 ).pack(anchor="w", padx=14, pady=(10, 2))

        all_bands = [b for inst in instruments for b in inst["bands"]]
        combo_cv  = tk.Canvas(inner, bg=C_BG2, bd=0, highlightthickness=0, height=COMBO_H)
        combo_cv.pack(fill="x", padx=14, pady=(0, 6))
        combo_cv.bind("<Configure>",
                      lambda e, cv=combo_cv, bands=all_bands:
                          _draw_combined_curve(cv, bands, e.width, e.height, C_BG2))
        combo_cv.bind("<MouseWheel>", _wheel)

        tk.Frame(inner, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=(0, 8))

        # Per-instrument rows, grouped
        groups_seen = []
        group_insts = {}
        for inst in instruments:
            g = inst["group"]
            if g not in group_insts:
                groups_seen.append(g)
                group_insts[g] = []
            group_insts[g].append(inst)

        for g in groups_seen:
            tk.Label(inner, text=g,
                     bg=C_BG, fg=C_FG_DIM, font=FONT_HEADER
                     ).pack(anchor="w", padx=14, pady=(6, 2))

            for inst in group_insts[g]:
                row = tk.Frame(inner, bg=C_CARD)
                row.pack(fill="x", padx=14, pady=(0, 4))
                row.bind("<MouseWheel>", _wheel)

                # Name column (fixed width)
                name_col = tk.Frame(row, bg=C_CARD, width=140)
                name_col.pack(side="left", fill="y", padx=(10, 0), pady=6)
                name_col.pack_propagate(False)
                name_col.bind("<MouseWheel>", _wheel)

                dot_color = inst.get("color", C_FG)
                tk.Label(name_col, text="\u25cf", fg=dot_color, bg=C_CARD,
                         font=("Segoe UI", 12)).pack(anchor="w")
                tk.Label(name_col, text=inst["name"],
                         bg=C_CARD, fg=C_FG, font=FONT_TITLE,
                         wraplength=130, justify="left").pack(anchor="w")
                tk.Label(name_col, text=inst["sub"],
                         bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                         wraplength=130, justify="left").pack(anchor="w")

                # Curve canvas
                cv = tk.Canvas(row, bg=C_BG2, bd=0, highlightthickness=0, height=CURVE_H)
                cv.pack(side="left", fill="both", expand=True, padx=6, pady=6)
                cv.bind("<Configure>",
                        lambda e, c=cv, b=inst["bands"]:
                            _draw_eq_curve_on(c, b, e.width, e.height, C_BG2))
                cv.bind("<MouseWheel>", _wheel)

            tk.Frame(inner, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=(2, 6))

        tk.Button(inner, text="Close",
                  bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_NORMAL, relief="flat", padx=14, pady=4,
                  command=top.destroy).pack(pady=(4, 14))

    # ---- SETTINGS -----------------------------------------------------------

    def _sanitize_geometry(self, geo, default="1300x820"):
        """Keep a restored window ON-SCREEN. A saved geometry can point off-screen
        (a monitor that's gone, or a size bigger than this display) — then only the
        top edge shows. Clamp size to the screen and the position into view."""
        try:
            # Tk reports position as ±X±Y; a window off the LEFT shows as '+-1500'
            # (sign '+' then a negative value), so capture sign and value apart.
            m = _re.match(r'^(\d+)x(\d+)([+-])(-?\d+)([+-])(-?\d+)$', geo or "")
            if not m:
                # "WxH" with no position is fine; anything else → default.
                return geo if _re.match(r'^\d+x\d+$', geo or "") else default
            w, h = int(m.group(1)), int(m.group(2))
            xs, xv, ys, yv = m.group(3), int(m.group(4)), m.group(5), int(m.group(6))
            sw = self.root.winfo_screenwidth()
            sh = self.root.winfo_screenheight()
            # A degenerate saved size (e.g. 120x1 from a stray event) → use default.
            if w < 600 or h < 400:
                w, h = 1300, 820
            w = min(w, sw)
            h = min(h, sh - 48)                    # leave room for the taskbar
            # '-' prefix = measured from the right/bottom edge.
            x = xv if xs == "+" else (sw - w - xv)
            y = yv if ys == "+" else (sh - h - yv)
            x = max(0, min(x, max(0, sw - w)))     # fully on the primary screen
            y = max(0, min(y, max(0, sh - h - 40)))
            return f"{w}x{h}+{x}+{y}"
        except Exception:
            return default

    def _apply_settings(self):
        s = self.settings
        try:
            self.root.geometry(self._sanitize_geometry(s.get("geometry", "1300x820")))
            self.root.deiconify()
            self.root.lift()
        except Exception:
            self.root.geometry("1300x820")
        # Restore checked
        checked = s.get("checked", [])
        for iid, var in self.check_vars.items():
            var.set(iid in checked)
        self._sync_group_all_boxes()
        self._refresh_live_notes()
        self._refresh_summary()
        # Restore tab
        try:
            idx = s.get("tab_index", 0)
            self.notebook.select(idx)
        except Exception:
            pass
        # The picker IS the line-up; settings["checked"] is only its echo.
        # If an older settings file (or a crash) left the two disagreeing,
        # the variant wins - otherwise ⟳ Update would be lit on a launch
        # where nothing has been touched, which is the one thing it must
        # never do.
        try:
            want = {i for i, v in self._vfixed_vars.items() if v.get()}
            have = {i for i, v in self.check_vars.items() if v.get()}
            if want != have:
                self._apply_variant_to_app()
        except Exception:
            pass
        self._snapshot_applied()
        # Restore sash after layout — two attempts for reliability
        self.root.after(100, self._restore_sash)
        self.root.after(350, self._restore_sash)

    def _apply_left_fold(self):
        """Put the left side away or bring it back, as the setting 'left_folded' says."""
        folded = bool(self.settings.get("left_folded", False))
        lf, rf = self._left_frame, self._right_frame
        try:
            shown = str(lf) in [str(p) for p in self.pane.panes()]
            if folded and shown:
                # v3.31: remember the divider ONLY if the panes have really been laid out. At program
                # start the left side is folded before anything is drawn; sash_coord() then answers
                # with the minimum (200), which used to overwrite the saved width - and every later
                # unfold came back squeezed until he dragged it out again.
                self._remember_sash()
                self.pane.forget(lf)
            elif not folded and not shown:
                self.pane.add(lf, before=rf, minsize=200)
                self.root.after(50, self._restore_sash)
                self.root.after(350, self._restore_sash)
        except tk.TclError:
            pass
        btn = getattr(self, "fold_btn", None)
        if btn is not None:
            btn.config(text="▶ Show left side" if folded else "◀ Fold left side")

    def _toggle_left_fold(self):
        self.settings["left_folded"] = not bool(self.settings.get("left_folded", False))
        self._apply_left_fold()
        save_settings(self.settings)

    def _sash_is_real(self):
        """True when the divider position can be trusted: both panes exist and the window has been
        drawn (before that Tk answers with the minimum width, not the real one)."""
        try:
            return (len(self.pane.panes()) == 2 and self.pane.winfo_ismapped()
                    and self._left_frame.winfo_width() > 50 and self.root.winfo_width() > 600)
        except tk.TclError:
            return False

    def _remember_sash(self):
        """Store the divider position - but never a position that was not really laid out."""
        if self._sash_is_real():
            try:
                self.settings["sash_pos"] = self.pane.sash_coord(0)[0]
            except tk.TclError:
                pass

    def _restore_sash(self, tries=0):
        if self.settings.get("left_folded"):
            return
        # The window is not drawn yet (width 1): wait, do not place the divider against a nonsense width.
        if self.root.winfo_width() < 600 or not self.pane.winfo_ismapped():
            if tries < 20:
                self.root.after(100, lambda: self._restore_sash(tries + 1))
            return
        try:
            pos = self.settings.get("sash_pos", 340)
            if not self.settings.get("sash_wide_329"):
                # v3.29, once: the left side (Song Variants, with the Sect column) needs more room,
                # at the expense of Selected Instruments. Drag the divider to taste afterwards.
                pos = max(pos, 820)
                self.settings["sash_wide_329"] = True
            if not self.settings.get("sash_fix_331"):
                # v3.31, once: an earlier version could save the divider at its minimum (200) when it
                # started with the left side folded, so the left side came back squeezed every time.
                pos = max(pos, 820)
                self.settings["sash_fix_331"] = True
            self.settings["sash_pos"] = pos          # the WISH is kept; only the placement is limited
            self.pane.sash_place(0, min(pos, max(340, self.root.winfo_width() - 480)), 0)
        except Exception:
            pass

    def _save_current_settings(self):
        s = self.settings
        try:
            # Only persist a REAL window geometry: skip minimized/withdrawn states
            # and degenerate sizes (a stray Configure event once saved '120x1',
            # which then hid the window off-screen on the next launch).
            if self.root.state() in ("normal", "zoomed"):
                geo = self.root.geometry()
                mm = _re.match(r'^(\d+)x(\d+)', geo or "")
                if mm and int(mm.group(1)) >= 600 and int(mm.group(2)) >= 400:
                    s["geometry"] = geo
        except Exception:
            pass
        try:
            s["tab_index"] = self.notebook.index(self.notebook.select())
        except Exception:
            pass
        s["checked"] = [iid for iid, v in self.check_vars.items() if v.get()]
        s["right_mode"] = self._right_mode
        s["list_order"] = self._list_order()
        try:
            s["instr_filters"] = [k for k, v in self._instr_filter_vars.items() if v.get()]
        except Exception:
            pass
        try:
            s["eq_mode"] = self.eq_mode.get()
        except Exception:
            pass
        save_settings(s)

    def _on_sash_drag(self, event):
        """Save sash position only when user releases the mouse after dragging."""
        try:
            self._remember_sash()
            save_settings(self.settings)
        except Exception:
            pass

    def _on_configure(self, event):
        if event.widget is self.root:
            self._save_current_settings()

    def _on_tab_change(self, event):
        self._save_current_settings()

    def _on_close(self):
        try:
            self._remember_sash()
        except Exception:
            pass
        # Whatever is still waiting for ⟳ Update is written into the variant
        # anyway. The old promise stands: the next launch starts with exactly
        # what you ended with, and nobody has to remember to click Save.
        #
        # ONE EXCEPTION, and it is the only path here that could destroy
        # saved work with no way back: an EMPTY left side is never written
        # over a variant that has a line-up. ↩ Reset followed by closing the
        # program would otherwise wipe it, and the promise above is about
        # the work you did, not about the absence of it. Emptying a variant
        # on purpose is still one click - on ⟳ Update.
        try:
            v = self._find_variant(self.current_variant)
            if v:
                fixed, counts = self._ui_to_current_variant()
                if fixed or not v.get("fixed"):
                    v["fixed"], v["counts"] = fixed, counts
                    v["stage_manual"] = dict(self._stage_manual)
                    v["pairs"] = clean_pairs(self._pairs)
                    v["swam"] = list(self._swam)
                    v["swam_sec"] = list(self._swam_sec)
                    self._persist_variants()
        except Exception:
            pass
        self._save_current_settings()
        self.root.destroy()

    # ---- FREQUENCY BANDS EXPLAINED ------------------------------------------

    # ---- 🎪 STAGE MAP -----------------------------------------------------

    STAGE_MAP_W = 74          # characters across the drawn stage

    def _stage_map_text(self):
        """The whole stage as plain text: a top-down map, then the numbers, then
        the reasons. Returned as [(style, text), …] for the tagged Text widget,
        and joined for the Copy button."""
        rows, info = self._stage()
        out = []
        if not rows:
            out.append(("body", "Nothing is ticked yet, so there is no band to "
                                "place. Tick the instruments on the left.\n"))
            return out, info

        W = self.STAGE_MAP_W
        persp = self._stage_perspective()
        out.append(("h1", "The stage, seen from %s\n"
                    % ("the audience" if persp == "audience"
                       else "behind the drummer")))
        out.append(("body", "Room %s on every instance — %s\n\n"
                    % (info["room"], info["room_why"])))

        # ---- the map -------------------------------------------------------
        ruler = [" "] * W
        for pct, mark in ((-100, "L"), (-50, "|"), (0, "C"), (50, "|"), (100, "R")):
            ruler[self._stage_col(pct, W)] = mark
        out.append(("code", "        " + "".join(ruler) + "\n"))
        out.append(("code", "        " + "─" * W + "   ▲ back of the stage\n"))

        placed = [r for r in rows.values() if r.get("dist") is not None]
        placed.sort(key=lambda r: (-r["dist"], r["pos_pct"]))
        for r in placed:
            line = [" "] * W
            name = _stage_name(r["id"])
            if r.get("skip"):
                name = "(" + name + ")"
            spread = r.get("pos_pcts")
            if spread:
                # A laddered channel is a range, so draw where it starts and
                # where it ends — the name alone would claim one spot it is
                # deliberately NOT standing in.
                line[self._stage_col(min(spread), W)] = "‹"
                line[self._stage_col(max(spread), W)] = "›"
            col = self._stage_col(r["pos_pct"], W)
            start = max(0, min(W - len(name), col - len(name) // 2))
            for k, ch in enumerate(name):
                if start + k < W:
                    line[start + k] = ch
            out.append(("code", "  D%3d │%s\n" % (r["dist"], "".join(line))))
        out.append(("code", "        " + "─" * W + "   ▼ you\n"))
        off = [r for r in rows.values() if r.get("dist") is None]
        if off:
            out.append(("code", "        (not on the stage at all: %s)\n"
                        % ", ".join(_stage_name(r["id"]) for r in off)))
        out.append(("body", "\nA name in (brackets) means the plug-in stays OFF "
                            "that channel — it is drawn so you can see where it "
                            "sits, not so you can process it.\n\n"))

        # ---- the numbers ---------------------------------------------------
        out.append(("h2", "What to dial in\n"))
        for iid in info["order"]:
            r = rows[iid]
            if r.get("swam"):
                out.append(("code", "  %-22s  \u2014 OFF here, placed in SWAM: %s\n"
                            % (_stage_name(iid), swam_text(r["swam"]))))
            elif r.get("skip"):
                out.append(("code", "  %-22s  — leave Virtual Stage OFF\n"
                            % _stage_name(iid)))
                # The one exception in the whole engine: a doubled bass. This
                # window is where the numbers live, so the option lives here
                # too — in full, whatever the comment settings say.
                opt = r.get("option")
                if opt:
                    out.append(("h2", "        " + opt["head"] + "\n"))
                    for ln in opt["lines"]:
                        out.append(("body", "          • " + ln + "\n"))
                    out.append(("tip", "          ⚠ " + opt["condition"] + "\n"))
            else:
                out.append(("code", "  %-22s  %-24s Distance %-4s Room %s%s\n"
                            % (_stage_name(iid), r["pos"], stage_dist_text(r), r["room"],
                               "   Lock Position ON" if r.get("lock") else "")))
                # v3.30: backing vocals as doubles / harmonies / own parts
                _alts = r.get("alts")
                if _alts:
                    out.append(("h2", "        " + _alts["head"] + "\n"))
                    for ln in _alts["lines"]:
                        out.append(("body", "          • " + ln + "\n"))
                    out.append(("tip", "          " + _alts["why"] + "\n"))
        out.append(("body", "\n"))
        out.extend(swam_room_lines(rows, info))          # v3.26: under a row of ****

        # ---- the reasons ---------------------------------------------------
        out.append(("h2", "Why these numbers and not others\n"))
        for n in info["notes"]:
            out.append(("body", "  • " + n + "\n\n"))
        if info.get("kit_notes"):
            out.append(("h2", "The drum kit\n"))
            for n in info["kit_notes"]:
                out.append(("body", "  • " + n + "\n\n"))

        moved = [(iid, rows[iid]["because"]) for iid in info["order"]
                 if rows[iid].get("because")]
        if moved:
            out.append(("h2", "What moved, and because of what\n"))
            for iid, whys in moved:
                out.append(("h2", "  " + _stage_name(iid) + "\n"))
                for w in whys:
                    out.append(("tip", "    ↳ " + w + "\n"))
            out.append(("body", "\n"))

        out.append(("h2", "Where it sits in the chain\n"))
        for head, body in VSTAGE_CHAIN:
            out.append(("h2", "  " + head + "\n"))
            out.append(("body", "    " + body + "\n"))
        return out, info

    def _stage_col(self, pct, width):
        """Position percent → column in the drawn map."""
        pct = max(-100.0, min(100.0, float(pct)))
        return int(round((pct + 100.0) / 200.0 * (width - 1)))

    def _show_stage_map(self):
        """The whole band on one stage: map, numbers, and the reasons.

        Deliberately not a preset generator. Every number in here depends on
        the rest of the line-up, so it is read off the screen and dialled in —
        a saved preset would be a snapshot of a song you are no longer mixing.
        See DEL 02m."""
        top = tk.Toplevel(self.root)
        top.title("Virtual Stage — stage map")
        top.configure(bg=C_BG)
        top.resizable(True, True)
        top.transient(self.root)
        top.geometry("900x680")

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🎪  Virtual Stage — where the band stands",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")

        bar = tk.Frame(top, bg=C_BG2, pady=4, padx=10)
        bar.pack(fill="x")
        tk.Label(bar, text="Seen from:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(0, 8))
        for label, value in (("🧍 Audience (hi-hat right)", "audience"),
                             ("🥁 Drummer (hi-hat left)", "drummer")):
            tk.Radiobutton(bar, text=label, variable=self.stage_persp_var,
                           value=value, bg=C_BG2, fg=C_FG, selectcolor=C_BG3,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=FONT_SMALL, cursor="hand2",
                           command=lambda t=top: self._restage(t)).pack(side="left",
                                                                        padx=(0, 12))
        tk.Button(bar, text="📋 Copy all", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG, font=FONT_SMALL,
                  relief="flat", padx=10, pady=2, cursor="hand2",
                  command=lambda: self._stage_map_copy()).pack(side="right")
        tk.Button(bar, text="✋ By hand…",
                  bg=C_GROUND_BTN, fg=C_BTN_FG,   # normal colour: C_GROUND_BTN
                  activebackground=C_BG, activeforeground=C_FG, font=FONT_SMALL,
                  relief="flat", padx=10, pady=2, cursor="hand2",
                  command=self._show_stage_manual).pack(side="right", padx=(0, 8))

        text_frame = tk.Frame(top, bg=C_BG)
        text_frame.pack(fill="both", expand=True, padx=10, pady=10)
        vsb = tk.Scrollbar(text_frame, bg=C_BG2, troughcolor=C_BG,
                           activebackground=C_ACCENT)
        vsb.pack(side="right", fill="y")
        txt = tk.Text(text_frame, bg=C_BG2, fg=C_FG, font=FONT_NORMAL,
                      relief="flat", bd=0, wrap="word", yscrollcommand=vsb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        vsb.config(command=txt.yview)
        txt.tag_configure("h1",   font=("Segoe UI", 12, "bold"), foreground=VSTAGE_COLOUR)
        txt.tag_configure("h2",   font=("Segoe UI", 10, "bold"), foreground=C_FG)
        txt.tag_configure("body", font=FONT_NORMAL,              foreground=C_FG_DIM)
        txt.tag_configure("code", font=FONT_MONO,                foreground=VSTAGE_COLOUR)
        txt.tag_configure("tip",  font=FONT_SMALL,               foreground=C_CHAR)
        self._stage_map_txt = txt
        self._stage_map_fill(txt)

        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _stage_map_fill(self, txt):
        segs, _info = self._stage_map_text()
        self._stage_map_last = "".join(b for _s, b in segs)
        txt.configure(state="normal")
        txt.delete("1.0", "end")
        for style, body in segs:
            txt.insert("end", body, style)
        txt.configure(state="disabled")

    def _restage(self, top=None):
        """Perspective changed from inside the map window: redraw it AND the
        main panel, so the two never disagree."""
        self._on_stage_persp_change()
        try:
            if self._stage_map_txt.winfo_exists():
                self._stage_map_fill(self._stage_map_txt)
        except Exception:
            pass

    def _stage_map_copy(self):
        try:
            self.root.clipboard_clear()
            self.root.clipboard_append(getattr(self, "_stage_map_last", ""))
        except Exception:
            pass

    # ---- ✋ MANUAL STAGE PLACEMENT (DEL 02m) -----------------------------
    # Three switches, and every one of them is about the ARRANGEMENT rather
    # than the instrument - which is exactly why no amount of looking at the
    # line-up could ever have worked them out. See the MANUAL INFLUENCE
    # block in DEL 02m for what each one does to the plan.

    # ---- 🏠 FORCED ROOM -----------------------------------------------------
    def _room_forced(self):
        """'Small' / 'Medium' / 'Large' when the room is forced, else None."""
        try:
            return stage_overrides_clean(
                getattr(self, "_stage_manual", None)).get(STAGE_ROOM_KEY)
        except Exception:
            return None

    def _set_stage_room(self, value):
        """Force the room (Small / Medium / Large) or give it back (Auto)."""
        tbl = dict(self._stage_manual)
        if value in VSTAGE_ROOMS:
            tbl[STAGE_ROOM_KEY] = value
        else:
            tbl.pop(STAGE_ROOM_KEY, None)
        self._stage_manual = stage_overrides_clean(tbl)
        self._stage_manual_changed()

    def _sync_room_btn(self):
        """Label and colour of the 🏠 button (and the dialog's drop-down)."""
        forced = self._room_forced()
        btn = getattr(self, "room_btn", None)
        try:
            if btn is not None:
                if forced:
                    btn.config(text="🏠 Room: %s ✋" % forced,
                               bg=C_ACCENT, fg=C_BG)
                else:
                    btn.config(text="🏠 Room: Auto", bg=C_BTN, fg=C_BTN_FG)
        except Exception:
            pass
        try:
            var = getattr(self, "_manual_room_var", None)
            if var is not None:
                var.set(forced or "Auto")
        except Exception:
            pass

    def _sync_room_info(self, count=None):
        """v3.35: the header label after 'Selected Instruments (n)': the song's Virtual Stage room
        ('Room: Medium', with a hand mark when YOU forced it) and, when the song has SWAM parts,
        their own room ('SWAM: LARGE 2')."""
        lbl = getattr(self, "room_info_lbl", None)
        if lbl is None:
            return
        try:
            if not count:
                lbl.config(text="")
                return
            _rows, info = self._stage()
            room = (info or {}).get("room")
            text = ("\U0001f3e0 %s%s" % (room, " ✋" if self._room_forced() else "")) if room else ""
            sw = ((info or {}).get("swam") or {}).get("room")
            if sw:
                text += "\nSWAM: %s · %s" % (str(sw.get("size", "")).replace("one of the ", ""),
                                                 sw.get("material", ""))
            lbl.config(text=text)
        except Exception:
            try:
                lbl.config(text="")
            except Exception:
                pass

    def _info_text(self):
        """v3.36: everything that decides the numbers of THIS song, as plain text for a chat:
        line-up + counts, pairs, hand placements, the room(s), where each SWAM part stands and why,
        then the stage map's numbers and reasons."""
        import time as _t
        L = []
        L.append("EQ Cheat Sheet v%s - info for Claude - %s" % (APP_VERSION, _t.strftime("%Y-%m-%d %H:%M")))
        L.append("Song / variant: %s" % (self.current_variant or "-"))
        try:
            if self._pending_bits():
                L.append("NOTE: Update is waiting - this is the line-up the right panel shows (not the newer ticks).")
        except Exception:
            pass
        ids = self._panel_ids()
        if self._list_order() == "pick":
            ids = vocals_last(ids)
        pairs = clean_pairs(self._pairs_for_engines())
        swam = set(clean_swam(self._swam_for_engines()))
        sec = set(self._swam_sec_for_engines())
        rows, info = self._stage()
        L.append("")
        L.append("SELECTED INSTRUMENTS (%d)" % len(ids))
        for i in ids:
            bits = []
            n = self._count_of(i)
            if n > 1:
                bits.append("x%d" % n)
            if i in pairs:
                bits.append("PAIR %d prio %d" % (pairs[i][0], pairs[i][1]))
            if i in swam:
                bits.append("SWAM" + (" SECTION" if (i in sec or "section" in i) else ""))
                if i in SWAM_TURNS or i in self._swam_turns_now():
                    bits.append("copies take turns")
            g = SMARTEQ_GROUP.get(i)
            d = DEPTH.get(i)
            if g:
                bits.append("EQ " + str(g[0]).upper())
            if d:
                bits.append("depth " + DEPTH_SPEC.get(d[0], {}).get("label", str(d[0]).upper()))
            L.append("  - %s (%s)%s" % (_stage_name(i), i, ("   [" + ", ".join(bits) + "]") if bits else ""))
        groups = self._swam_hold_groups(set(ids), self._stage_effective_table())
        if groups:
            L.append("")
            L.append("PAIRS / SIBLINGS (priority in the SWAM room): " +
                     "; ".join(" + ".join(_stage_name(x) for x in g) for g in groups))
        man = self._stage_manual_table()
        if man:
            L.append("")
            L.append("HAND PLACEMENTS: " + json.dumps(man, ensure_ascii=False))
        L.append("")
        L.append("VIRTUAL STAGE ROOM: %s%s - %s" % (info.get("room"),
                                                     " (forced by hand)" if self._room_forced() else " (auto)",
                                                     info.get("room_why", "")))
        sw = (info or {}).get("swam")
        if sw:
            r = sw["room"]
            L.append("")
            L.append("SWAM ROOM (Room Type never changes): Room Sizes %s - Absorption %s - Mic %s" %
                     (r["size"], r["material"], r["mic"]))
            L.append("  " + r["why"])
            L.append("  Min. distance between sources: %.1f m; max distance here: %.1f m" %
                     (SWAM_MIN_SEP_M, SWAM_DIST_MAX_M * r["scale"]))
            for i in sw["ids"]:
                s = rows[i]["swam"]
                L.append("  %-22s %s" % (_stage_name(i), swam_text(s)))
                for mv in s.get("moved") or []:
                    L.append("      moved: " + mv)
        L.append("")
        try:
            segs, _i = self._stage_map_text()
            txt = "".join(b for _s, b in segs)
            cut = txt.find("Where it sits in the chain")
            L.append((txt[:cut] if cut > 0 else txt).rstrip())
        except Exception as e:
            L.append("(stage map not available: %s)" % e)
        return "\n".join(L) + "\n"

    def _copy_info(self):
        """v3.36: 📋 Copy info - put _info_text() on the clipboard."""
        try:
            text = self._info_text()
            self.root.clipboard_clear()
            self.root.clipboard_append(text)
            self.root.update()
            self._toast("Copied %d lines - paste it into the chat." % (text.count("\n")))
        except Exception as e:
            self._toast("Could not copy: %s" % e)

    def _kill_mediabay(self):
        """v3.35: end Steinberg's MediaBay process (so Cubase re-reads its preset folders)."""
        from tkinter import messagebox
        found = mediabay_pids()
        if found is None:
            messagebox.showinfo(APP_NAME, "Could not list the running programs, so nothing was ended.")
            return
        if not found:
            messagebox.showinfo(APP_NAME, "Steinberg MediaBay is not running - nothing to end.\n\n"
                                          "New presets will be read the next time Cubase starts.")
            return
        if cubase_running():
            if not messagebox.askyesno(
                    APP_NAME, "Cubase is still running.\n\nClose Cubase first, otherwise it may "
                              "complain or lose its preset list.\n\nEnd MediaBay anyway?",
                    default="no"):
                return
        gone, left, problem = kill_mediabay()
        if problem:
            messagebox.showinfo(APP_NAME, problem)
        elif left:
            messagebox.showinfo(APP_NAME, "Ended %d of %d MediaBay process(es); %d would not die "
                                          "(it may run as another user - end it in Task Manager)."
                                % (gone, len(found), left))
        else:
            self._toast("MediaBay ended (%s). Start Cubase again." %
                        ", ".join("PID %d" % p for p, _n in found))

    def _pick_room_menu(self):
        """The 🏠 button: a small menu under it."""
        menu = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=FONT_SMALL)
        cur = self._room_forced() or "Auto"
        self._room_menu_var = tk.StringVar(value=cur)    # kept alive on self
        for label in ("Auto",) + tuple(VSTAGE_ROOMS):
            menu.add_radiobutton(
                label=("%s  (the count decides)" % label) if label == "Auto"
                else label,
                value=label, variable=self._room_menu_var,
                command=lambda v=label: self._set_stage_room(v))
        btn = self.room_btn
        menu.tk_popup(btn.winfo_rootx(), btn.winfo_rooty() + btn.winfo_height())

    def _stage_manual_changed(self):
        """Hand placements go in AT ONCE.

        They are decisions made in a dialog, not ticks you are still
        thinking about, so there is nothing here for ⟳ Update to hold - the
        same reason the right-hand panel never waits either."""
        v = self._find_variant(self.current_variant)
        if v:
            v["stage_manual"] = dict(self._stage_manual)
            v["pairs"] = clean_pairs(self._pairs)
            v["swam"] = list(self._swam)
            v["swam_sec"] = list(self._swam_sec)
            self._persist_variants()
        self._stage_cache_key = None
        self._sync_room_btn()
        self._refresh_live_notes()
        self._refresh_summary()
        for attr, fill in (("_stage_map_txt", self._stage_map_fill),):
            w = getattr(self, attr, None)
            try:
                if w is not None and w.winfo_exists():
                    fill(w)
            except Exception:
                pass
        self._manual_sync()

    def _stage_manual_set(self, iid, field, value):
        """Write ONE field of one hand placement.

        "Opposite of" is written BOTH ways round on purpose: it is one fact
        about two channels, and a pairing only one of the two knows about is
        a pairing you cannot see from the other one's card."""
        blank = {"role": "auto", "side": "auto", "opposite": "", "sibling": ""}
        self._mark_focus(iid)
        o = dict(self._stage_manual.get(iid) or blank)
        if field in ("opposite", "sibling"):
            # "Opposite of" and "Sibling of" are the same KIND of fact (a
            # pairing, written both ways round), and a channel has only one
            # pairing at a time: setting one clears the other, here and on
            # the partner, or a stale half would keep pairing them.
            for fld in ("opposite", "sibling"):
                old = o.get(fld) or ""
                if old and (fld != field or old != value):
                    back = dict(self._stage_manual.get(old) or {})
                    if back.get(fld) == iid:
                        back[fld] = ""
                        self._stage_manual[old] = back
                    if fld != field:
                        o[fld] = ""
            o[field] = value
            if value:
                other = dict(self._stage_manual.get(value) or blank)
                other[field] = iid
                other["opposite" if field == "sibling" else "sibling"] = ""
                self._stage_manual[value] = other
        else:
            o[field] = value
        self._stage_manual[iid] = o
        self._stage_manual = stage_overrides_clean(self._stage_manual)
        self._stage_manual_changed()

    def _stage_manual_clear(self):
        """Give every channel back to the engine."""
        if not self._stage_manual:
            self._toast("Nothing is set by hand.")
            return
        self._stage_manual = {}
        self._stage_manual_changed()
        self._toast("Cleared — the engine has them all back (room too).")

    def _manual_sync(self):
        """Put the open dialog back in step with the table.

        The menus are NOT rebuilt: one of them is under the pointer at this
        very moment. Only the variables and the summary line move, which is
        what makes a pairing appear on the OTHER channel's row by itself."""
        win = getattr(self, "_manual_win", None)
        try:
            if win is None or not win.winfo_exists():
                return
        except Exception:
            return
        ov = self._stage_manual_table()
        self._sync_room_btn()
        for iid, vars_ in (getattr(self, "_manual_vars", {}) or {}).items():
            o = ov.get(iid) or {"role": "auto", "side": "auto", "opposite": "",
                                "sibling": ""}
            try:
                vars_["role"].set(self._MANUAL_ROLE_LABEL.get(o["role"], "Auto"))
                vars_["side"].set(self._MANUAL_SIDE_LABEL.get(o["side"], "Auto"))
                vars_["opposite"].set(_stage_name(o["opposite"])
                                      if o["opposite"] else "—")
                vars_["sibling"].set(_stage_name(o.get("sibling"))
                                     if o.get("sibling") else "—")
            except Exception:
                pass
        lbl = getattr(self, "_manual_summary_lbl", None)
        try:
            if lbl is not None and lbl.winfo_exists():
                lines = stage_manual_summary(ov)
                lbl.config(text="\n".join(lines) if lines else
                           "Nothing set by hand — the engine has the whole "
                           "stage.")
        except Exception:
            pass

    def _show_stage_manual(self):
        """✋ The three things about the arrangement this program cannot work
        out for itself."""
        top = tk.Toplevel(self.root)
        top.title("Virtual Stage — by hand")
        top.configure(bg=C_BG)
        top.resizable(True, True)
        top.transient(self.root)
        top.geometry("1100x860")
        self._manual_win = top
        self._manual_vars = {}
        self._MANUAL_ROLE_LABEL = {k: lbl for k, lbl, _d in STAGE_ROLES}
        self._MANUAL_SIDE_LABEL = {k: lbl for k, lbl in STAGE_SIDES}
        role_key = {lbl: k for k, lbl, _d in STAGE_ROLES}
        side_key = {lbl: k for k, lbl in STAGE_SIDES}

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="✋  Virtual Stage — by hand",
                 bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)",
                  bg=C_BTN, fg=C_BTN_FG,        # normal colour: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2", command=top.destroy).pack(side="right")
        tk.Button(hdr, text="Clear all",
                  bg=C_RESET_BTN, fg=C_BTN_FG,  # normal colour: C_RESET_BTN
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2",
                  command=self._stage_manual_clear).pack(side="right", padx=(0, 8))

        # v3.24: the way BACK to the stage map. This window used to be a dead end:
        # the map has a '✋ By hand…' button, but nothing led from here to the map.
        def _to_map():
            self._manual_win = None
            top.destroy()
            self._show_stage_map()
        tk.Button(hdr, text="🎪 Stage map…",
                  bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2", command=_to_map).pack(side="right", padx=(0, 8))

        # v3.24: the WHOLE page scrolls (explanation, room size and the table), not
        # just the table. Before, the wheel did nothing over the Room size row or the
        # explanation above it, because only the table was inside a scroll area.
        foot = tk.Frame(top, bg=C_BG2, padx=12, pady=6)
        foot.pack(side="bottom", fill="x")
        pg_wrap = tk.Frame(top, bg=C_BG)
        pg_wrap.pack(fill="both", expand=True)
        pg = tk.Canvas(pg_wrap, bg=C_BG, bd=0, highlightthickness=0)
        pg_vsb = tk.Scrollbar(pg_wrap, orient="vertical", command=pg.yview,
                              bg=C_BG2, troughcolor=C_BG,
                              activebackground=C_ACCENT)
        pg.configure(yscrollcommand=pg_vsb.set)
        pg_vsb.pack(side="right", fill="y")
        pg.pack(side="left", fill="both", expand=True)
        page = tk.Frame(pg, bg=C_BG)
        pg_win = pg.create_window((0, 0), window=page, anchor="nw")
        page.bind("<Configure>",
                  lambda e, c=pg: c.configure(scrollregion=c.bbox("all")))
        pg.bind("<Configure>",
                lambda e, c=pg, w=pg_win: c.itemconfig(w, width=e.width))

        def _page_wheel(e, _c=pg):
            _c.yview_scroll(-2 if e.delta > 0 else 2, "units")
            return "break"

        intro = tk.Frame(page, bg=C_BG2, padx=12, pady=8)
        intro.pack(fill="x")
        for text, colour in (
            ("WHAT IS THE STAGE?  A map of where every channel stands. Two "
             "numbers per channel: SIDE (left - right) and DISTANCE (near the "
             "listener - far back). The program fills in both for you from "
             "the line-up, and that is right for nearly all of it. The three "
             "columns below are only for what the line-up cannot tell it - "
             "what the parts DO in this song. Leave a row on Auto and the "
             "program decides.", C_FG),
            ("QUICK ANSWERS\n"
             "  - Two copies of the same part (2 x Guitar Rhythm, 2 x Cello) "
             "that matter EQUALLY: leave both on Auto (or give them the SAME "
             "Role). The program already puts one on Left and one on Right, "
             "equally far out - and if the family has exactly ONE other part "
             "(2 x Rhythm + 1 Chord), that one stands in the Centre between "
             "them. You do not need to set Side. Co-lead is only for when the "
             "pair should stand CLOSE to the middle, as a duet.\n"
             "  - Eight parts that are all equally important: give all eight "
             "the same Role (Auto, or Feature if you want them all forward). "
             "A Role only matters when two parts are DIFFERENT - if all are "
             "alike, none is favoured. Lead is for ONE part at a time; "
             "Co-lead is for exactly TWO (a duet).\n"
             "  - Two DIFFERENT channels that should simply mirror each other "
             "left/right, lead or not: set Siblings on one of them.\n"
             "  - Rule of thumb: same Role = equal focus. A higher Role "
             "(Lead > Co-lead > Feature > Support > ... > Texture) = closer to "
             "the listener, nearer the middle, and it keeps its place when "
             "two parts want the same spot.", C_ACCENT),
            ("•  Role — how much does this part matter RIGHT NOW? A piano "
             "riff can be the hook or the bed under it, and the channel looks "
             "identical both ways. Nine steps from LEAD (furthest forward, "
             "never gives way) through FEATURE, SUPPORT, DOUBLE and HARMONY "
             "to BED and TEXTURE (furthest back, first to yield). CO-LEAD is "
             "for equal partners that share the tune (a duet, two main "
             "instruments, or two copies #1/#2 of one part): they take "
             "opposite sides close to the middle. DOUBLE is drawn halfway "
             "in towards the middle.", C_FG_DIM),
            ("•  Side — for when there is a reason nothing in a mix can "
             "see: the video, the live line-up, or simply ‘not there, over "
             "here’. Left / Right only picks the SIDE; how far out it stands "
             "is still the program's number for that part.", C_FG_DIM),
            ("•  Siblings — a MATCHED STEREO PAIR. Pick the other channel and "
             "the two stand one on each side of Centre, as a mirror image "
             "(same distance out, same Distance). Role does not matter: "
             "siblings are equal by definition, so neither has to be the "
             "Lead. Set it on either one; it means both. If one of them is "
             "already tied down by hand (you gave it a Side) it stays and "
             "the other takes the mirror spot. Use it for two DIFFERENT "
             "channels that belong together (Violin + Viola, Piano Riff + "
             "Organ). Two copies of the SAME part pair themselves, so the "
             "copy rows have no Siblings menu.", C_FG_DIM),
            ("•  Opposite of — the looser version: two parts that ANSWER each "
             "other just must not end up on the same side (Guitar and Guitar "
             "R). One keeps its place, the other goes to the far side - not "
             "necessarily as far out, and Role still counts. Set it on "
             "either one of the two; it means both. A channel has either a "
             "Sibling OR an Opposite, not both.", C_FG_DIM),
            ("•  A part you have SEVERAL of (✖3 solo guitars) gets one row "
             "per copy - #1, #2, #3 - each with its own Role and Side, so "
             "one can be the lead and two can be support. The louder copies "
             "stand nearer the middle, and the Distance can differ per copy. "
             "ROOM below forces Small / Medium / Large for the whole song.",
             C_FG_DIM),
            ("Anything set here writes its own line on the channel, starting "
             "with a hand — so the sheet can always tell your numbers from "
             "its own, and those lines are never hidden with the why-lines. "
             "The drum kit and the channels this plug-in stays OFF are not "
             "listed: the kit is laid out as ONE object, and a position on a "
             "channel that is switched off would contradict the reason "
             "printed next to it.", C_ACCENT),
        ):
            tk.Label(intro, text=text, bg=C_BG2, fg=colour, font=FONT_SMALL,
                     wraplength=1050, justify="left",
                     anchor="w").pack(fill="x", pady=(0, 3))

        roomrow = tk.Frame(page, bg=C_BG2, padx=12, pady=4)
        roomrow.pack(fill="x", pady=(2, 0))
        tk.Label(roomrow, text="🏠 Room size for the whole song:", bg=C_BG2,
                 fg=C_FG, font=FONT_SMALL).pack(side="left")
        self._manual_room_var = tk.StringVar(value=self._room_forced() or "Auto")
        _rm = tk.OptionMenu(roomrow, self._manual_room_var, "Auto",
                            *VSTAGE_ROOMS, command=self._set_stage_room)
        _rm.config(bg=C_BG3, fg=C_FG, activebackground=C_BG3,
                   activeforeground=C_FG, highlightthickness=0, relief="flat",
                   font=FONT_SMALL, width=8, anchor="w", cursor="hand2",
                   indicatoron=0, padx=6, pady=1)
        _rm["menu"].config(bg=C_BG2, fg=C_FG, activebackground=C_BG3,
                           activeforeground=C_FG, font=FONT_SMALL)
        _rm.pack(side="left", padx=6)
        tk.Label(roomrow, text="Auto counts the places on the stage (1-5 "
                 "Small, 6-10 Medium, 11+ Large). Force one if the band "
                 "feels closer or bigger than the count says.",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL, wraplength=560,
                 justify="left", anchor="w").pack(side="left", padx=4)

        ids = [i for i in self._panel_ids() if stage_manual_ok(i)]
        body = tk.Frame(page, bg=C_BG)
        body.pack(fill="both", expand=True, padx=10, pady=(8, 0))
        if not ids:
            tk.Label(body, text="No channel in this song can be hand-placed "
                                "yet — tick some instruments first.",
                     bg=C_BG, fg=C_FG_DIM, font=FONT_NORMAL,
                     justify="left", anchor="w").pack(fill="x", pady=20)
        else:
            inner = body        # v3.24: no scroll area of its own - the page scrolls

            # The heading row is built AFTER the rows, from their real
            # widths: a Label of "width 12" and an OptionMenu of "width 12"
            # are not the same number of pixels, so headings written by
            # hand drift a little further left on every column.
            first_cells = []
            first_row = [None]

            names = {i: _stage_name(i) for i in ids}
            ov = self._stage_manual_table()

            def _menu(parent, var, values, cb, width):
                om = tk.OptionMenu(parent, var, *values, command=cb)
                om.config(bg=C_BG2, fg=C_FG, activebackground=C_BG3,
                          activeforeground=C_FG, highlightthickness=0,
                          relief="flat", font=FONT_SMALL, width=width,
                          anchor="w", cursor="hand2",
                          indicatoron=0, padx=6, pady=1)
                om["menu"].config(bg=C_BG2, fg=C_FG, activebackground=C_BG3,
                                  activeforeground=C_FG, font=FONT_SMALL)
                om.pack(side="left", padx=2)
                return om

            # A part you have several of gets ONE ROW PER COPY, named like the
            # part: "Single-String Lead (Low) #1, #2, #3".
            try:
                rows_now = self._stage()[0]
            except Exception:
                rows_now = {}
            entries = []
            _nc_of = {}
            for _i in ids:
                _nc = len((rows_now.get(_i) or {}).get("pos_pcts") or [])
                _nc_of[_i] = _nc
                if _nc > 1:
                    for _k in range(1, _nc + 1):
                        entries.append((stage_copy_key(_i, _k),
                                        "%s #%d" % (names[_i], _k), _i, _k))
                else:
                    entries.append((_i, names[_i], _i, 0))

            for key, shown, iid, kno in entries:
                o = ov.get(key) or {"role": "auto", "side": "auto",
                                    "opposite": ""}
                row = tk.Frame(inner, bg=C_BG)
                row.pack(fill="x", pady=1)
                if first_row[0] is None:
                    first_row[0] = row
                inst = next((x for x in EQ_DATA if x["id"] == iid), None)
                dot = tk.Label(row, text="●", bg=C_BG,
                               fg=(inst or {}).get("color", C_FG),
                               font=("Segoe UI", 9))
                dot.pack(side="left", padx=(4, 2))
                nm = tk.Label(row, text=shown, bg=C_BG, fg=C_FG,
                              font=FONT_SMALL, width=26, anchor="w")
                nm.pack(side="left", padx=(0, 2))
                if not first_cells:
                    first_cells = [(dot, ""), (nm, "Channel")]
                rv = tk.StringVar(
                    value=self._MANUAL_ROLE_LABEL.get(o["role"], "Auto"))
                sv = tk.StringVar(
                    value=self._MANUAL_SIDE_LABEL.get(o["side"], "Auto"))
                pv = tk.StringVar(
                    value=(names.get(o["opposite"]) or _stage_name(o["opposite"]))
                    if o["opposite"] else "—")
                bv = tk.StringVar(
                    value=(names.get(o.get("sibling")) or
                           _stage_name(o.get("sibling")))
                    if o.get("sibling") else "—")
                self._manual_vars[key] = {"role": rv, "side": sv,
                                          "opposite": pv, "sibling": bv}
                mr = _menu(row, rv, [lbl for _k, lbl, _d in STAGE_ROLES],
                           lambda val, i=key, m=role_key:
                               self._stage_manual_set(i, "role",
                                                      m.get(val, "auto")),
                           11)
                ms = _menu(row, sv, [lbl for _k, lbl in STAGE_SIDES],
                           lambda val, i=key, m=side_key:
                               self._stage_manual_set(i, "side",
                                                      m.get(val, "auto")),
                           9)
                if _nc_of.get(iid, 1) > 1:
                    mb = tk.Label(row, text="(pairs itself)",
                                  bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL,
                                  width=21, anchor="w")
                    mb.pack(side="left", padx=2)
                else:
                    sib_opts = ["—"] + [names[j] for j in ids
                                        if j != iid and _nc_of.get(j, 1) < 2]
                    sib_back = {names[j]: j for j in ids
                                if j != iid and _nc_of.get(j, 1) < 2}
                    mb = _menu(row, bv, sib_opts,
                               lambda val, i=iid, m=sib_back:
                                   self._stage_manual_set(i, "sibling",
                                                          m.get(val, "")),
                               21)
                if kno >= 2:
                    mp = tk.Label(row, text="(set on #1)", bg=C_BG,
                                  fg=C_FG_DIM, font=FONT_SMALL, width=21,
                                  anchor="w")
                    mp.pack(side="left", padx=2)
                else:
                    others = ["—"] + [names[j] for j in ids if j != iid]
                    back = {names[j]: j for j in ids if j != iid}
                    mp = _menu(row, pv, others,
                               lambda val, i=iid, m=back:
                                   self._stage_manual_set(i, "opposite",
                                                          m.get(val, "")),
                               21)
                if len(first_cells) == 2:
                    first_cells += [(mr, "Role"), (ms, "Side"),
                                    (mb, "Siblings (matched pair)"),
                                    (mp, "Opposite of")]

            if first_cells:
                inner.update_idletasks()
                head = tk.Frame(inner, bg=C_BG3)
                head.pack(fill="x", before=first_row[0])
                for w, txt in first_cells:
                    info = w.pack_info()
                    px = info.get("padx", 0)
                    try:
                        pad = sum(int(x) for x in px) if isinstance(
                            px, (tuple, list)) else int(px) * 2
                    except (TypeError, ValueError):
                        pad = 4
                    cell = tk.Frame(head, bg=C_BG3,
                                    width=w.winfo_reqwidth() + pad,
                                    height=18)
                    cell.pack_propagate(False)
                    cell.pack(side="left")
                    tk.Label(cell, text=txt, bg=C_BG3, fg=C_ACCENT,
                             font=("Segoe UI", 8, "bold"),
                             anchor="w").pack(fill="both", expand=True,
                                              padx=(2, 0))

            for _k, lbl, desc in STAGE_ROLES:
                line = tk.Frame(inner, bg=C_BG2)
                line.pack(fill="x", pady=(6, 0), padx=2)
                tk.Label(line, text=lbl, bg=C_BG2, fg=C_ACCENT,
                         font=("Segoe UI", 8, "bold"), width=10,
                         anchor="nw").pack(side="left", padx=(6, 0), pady=3)
                tk.Label(line, text=desc, bg=C_BG2, fg=C_FG_DIM,
                         font=FONT_SMALL, wraplength=680, justify="left",
                         anchor="w").pack(side="left", fill="x", expand=True,
                                          pady=3)
            tk.Label(inner,
                     text="A Role is also a LEVEL. Two parts of one family on "
                          "opposite sides (a chord guitar and a rhythm guitar) "
                          "only balance if the louder one stands nearer the "
                          "middle: Lead / Co-lead / Feature are the louder "
                          "parts, Support / Double / Bed / Harmony / Texture "
                          "the quieter ones. Equal Roles (or both on Auto) "
                          "keep the mirrored edges.",
                     bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL, wraplength=1020,
                     justify="left", anchor="w").pack(fill="x", padx=8,
                                                      pady=(8, 2))

        self._manual_summary_lbl = tk.Label(
            foot, text="", bg=C_BG2, fg=C_DIFF, font=FONT_SMALL,
            wraplength=1050, justify="left", anchor="w")
        self._manual_summary_lbl.pack(fill="x")
        self._manual_sync()
        # The wheel works over EVERYTHING on the page (the Room size row included).
        pg.bind("<MouseWheel>", _page_wheel)
        self._bind_wheel(page, _page_wheel)

        def _gone(_e=None):
            self._manual_win = None
            top.destroy()

        top.protocol("WM_DELETE_WINDOW", _gone)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", _gone)

    def _show_freq_bands(self):
        """Pop-up window: clickable frequency band bar with detailed info panel."""
        top = tk.Toplevel(self.root)
        top.title("Frequency Bands Explained")
        top.configure(bg=C_BG)
        top.geometry("860x620")
        top.resizable(True, True)
        top.transient(self.root)
        top.bind("<Escape>", lambda e: top.destroy())

        # Header
        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="📐  Frequency Bands Explained",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)",
                  bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        # ── Band button bar ───────────────────────────────────────────────────
        btn_row = tk.Frame(top, bg=C_BG2, pady=8, padx=10)
        btn_row.pack(fill="x")

        BAND_ORDER = ["sub", "bass", "lomid", "mid", "himid", "highs"]
        self._fb_buttons = {}
        self._fb_active  = tk.StringVar(value="")

        for key in BAND_ORDER:
            d = FREQ_BAND_DATA[key]
            btn = tk.Button(
                btn_row, text=f"{d['name']}\n{d['range']}",
                bg=C_BG3, fg=d["color"],
                activebackground=C_CARD, activeforeground=d["color"],
                font=("Segoe UI", 9, "bold"),
                relief="flat", bd=1, padx=10, pady=6,
                cursor="hand2",
                command=lambda k=key: self._on_freq_band_click(k, top),
            )
            btn.pack(side="left", expand=True, fill="x", padx=3)
            self._fb_buttons[key] = btn

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x")

        # ── Detail area (scrollable) ──────────────────────────────────────────
        outer = tk.Frame(top, bg=C_BG)
        outer.pack(fill="both", expand=True)

        canv = tk.Canvas(outer, bg=C_BG, bd=0, highlightthickness=0)
        vsb  = tk.Scrollbar(outer, orient="vertical", command=canv.yview,
                            bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canv.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canv.pack(side="left", fill="both", expand=True)

        self._fb_detail_canvas = canv
        self._fb_detail_inner  = tk.Frame(canv, bg=C_BG)
        win_id = canv.create_window((0, 0), window=self._fb_detail_inner, anchor="nw")

        def _cfg(e):  canv.configure(scrollregion=canv.bbox("all"))
        def _rsz(e):  canv.itemconfig(win_id, width=e.width)
        def _whl(e):  canv.yview_scroll(max(1, abs(round(e.delta / 40))) * (-1 if e.delta > 0 else 1), "units")

        self._fb_detail_inner.bind("<Configure>", _cfg)
        canv.bind("<Configure>", _rsz)
        canv.bind("<MouseWheel>", _whl)
        self._fb_detail_inner.bind("<MouseWheel>", _whl)
        # Store _whl so _on_freq_band_click can bind dynamic children to the same handler
        self._fb_whl = _whl

        # Intro text
        intro = tk.Frame(self._fb_detail_inner, bg=C_BG, padx=16, pady=14)
        intro.pack(fill="x")
        tk.Label(intro,
                 text="Click any frequency band above to see its characteristics, "
                      "what instruments live there, the danger zone, and how to use it "
                      "correctively, as enhancement, or creatively.",
                 bg=C_BG, fg=C_FG_DIM, font=FONT_NORMAL,
                 wraplength=800, justify="left").pack(anchor="w")

        # ── Additive vs. Subtractive section ─────────────────────────────────
        tk.Frame(self._fb_detail_inner, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(4, 0))

        add_sub_frame = tk.Frame(self._fb_detail_inner, bg=C_BG, padx=16, pady=10)
        add_sub_frame.pack(fill="x")

        tk.Label(add_sub_frame, text="Additive vs. Subtractive EQ",
                 bg=C_BG, fg=C_ACCENT, font=("Segoe UI", 11, "bold")).pack(anchor="w", pady=(0, 8))

        cols = tk.Frame(add_sub_frame, bg=C_BG)
        cols.pack(fill="x")

        for title, color, body in [
            ("Subtractive EQ  (cut first)",  C_CUT,
             "Cut unwanted frequencies before adding anything. Use a narrow Q (3–8) for "
             "surgical removal of specific resonances, hum, or boxiness. Preserves headroom "
             "and keeps the mix dynamic. The preferred approach of most professional engineers.\n\n"
             "Rule of thumb: subtract first — if you're stacking multiple large boosts, "
             "the real fix is likely at the source (mic placement, room treatment, a better take)."),
            ("Additive EQ  (boost to enhance)", C_BOOST,
             "Boost desired frequencies to shape tone and character. Use a wide Q (0.5–1.5) "
             "for musical, natural-sounding shelves and peaks. Narrow boosts sound honky and "
             "artificial — our ears identify them immediately.\n\n"
             "Both approaches are valid, but the golden rule is: subtract first, "
             "then add only what's needed."),
        ]:
            box = tk.Frame(cols, bg=C_CARD, padx=12, pady=10)
            box.pack(side="left", fill="both", expand=True, padx=(0, 8))
            tk.Label(box, text=title, bg=C_CARD, fg=color,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(0, 6))
            tk.Label(box, text=body, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=360, justify="left").pack(anchor="w")

        # ── 3 uses of EQ ─────────────────────────────────────────────────────
        tk.Frame(self._fb_detail_inner, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(4, 0))

        uses_frame = tk.Frame(self._fb_detail_inner, bg=C_BG, padx=16, pady=10)
        uses_frame.pack(fill="x")

        tk.Label(uses_frame, text="The 3 Main Uses of EQ",
                 bg=C_BG, fg=C_ACCENT, font=("Segoe UI", 11, "bold")).pack(anchor="w", pady=(0, 8))

        uses_cols = tk.Frame(uses_frame, bg=C_BG)
        uses_cols.pack(fill="x")

        USE_CASES = [
            ("Corrective",  C_CUT,
             "Remove problems baked in during recording: room resonances, "
             "low-frequency rumble, electrical hum, or a boxy mic placement. "
             "Most important for home studio producers where acoustic treatment "
             "can't solve every problem. Always correct before enhancing."),
            ("Enhancement", C_BOOST,
             "Boost pleasing characteristics to sculpt tone. Adding air to a vocal, "
             "bringing out the attack of a snare, adding warmth to an acoustic guitar. "
             "Keep boosts wide (low Q) and subtle — 1–3 dB is usually sufficient."),
            ("Creative",    C_CHAR,
             "Extreme filtering used as an effect. The classic 'telephone' or lo-fi "
             "vocal sound is created by aggressively high-passing and low-passing so only "
             "a narrow midrange band survives. Bandpass filters on synths. "
             "Parallel distorted EQ sends for grit and weight."),
        ]
        for title, color, body in USE_CASES:
            box = tk.Frame(uses_cols, bg=C_CARD, padx=12, pady=10)
            box.pack(side="left", fill="both", expand=True, padx=(0, 8))
            tk.Label(box, text=title, bg=C_CARD, fg=color,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(0, 6))
            tk.Label(box, text=body, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=220, justify="left").pack(anchor="w")

        # Placeholder for band detail (filled by _on_freq_band_click)
        self._fb_band_detail_frame = tk.Frame(self._fb_detail_inner, bg=C_BG)
        self._fb_band_detail_frame.pack(fill="x")

        # ── 5 Essential EQ Tips ───────────────────────────────────────────────
        tk.Frame(self._fb_detail_inner, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(4, 0))

        tips_frame = tk.Frame(self._fb_detail_inner, bg=C_BG, padx=16, pady=10)
        tips_frame.pack(fill="x")

        tk.Label(tips_frame, text="5 Essential EQ Mixing Tips",
                 bg=C_BG, fg=C_ACCENT, font=("Segoe UI", 11, "bold")).pack(anchor="w", pady=(0, 8))

        EQ_TIPS = [
            ("1. Cut Narrow, Boost Wide",
             "For surgical cuts (removing a resonance, boxiness, or hum), use a narrow Q (3–8). "
             "This removes the problem without touching surrounding frequencies you want to keep.\n\n"
             "For boosts, use a wide Q (0.5–1.5). Narrow boosts sound honky and unnatural — "
             "our ears identify them immediately because they have no real-world acoustic equivalent. "
             "Broad tonal shaping sounds musical because that is how real instruments and rooms behave.",
             C_BOOST),
            ("2. Carve Space — Complementary EQ",
             "Every element needs its own home in the frequency spectrum. When two instruments "
             "compete for the same range — lead vocal and guitar both fighting for 3–4 kHz — "
             "neither wins.\n\n"
             "The fix: boost the frequency on the element you want to prioritize, "
             "cut it on the competing element. Boost 3 kHz on the vocal; cut 3 kHz on the guitar. "
             "Both keep their character but stop fighting.",
             C_CHAR),
            ("3. High-Pass Filters — Use Carefully",
             "High-pass every track that isn't meant to carry low-frequency energy — which is "
             "almost everything except kick, bass, and possibly piano or synth pads.\n\n"
             "The danger: filtering too aggressively. Setting the cutoff too high on instruments "
             "that carry meaningful low-mid energy strips warmth and body. "
             "Always listen to the HPF in the full mix, not soloed — solo always sounds too thin.",
             C_CUT),
            ("4. Don't Mix With Your Eyes",
             "Spectrum analyzers and EQ curve displays are useful for identifying problem "
             "frequencies, but they tell you what is happening — not whether it sounds good.\n\n"
             "Your ears are the final authority. Use reference tracks. "
             "Take ear breaks every 45–60 minutes. If something looks enormous on screen "
             "but sounds right in the mix, trust the mix.",
             C_FG_DIM),
            ("5. Mix in Context — Never Solo",
             "EQing every track in isolation produces a collection of beautifully tuned "
             "individual sounds that don't work together. Each was tuned to sound great alone, "
             "not to fit the arrangement.\n\n"
             "A rhythm guitar that sounds thin and unnatural soloed — rolled off at both ends — "
             "may sit perfectly in the full mix. Solve problems in the full mix. "
             "Solo only to locate a specific resonance, then return to the full mix to evaluate.",
             C_ACCENT),
        ]

        for i, (title, body, color) in enumerate(EQ_TIPS):
            tip_box = tk.Frame(tips_frame, bg=C_CARD, padx=12, pady=10)
            tip_box.pack(fill="x", pady=(0, 6))
            tk.Label(tip_box, text=title, bg=C_CARD, fg=color,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(0, 4))
            tk.Label(tip_box, text=body, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=780, justify="left").pack(anchor="w")

        # ── Mastering EQ note ─────────────────────────────────────────────────
        tk.Frame(self._fb_detail_inner, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(4, 0))

        mastering_frame = tk.Frame(self._fb_detail_inner, bg=C_BG, padx=16, pady=10)
        mastering_frame.pack(fill="x")

        tk.Label(mastering_frame, text="EQ for Mastering vs. Mixing",
                 bg=C_BG, fg=C_ACCENT, font=("Segoe UI", 11, "bold")).pack(anchor="w", pady=(0, 8))

        mastering_cols = tk.Frame(mastering_frame, bg=C_BG)
        mastering_cols.pack(fill="x")

        for title, color, body in [
            ("Mixing EQ", C_BOOST,
             "Works on individual tracks. Typical moves: 4–8 dB cuts and boosts or more. "
             "Narrow surgical cuts for resonances. Wide boosts to sculpt character. "
             "High-pass filters on most tracks. EQ before or after compression depending on goal."),
            ("Mastering EQ", C_CHAR,
             "Works on the stereo mixdown — every change affects everything simultaneously. "
             "Typical moves: 0.5–1.5 dB, sometimes less. Always wide Q. "
             "1 dB at 80 Hz in mastering changes kick, bass, piano, and synths all at once. "
             "Prefer linear-phase EQ to avoid phase artefacts in the stereo image."),
        ]:
            box = tk.Frame(mastering_cols, bg=C_CARD, padx=12, pady=10)
            box.pack(side="left", fill="both", expand=True, padx=(0, 8))
            tk.Label(box, text=title, bg=C_CARD, fg=color,
                     font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(0, 6))
            tk.Label(box, text=body, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=360, justify="left").pack(anchor="w")

        # Bind wheel to all static children already in the window
        self._bind_wheel_recursive(self._fb_detail_inner, _whl)

    def _bind_wheel_recursive(self, widget, fn):
        """Bind MouseWheel to widget and all its descendants."""
        try:
            widget.bind("<MouseWheel>", fn)
        except Exception:
            pass
        for child in widget.winfo_children():
            self._bind_wheel_recursive(child, fn)

    def _on_freq_band_click(self, key, top):
        """Show detail for the clicked frequency band."""
        # Highlight active button
        for k, btn in self._fb_buttons.items():
            color = FREQ_BAND_DATA[k]["color"]
            if k == key:
                btn.configure(bg=C_CARD_SEL, relief="sunken")
            else:
                btn.configure(bg=C_BG3, relief="flat")

        # Clear and rebuild the band detail frame
        for w in self._fb_band_detail_frame.winfo_children():
            w.destroy()

        d = FREQ_BAND_DATA[key]
        f = self._fb_band_detail_frame
        color = d["color"]

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", padx=16, pady=(4, 0))

        # Name + range
        title_row = tk.Frame(f, bg=C_BG, padx=16, pady=10)
        title_row.pack(fill="x")
        tk.Label(title_row, text=d["name"], bg=C_BG, fg=color,
                 font=("Segoe UI", 14, "bold")).pack(side="left")
        tk.Label(title_row, text=f"  {d['range']}", bg=C_BG, fg=C_FG_DIM,
                 font=("Consolas", 11)).pack(side="left")

        # 3-column: Characteristics | Instruments | Danger
        row1 = tk.Frame(f, bg=C_BG, padx=16)
        row1.pack(fill="x", pady=(0, 10))

        sections = [
            ("Characteristics", d["char"]),
            ("Instruments in this range", "\n".join(f"• {i}" for i in d["instruments"])),
            ("⚠  Danger zone", d["danger"]),
        ]
        for title, body in sections:
            col = tk.Frame(row1, bg=C_CARD, padx=10, pady=10)
            col.pack(side="left", fill="both", expand=True, padx=(0, 8))
            hc = color if "Danger" in title else C_FG_DIM
            tk.Label(col, text=title, bg=C_CARD, fg=hc,
                     font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(0, 5))
            tk.Label(col, text=body, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=230, justify="left").pack(anchor="w")

        # 3-column: Corrective | Enhancement | Creative
        row2 = tk.Frame(f, bg=C_BG, padx=16)
        row2.pack(fill="x", pady=(0, 10))

        use_sections = [
            ("Corrective",  C_CUT,   d["corrective"]),
            ("Enhancement", C_BOOST, d["enhancement"]),
            ("Creative",    C_CHAR,  d["creative"]),
        ]
        for title, uc_color, items in use_sections:
            col = tk.Frame(row2, bg=C_CARD, padx=10, pady=10)
            col.pack(side="left", fill="both", expand=True, padx=(0, 8))
            tk.Label(col, text=title, bg=C_CARD, fg=uc_color,
                     font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(0, 5))
            body = "\n".join(f"• {item}" for item in items) if items else "—"
            tk.Label(col, text=body, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=230, justify="left").pack(anchor="w")

        # Additive / Subtractive notes for this band
        note_row = tk.Frame(f, bg=C_BG, padx=16)
        note_row.pack(fill="x", pady=(0, 16))

        for label, note_color, note_text in [
            ("Additive EQ here:",    C_BOOST, d["additive_note"]),
            ("Subtractive EQ here:", C_CUT,   d["subtractive_note"]),
        ]:
            nb = tk.Frame(note_row, bg=C_BG2, padx=10, pady=6)
            nb.pack(side="left", fill="both", expand=True, padx=(0, 8))
            tk.Label(nb, text=label, bg=C_BG2, fg=note_color,
                     font=("Segoe UI", 9, "bold")).pack(anchor="w")
            tk.Label(nb, text=note_text, bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=380, justify="left").pack(anchor="w")

        # Bind wheel to all newly created children
        self._bind_wheel_recursive(self._fb_band_detail_frame, self._fb_whl)

        # Scroll so the band detail header is visible (not absolute bottom)
        def _scroll_to_detail():
            self._fb_detail_canvas.update_idletasks()
            # Get y position of the band detail frame relative to the inner frame
            try:
                inner = self._fb_detail_inner
                frame = self._fb_band_detail_frame
                inner_h = inner.winfo_height()
                frame_y = frame.winfo_y()
                if inner_h > 0:
                    frac = frame_y / inner_h
                    self._fb_detail_canvas.yview_moveto(max(0.0, frac - 0.02))
            except Exception:
                pass
        self._fb_detail_canvas.after(60, _scroll_to_detail)

    # ---- HELP ---------------------------------------------------------------

    # ---- "Explain" topics (short 'how it works' reads) ----------------------

    def _explain_data(self):
        """Return {key: (title, [(style, text), ...])} for the Explain menu.
        Styles reuse the Help tags: h1 / h2 / body / code / tip / warn."""
        return {
            "defaults": ("Δ Defaults — why most of the sheet is grey", [
                ("h1", "Read the difference, not the whole answer\n"),
                ("body", "Nine plug-ins on a channel, and most of their knobs "
                 "say exactly the same thing in every song you will ever mix. "
                 "So each instrument gets a DEFAULT — what it is set to when "
                 "there is ONE of it, in the kind of song it usually turns up "
                 "in. Save that in the plug-in's own preset. From then on this "
                 "sheet only has to tell you what THIS song does "
                 "differently.\n\n"),
                ("code", "  grey          →  your preset already did it. Do not open the plug-in.\n"
                         "  in colour, Δ  →  this song is the exception. Dial this one.\n\n"),
                ("h2", "Where a default comes from\n"),
                ("body", "One band. An instrument standing alone on a stage "
                 "would get a small room and a centre position, and that is a "
                 "song nobody mixes — so every default is read off THE DEFAULT "
                 "BAND: lead vocal, backing vocals, chord guitar, rhythm "
                 "guitar, bass, bass X, kick, snare, hi-hat, tom, cymbal, "
                 "piano, organ.\n\n"),
                ("body", "Anything that is not in that band gets its default "
                 "by standing IN it, one of it. The ride is placed beside the "
                 "band's hi-hat, the percussion beside its kit, a cello in "
                 "front of its guitars — which is the context each of them "
                 "actually turns up in.\n\n"),
                ("body", "The solo guitar is a guest on purpose. A third "
                 "guitar widens the whole guitar row: with it in the band the "
                 "chord and rhythm guitars move from R65/L65 out to R75/L75, "
                 "and a default should not depend on whether you happened to "
                 "record a solo. Same for the percussion. (The ride used to push "
                 "the hi-hat from R20 to R25 as well; since v3.23 the stage "
                 "treats hi-hat and ride as taking turns, so it no longer does.)\n\n"),
                ("h2", "Three rooms, three sets\n"),
                ("body", "The room is a SONG setting, so one set of defaults "
                 "could only ever be right in one size of room. There are "
                 "three: a Small band (a singer, a guitar, a piano and the "
                 "kit), the Medium band above, and a Large one — the same band "
                 "produced, with a solo guitar, a second keyboard, brass and "
                 "strings. The sheet measures this song against the set for "
                 "the room it is actually in, so Room is grey until the song "
                 "sits genuinely between two rooms.\n\n"),
                ("h2", "How the room is measured\n"),
                ("body", "In PLACES ON THE STAGE, not in channels — a drum kit "
                 "takes up one place whether it has one tom or four, no "
                 "cymbals or seven.\n\n"),
                ("code", "  the whole kit (+ shaker/tambourine)   1 place\n"
                         "  hand drums (congas, bongos, taiko)    its own — a second player\n"
                         "  every other instrument                1 each, and ✖2 really is 2\n"
                         "  a section or a bed                    2 — one channel, not one person\n\n"
                         "  1–5 places  Small     6–10  Medium     11+  Large\n\n"),
                ("h2", "The other way: a vote\n"),
                ("body", "View ▸ Defaults can take the numbers from a VOTE "
                 "over ten built-in songs instead, or over your own Song "
                 "Variants. Each FIELD votes on its own — Position, Distance "
                 "and Room are three answers, not one — and any field the "
                 "songs did not agree on is printed with its score. Worth a "
                 "look for an instrument your band never contains.\n\n"),
                ("h2", "What stays in colour\n"),
                ("body", "Virtual Stage, mostly — Position and Distance are "
                 "the numbers that genuinely move with the line-up, which is "
                 "also why its presets are named after the numbers they hold. Then the ducks "
                 "whose side-chain source is not in this song, and the ✖N box, "
                 "which only appears when you have raised a count. Everything "
                 "else — the low cut, the Omega and Corridor presets, the "
                 "compressor, the smart:EQ tier, SubMass, the reverb depth — "
                 "does not depend on the line-up at all, so once its preset is "
                 "saved it is grey for good.\n\n"),
                ("h2", "The Defaults window\n"),
                ("body", "View ▸ 📐 Defaults, or the button on the Filter row. "
                 "It lists what every preset should hold, prints the vote "
                 "beside any field the reference songs did not agree on, and "
                 "has a Copy-all so it can sit on the second screen while you "
                 "build the presets. It can vote over your own Song Variants "
                 "instead of the built-in songs.\n\n"),
                ("warn", "A field the vote only just won (\"R25 won 1 of 2\") "
                 "is a coin toss dressed as an answer. Those are printed with "
                 "their score for exactly that reason — trust the unanimous "
                 "ones, dial the close ones by ear.\n"),
                ("tip", "Δ changes the COLOURS and nothing else. Every number "
                 "the program has always printed is still on the screen — turn "
                 "Δ off on the Filter row and the old view comes straight "
                 "back.\n"),
            ]),
            "multiples": ("One or several of the same instrument", [
                ("h1", "Does it matter whether I have one or two?\n"),
                ("body", "It matters more than almost anything else you can change. Set the count with the "
                 "'how many' box on any instrument card (or in the Song Variants tab) and a ✖N box appears "
                 "with the whole plan: level, pan, tone split, low cut, reverb and the bus.\n\n"),
                ("h2", "The one fact that explains everything\n"),
                ("body", "Two tracks of the same part do NOT sound like one part played louder — unless you "
                 "made them identical, in which case that is exactly what they are.\n\n"),
                ("code", "  Same audio, copied      →  +6 dB, zero width. A volume knob.\n"
                         "  Two separate takes      →  +3 dB, real width from the differences.\n"
                         "  N separate takes        →  +10·log10(N) dB in their shared band.\n\n"),
                ("body", "So three chord guitars are not 'three guitars'. They are a 4.8 dB boost across "
                 "200 Hz–4 kHz that nobody asked for, sitting on top of the vocal. The program prints that "
                 "number for whatever count you set, and tells you to pull each copy down by it.\n\n"),
                ("h2", "What the ✖N box actually gives you\n"),
                ("body", "A PAN LADDER (#1 L85, #2 Centre, #3 R85 — computed for your count), a TONE SPLIT "
                 "so each copy owns a different band, a LOW-CUT LADDER so only ONE copy keeps the low end, a "
                 "reverb ladder so they sit at different depths, and the bus verdict — because two channels of "
                 "one instrument have earned a bus, one glue comp and one smart:EQ slot.\n\n"),
                ("h2", "Widening vs layering — not the same thing\n"),
                ("body", "Guitars, backing vocals, pads and plucks WIDEN: spread them apart and differentiate "
                 "them. Bass, kick, lead vocal and low horns LAYER: they must stay centred and split the "
                 "frequency range instead, because panning them apart just breaks the centre of the mix. Toms, "
                 "percussion and cymbals SPREAD by physical position. Each instrument's card knows which it is.\n\n"),
                ("warn", "The trap: two identical bass tracks, or two unaligned kick samples, CANCEL around "
                 "60–100 Hz. The low end gets quieter the more you add, and no EQ fixes it — only nudging one "
                 "of them in time does.\n"),
            ]),
            "hearing": ("Mixing when you cannot trust your ears", [
                ("h1", "The program can do the listening you cannot\n"),
                ("body", "Fill in Help ▸ 🦻 Hearing profile — one line per octave band, saying whether you can "
                 "judge that range by ear. Everything else follows from it, and until you do, nothing changes.\n\n"),
                ("h2", "What changes once it is filled in\n"),
                ("body", "Every band on every card gets a mark: ✔ judge by ear · ◐ set the number then check · "
                 "⛔ use the number and leave it. Boosts inside a range you cannot judge are CAPPED at +2 dB "
                 "(+4 dB when you are only unsure), and 'TRY / depends on the track' bands in those ranges stop "
                 "being a question — the program picks the value and says so.\n\n"),
                ("h2", "Why the cap is the whole point\n"),
                ("warn", "If your loss at 8 kHz is 20 dB, then boosting the cymbals until you can hear them "
                 "means you have added about 20 dB of cymbals for everyone else. It sounds right to you and "
                 "brittle and painful to them. That single mechanism is behind most 'my mixes sound harsh on "
                 "other systems' problems, and it cannot be solved by listening harder.\n\n"),
                ("body", "The cure is not to guess better. It is to move those decisions out of the listening "
                 "domain entirely: numbers from this program, meters for level and loudness, an analyser "
                 "against a reference track, and plug-ins that decide from analysis — smart:EQ for masking, "
                 "smart:comp for level, Bandwidth's presets instead of a curve you dial by ear.\n\n"),
                ("h2", "What it does NOT do\n"),
                ("body", "It does not make anything audible again and it is not a hearing test. It stops you "
                 "making decisions in ranges you cannot check — a different problem, and a solvable one. "
                 "Open 🦻 My rules for your own generated rule sheet.\n"),
            ]),
            "roadmap": ("Buses & the Roadmap — what feeds what", [
                ("h1", "The Roadmap: your routing tree\n"),
                ("body", "The Channel Plan tells you what to put ON a channel. The Roadmap (🗺 button in the "
                 "right panel, or Generate ▸ Roadmap) tells you where that channel GOES — channel → sub-bus → "
                 "section bus → master — and gives you a numbered build order for Cubase.\n\n"),
                ("h2", "The drum tree\n"),
                ("code", "  Kick + Snare                    →  Drums: Front\n"
                         "  Toms                            →  Drums: Toms\n"
                         "  Drums: Toms + Hi-Hat + Ride     →  Drums: Mid\n"
                         "  Cymbals                         →  Drums: Cymbals\n"
                         "  Drums: Cymbals + Percussion     →  Drums: Back\n"
                         "  Front + Mid + Back              →  Drums: All\n\n"),
                ("body", "Two payoffs. First, one fader per section: the drums are too loud, so you pull "
                 "Drums: All — not eight faders, and the internal balance you spent an hour on survives. "
                 "Second, shared plug-ins: if every tom gets the same treatment, the tom plug-ins live ONCE on "
                 "Drums: Toms instead of once per tom channel. Less CPU, one place to tweak, and they cannot "
                 "drift out of sync with each other.\n\n"),
                ("h2", "The rest of the tree\n"),
                ("body", "Bass parts (root bass, bass loop/riff, double bass) share a Bass bus as soon as there "
                 "is more than one — one shared low end, one shared duck against the kick. All guitars share a "
                 "Guitars bus. The lead vocal keeps its own path; backing vocals and choir/vocal pads share "
                 "Vocals: Back. Keys, winds and strings each get a Background bus, and those three feed "
                 "Background: All — the fader that pushes the whole arrangement behind the vocal.\n\n"),
                ("warn", "A bus has to EARN its place. The Roadmap only creates one when at least two channels "
                 "sit under it (a count of 3 toms counts as three). One lonely tom is just a tom, so the bus is "
                 "dissolved into its parent automatically.\n\n"),
                ("h2", "What goes on a bus\n"),
                ("tip", "  • Glue compressor — 2:1, only 1–3 dB of gain reduction.\n"
                 "  • smart:EQ — this is the group slot. One bus = one of your 10.\n"
                 "  • The section fader, and a shared reverb send if the section shares a depth.\n\n"),
                ("warn", "NOT on a bus: the low cut. Lowtility does the high-pass ONCE, on the channel. Two "
                 "high-passes in series shift the corner up and smear the low end.\n\n"),
                ("h2", "Why this is the same problem as the 10-slot limit\n"),
                ("body", "A bus is exactly what carries one smart:EQ instance, so the routing tree and the "
                 "group plan are the same picture. 30 channels can be 8 buses — that is what makes the 10-slot "
                 "limit survivable. When the plan still needs more than 10, the 🎯 smart:EQ Groups window "
                 "colour-codes which buses belong together and merges the cheapest ones for you.\n"),
            ]),
            "insert_send": ("Insert vs. Send (reverb & delay)", [
                ("h1", "Insert vs. Send — what's the difference?\n"),
                ("body", "An INSERT sits directly in the channel's signal path: the WHOLE channel goes through "
                 "it. That's what you want for EQ, low-cut, compression, saturation, Trackspacer — things that "
                 "shape the actual signal in place.\n\n"),
                ("body", "A SEND routes a COPY of the channel to a separate FX (aux) channel that holds the "
                 "effect. The dry track stays untouched on its own channel; the FX channel adds the wet part, "
                 "mixed back in. Reverb and delay are normally used this way.\n\n"),
                ("h2", "Why reverb / delay belong on a send\n"),
                ("tip", "  • ONE reverb, MANY tracks → they all sit in the SAME room and glue together.\n"
                 "  • Depth is set by the SEND amount per track (more send = further back).\n"
                 "  • The dry signal stays 100% clean; only ambience is added in parallel.\n"
                 "  • Far less CPU than a reverb on every channel.\n\n"),
                ("h2", "Same as an insert, just different result?\n"),
                ("body", "For ONE track a 20% insert-reverb sounds close to a send. The difference shows in the "
                 "whole mix: insert-per-track = every part in its own slightly different room (can sound "
                 "disjointed, more CPU); send = one shared, cohesive space with easy per-track depth control, "
                 "and the dry stays pristine.\n\n"),
                ("warn", "Rule of thumb: EQ / Lowtility / Kirchhoff / smart:EQ / Trackspacer → INSERT. "
                 "Reverb / Delay → SEND.\n\n"),
                ("body", "See the 'Reverb depth buses' topic for the exact step-by-step (and how to load the "
                 "Near / Mid / Far / Front presets onto the FX channels).\n"),
            ]),
            "reverb_buses": ("Reverb depth buses — Near / Mid / Far / Front", [
                ("h1", "Setting up the depth (reverb) buses\n"),
                ("body", "Instead of a reverb per track, you make a FEW FX channels — one per depth tier — and "
                 "send each track to the one that matches its depth. That's the most efficient, best-sounding "
                 "way, and it's exactly what the 🌫 Reverb Groups button and the Channel Plan map out for you.\n\n"),
                ("h2", "Step by step (Cubase)\n"),
                ("tip", "  1. Add an FX/Effect track and put smart:reverb on it. Set its MIX to 100% wet (it's a\n"
                 "     send — the dry comes from the original track).\n"
                 "  2. Repeat for each depth you need: typically Near, Mid, Far (and a Front bus for the very\n"
                 "     up-front lead). 2–3 buses cover a whole mix.\n"
                 "  3. On every instrument, open Sends, choose the FX channel that matches its depth tier\n"
                 "     (the Channel Plan / Reverb Groups tells you which), and raise the send: a little for\n"
                 "     Near, more for Far. Kick & bass stay DRY (no send).\n\n"),
                ("h2", "How do I get the Near / Mid / Far / Front PRESET in there?\n"),
                ("body", "The program generates one smart:reverb preset per tier with the right "
                 "Distance/Size/Width already set:\n\n"),
                ("tip", "  1. Menu: Generate ▸ Options… → tick 'smart:reverb: one preset per tier (buses)'.\n"
                 "  2. Menu: Generate ▸ '🌫 smart:reverb presets: All' (or 'Selected'). This writes files like\n"
                 "     Reverb-FRONT / Reverb-NEAR / Reverb-MID / Reverb-FAR into your smart:reverb preset\n"
                 "     folder (Documents\\VST3 Presets\\sonible\\smartReverb2 by default; set via File ▸ Set\n"
                 "     smart:reverb preset folder…). A text recipe + backups also go to Helpfiles\\Presets.\n"
                 "  3. In Cubase, on each FX channel's smart:reverb, open the preset selector at the TOP of the\n"
                 "     plugin (Cubase's preset field, by the sidechain button) and load the matching tier preset\n"
                 "     — FRONT on the Front bus, NEAR on the Near bus, and so on. Keep Mix at 100% wet.\n\n"),
                ("body", "First time you generate, smart:reverb needs ONE preset YOU made by ear as a SEED "
                 "(name it with 'lead' or 'vocal'); the program copies its learned room and only changes "
                 "Distance/Size/Width per tier. It never invents the AI state.\n\n"),
                ("warn", "Don't use smart:reverb's INTERNAL group with generated presets (they're clones — the "
                 "group can't tell them apart). You don't need it: the depth BUSES above do the job.\n"),
            ]),
            "smarteq": ("smart:EQ groups — Front / Mid / Back", [
                ("h1", "smart:EQ groups (cross-channel unmasking)\n"),
                ("body", "smart:EQ 4's group feature listens across channels and carves space automatically — "
                 "but it needs to know WHO WINS when two parts overlap. That's a priority, and the program "
                 "gives it to you as a tier:\n\n"),
                ("tip", "  • ▲ FRONT — high priority; stays present, others yield to it (lead vocal, kick, snare…).\n"
                 "  • ■ MID   — supporting layer.\n"
                 "  • ▼ BACK  — low priority; carved to make room (pads, beds, background).\n\n"),
                ("body", "Add smart:EQ MANUALLY on the track (don't load a generated preset — a clone drags the "
                 "seed's name and EQ onto every track). Run its Learn, put the competing tracks in one group, "
                 "and rank them Front → Back as the cards say. smart:EQ has a 10-channel group limit — the "
                 "🎯 smart:EQ Groups popup shows a sub-bus plan to stay under it.\n\n"),
                ("warn", "This is SPECTRAL (frequency) unmasking. Two parts clashing in TIME (kick + bass at "
                 "60–100 Hz) need DUCKING instead — see that topic.\n"),
            ]),
            "duck": ("Ducking — start gentle", [
                ("h1", "Ducking (Trackspacer / Kickstart)\n"),
                ("body", "Ducking makes parts take turns in TIME: the louder part briefly pushes the other down "
                 "so both stay clear. The program shows a 🦆 footnote naming what to side-chain to and the "
                 "settings, for the two tools you own.\n\n"),
                ("tip", "  • Trackspacer (Wavesfactory) — a reactive EQ on the YIELDING track; feed the dominant\n"
                 "    part to its side-chain. Pull its High-Cut to ~150 Hz for kick↔bass so only the lows duck.\n"
                 "  • Kickstart — a tempo-synced volume duck; only for an on-beat kick.\n\n"),
                ("warn", "START GENTLE. The Amounts are intentionally LOW (~10–20%). Raise only until the lead "
                 "JUST pokes through. If the ducked part DISAPPEARS or pumps, you went too far — pull it back. "
                 "30–40% will usually swallow the part whole.\n\n"),
                ("h2", "No source, no duck\n"),
                ("body", "A duck needs a SOURCE. Once you have ticked the instruments in your song, the program "
                 "hides every duck whose source is missing: no kick in the song → no 'duck the bass under the "
                 "kick' anywhere (the card says so in a dim line instead), no lead vocal → no vocal ducks. "
                 "With nothing ticked at all, the cards go back to reference mode and show every duck.\n"),
            ]),
            "midside": ("Mid/Side EQ in Kirchhoff", [
                ("h1", "Mid/Side — air, width & clarity by the numbers\n"),
                ("body", "Each Kirchhoff band can work on part of the stereo image instead of the whole signal: "
                 "Mid (the centre L+R share) or Side (the wide L−R difference).\n\n"),
                ("tip", "  • AIR / SPACE   → on SIDE, a high-shelf above ~10 kHz, +2…+3 dB.\n"
                 "  • NO PORRIDGE   → on MID, cut −3…−4 dB at 200–500 Hz (clears the centre, keeps width).\n"
                 "  • TIGHT LOW END → on SIDE, high-pass ~100–150 Hz (forces lows to mono).\n\n"),
                ("body", "The Selected-Instruments view prints a ready-made '🎛 Kirchhoff M/S' line per track. "
                 "Mono/centre sources (kick, bass, lead vocal) have little Side, so there you just work in "
                 "Stereo or Mid and keep the lows mono.\n"),
            ]),
            "channelplan": ("Channel Plan, stems & the inserts map", [
                ("h1", "The 📐 Channel Plan view\n"),
                ("body", "The default right-panel view puts everything you need to ROUTE a song in one place: "
                 "each channel's smart:EQ priority, reverb depth, duck source and pan together. Low-cut and the "
                 "Kirchhoff EQ table are per-channel and left out here (use the 📋 Instruments view for those).\n\n"),
                ("h2", "🔗 Shareable stems\n"),
                ("body", "Channels that share the SAME smart:EQ group AND the SAME reverb depth get a coloured "
                 "◆ badge. Those can be bussed together: one smart:EQ sub-bus + one reverb send covers the whole "
                 "group. Channels with no badge stay on their own.\n\n"),
                ("h2", "🧩 Insert order map\n"),
                ("body", "Shows your core tools + everything you marked ♥/👍, ordered top-to-bottom the way they "
                 "sit on a channel strip, with the ()/(()) usage notation. Sends (delay/reverb) are listed at "
                 "the end; auto-mastering tools on a separate 'master bus only' line. See the 'Notation' topic "
                 "for the parentheses, and 'Insert vs. Send' for why reverb sits on a send.\n"),
            ]),
            "scope": ("Notation: () and (()) — how many channels", [
                ("h1", "The ( ) and (( )) notation\n"),
                ("body", "In the inserts map a plugin's name is wrapped to show how WIDELY it's used in a mix:\n\n"),
                ("tip", "  • Plain  (e.g. Lowtility)   → on (almost) EVERY channel.\n"
                 "  • (Name) (e.g. (smart:EQ))   → on MANY but not all channels.\n"
                 "  • ((Name)) (e.g. ((Trackspacer))) → on only the ODD/FEW channels.\n\n"),
                ("body", "You set this per plugin in the 🧩 Plugins tab — click the [all]/[many]/[few] tag to "
                 "cycle it, or pick it in Add/Edit. It only affects how the inserts map reads; it doesn't change "
                 "any audio.\n"),
            ]),
            "corridor": ("Corridor reverb — the preset bundle", [
                ("h1", "What this bundle is\n"),
                ("body", "Corridor (Quantastical Sound) is a room reverb, and unlike the sonible plug-ins "
                 "its preset file is plain readable XML. That means this program can WRITE real Corridor "
                 "presets from the chart instead of cloning one of yours under a new name. "
                 "Generate ▸ \U0001f300 Corridor presets writes them straight into Corridor's own preset "
                 "folder, and every file is read back after it is written.\n\n"),
                ("h2", "It still needs one preset of yours\n"),
                ("body", "Not for the sound — for the container. A .vstpreset carries the plug-in's class id, "
                 "JUCE's own trailer and the <RoomPans> listening positions, and copying those out of a file "
                 "this exact build already accepted is what guarantees the generated ones load. Your "
                 "'corridor-test' is exactly right. Keep any one Corridor preset in the folder and this works.\n\n"),
                ("h2", "Why most of them are vocal presets\n"),
                ("body", "Because a voice is the one source where the reverb choice is a musical decision "
                 "rather than a taste one. Too much and the words go; too little and the singer is standing "
                 "in a different recording from the band. There are five for a lead vocal, three for backing "
                 "vocals and two for a choir or vocal pad, plus one each for the instruments that usually want "
                 "a space.\n\n"),
                ("h2", "The three knobs that do the work\n"),
                ("code", "  Pre-Delay   How long the voice stays completely dry.\n"
                         "              LEAD vocal  → 20–35 ms: it separates the singer from the tail,\n"
                         "                            which is what keeps the words in front of it.\n"
                         "              BACKING     → 6–10 ms: it glues the tail on and pushes them back.\n"
                         "              Same knob, opposite job. That is the whole trick.\n\n"
                         "  Low Decay   How much longer the LOWS ring than the mids. Down (30–45) on\n"
                         "              anything with a voice or a piano in it, or the tail collects\n"
                         "              underneath the part and turns to mud.\n\n"
                         "  Duck        The reverb gets out of the way while the source plays and blooms\n"
                         "              in the gaps. It is why the Ballad Long preset is usable at all.\n"),
                ("body", "\n"),
                ("h2", "One space, not one per channel\n"),
                ("body", "The \U0001f300 Corridor list in the right panel groups the channels BY PRESET on purpose. "
                 "Every horn shares one preset, the whole kit shares one, because separate reverbs on players "
                 "standing in the same room is what makes a section sound like three overdubs. The kick and "
                 "the basses appear under 'keep these dry' and get no preset at all — no line means nothing "
                 "to do, the same rule the depth engine uses.\n\n"),
                ("h2", "About the numbers, honestly\n"),
                ("body", "Corridor's parameter NAMES are read straight out of the plug-in, so those are exact. "
                 "It publishes no minimum or maximum for anything, anywhere in its binary, so the ranges are "
                 "inferred — and every value in the bundle is therefore kept inside the span your own "
                 "'corridor-test' preset proves is legal. They are starting points that load and play, which "
                 "is the same promise the rest of this program makes.\n\n"),
                ("warn", "The room MODEL (Vault, Abyss, Grove, Atrium …) is the one exception. The plug-in "
                 "names its rooms but not their order, so every generated preset uses the model your own test "
                 "preset uses rather than guessing. If you check the order in Corridor once, set "
                 "CORRIDOR_USE_ROOM_MODELS = True in the source and each preset picks its own room instead.\n"),
            ]),
            "omega": ("Omega 458a — saturation, and what Intensity really does", [
                ("h1", "The one plug-in that tells you the truth about itself\n"),
                ("body", "Kush Audio's Omega 2 458a is a transformer/preamp saturator, and it is the "
                 "best-documented plug-in in this whole program. It carries its own parameter table inside "
                 "the .vst3 — every name, range, step, default and curve, plus the complete signal path and "
                 "the fixed EQ the model applies before you touch anything. Nothing below is a guess. "
                 "Compare that with smart:EQ, whose state is an opaque blob we can only clone.\n\n"),
                ("h2", "The signal path, read out of the plug-in\n"),
                ("code", "  IN ─▶ EQ ─▶ [-20 dB Pad] ─▶ SATURATOR ─▶ COMPRESSOR ─▶ [+20 dB]\n"
                         "        │                                                    │\n"
                         "        │   (the fixed 458a curve + YOUR HPF/LPF)          MAKEUP\n"
                         "        │                                                    │\n"
                         "        └────────── dry, untouched ─────────────▶ BLEND ◀────┘\n"
                         "                                                    │\n"
                         "                                                 OUTPUT ─▶ OUT\n\n"),
                ("h2", "1. The filters are BEFORE the saturator — the dry path is not\n"),
                ("body", "This is the single most useful thing to know about the plug-in. The HPF and LPF "
                 "shape what gets saturated, and the Blend dry signal is tapped before them. So:\n\n"),
                ("code", "  HPF 140 Hz + Blend 50 %\n"
                         "     = the saturator never sees the sub at all\n"
                         "     + half the original arrives at the output untouched, sub included\n\n"),
                ("body", "That is the only honest way to saturate a bass or a kick. Distorting a 45 Hz "
                 "fundamental does not land at 45 Hz — it lands as intermodulation right across the mids, "
                 "and no EQ afterwards puts that back. It is why the Kick and Bass presets here look the way "
                 "they do, and it is worth setting Blend to 100 % once just to hear what you are avoiding.\n\n"),
                ("h2", "2. Intensity is a macro, not a drive knob\n"),
                ("body", "One control moves five things at once. These are the plug-in's own numbers:\n\n"),
                ("code", "  saturator drive      -28.25 dB  …  +15.45 dB\n"
                         "  61 Hz peak                0 dB  …   +0.35 dB\n"
                         "  12.5 kHz peak             0 dB  …   +1.00 dB\n"
                         "  1.79 kHz peak             0 dB  …   -0.30 dB\n"
                         "  compressor make-up      +17 dB  …  -10 dB   (the compensation)\n\n"),
                ("body", "So turning Intensity up is not only more harmonics: it is also a little more low "
                 "end, a little more top, and a small scoop exactly where a mix goes honky. And it "
                 "compensates 27 dB of level against 43.7 dB of added drive — MOST of it, not all of it. "
                 "Match loudness by ear before you decide one setting beats another, or you are just "
                 "hearing 'louder'.\n\n"),
                ("h2", "3. Makeup and Output Gain are not the same knob\n"),
                ("body", "Makeup sits BEFORE the Blend, so it changes the level of the processed path only — "
                 "turn it up and you get more effect at the same output. Output Gain sits AFTER the Blend and "
                 "moves everything. At Blend 100 % they behave identically; the moment you blend, they stop "
                 "being interchangeable.\n\n"),
                ("h2", "4. The -20 dB Pad is not a volume control\n"),
                ("body", "It is -20 dB going into the saturator and +20 dB coming out, so the level lands "
                 "where it was and the SATURATION drops by 20 dB. Pulling Input Gain down instead makes the "
                 "whole thing quieter as well as cleaner. On a bus — which arrives about 20 dB hotter than a "
                 "channel — the Pad is the right answer and Input Gain is not. That is why the Bus / Mix "
                 "preset is the only one here with it engaged.\n\n"),
                ("h2", "There is a compressor you cannot switch off\n"),
                ("body", "The model runs a Kush compressor after the saturator at attack 3.24 ms and release "
                 "135 ms, with no user control at all. That is why Omega thickens a part even at low "
                 "Intensity, why it works on a snare (3.24 ms is slower than a snare transient, so the crack "
                 "gets through and the body behind it gets squeezed), and why it is not a neutral colour "
                 "box. Treat it as a channel strip, not as a saturator.\n\n"),
                ("h2", "What the 458a does before you turn anything\n"),
                ("body", "The model applies a fixed EQ curve of its own. Read out of the plug-in's own "
                 "defaults, that is:\n\n"),
                ("code", "  +6.4 dB @ 376 Hz  (Q 0.61)   low-mid weight — the biggest single move\n"
                         "  -0.7 dB @ 416 Hz  (shelf)    so the weight lands as body, not as mud\n"
                         "  +0.3 dB @ 2.13 kHz (shelf)   a gentle presence lift\n"
                         "  +1.2 dB @ 16.2 kHz (Q 0.72)  air\n\n"),
                ("warn", "That +6.4 dB of 376 Hz is the reason to read this section. If your Kirchhoff chart "
                 "also asks for a boost around there, you are about to make the same move twice — and 'why "
                 "does this channel sound thick' is almost always two plug-ins agreeing with each other. "
                 "Where that overlap exists, the instrument's own Omega footnote says so on a ↔ line (switch "
                 "on View ▸ Extra comments to see them).\n\n"),
                ("h2", "One instance per channel\n"),
                ("body", "Unlike Corridor, this is not a shared space — every channel that wants it gets its "
                 "own instance, and the presets are grouped in the 🔥 list only to keep the list short. The "
                 "exception is the bus: one Omega on a drum bus beats one on every drum under it, because "
                 "six saturators feeding a bus is six sets of intermodulation products summing, which is a "
                 "different and worse sound than one saturator hearing the whole kit at once.\n\n"),
                ("h2", "Two switches a preset does not carry\n"),
                ("body", "The plug-in marks OVERSAMPLING (the LOW LATENCY / ANALOG HIGHS button) and BYPASS "
                 "as global rather than per-preset, so loading a preset never moves them. Set them once and "
                 "they stay put.\n"),
            ]),
            "bandwidth": ("Bandwidth — stereo width, and what Strength does", [
                ("h1", "Width you can add without breaking the mono mix\n"),
                ("body", "In The Mix's Bandwidth adds stereo width by synthesising delayed copies of the "
                 "signal and putting them in the sides. The added part sums to nothing in mono, so the "
                 "original is never damaged if the song is played on a phone speaker, a club system or a "
                 "mono radio. It also works on a mono source.\n\n"),
                ("h2", "Three bands, two crossovers\n"),
                ("code", "  LOW   ──  LOW CROSS  ──  MID  ──  HIGH CROSS  ──  HIGH\n"
                         "  0-200 %   (default 400 Hz)  0-200 %   (default 4 kHz)   0-200 %\n\n"),
                ("body", "Each band has its own width mix. 0 % leaves the band exactly as it was; 200 % is "
                 "the plug-in's ceiling. The crossovers are 24 dB/oct, so a band can be narrowed or "
                 "widened: High cross 6 kHz means the High slider only widens above 6 kHz.\n\n"),
                ("h2", "Strength is time, not size\n"),
                ("body", "Strength controls how much delay the synthesised copies get. The manual says 3 "
                 "to 6 suits most sources and that bass sounds should stay BELOW 6, because more starts to "
                 "shift the left/right balance. It is why every bass, cello and kick preset here has a "
                 "Strength of 3 to 4.5.\n\n"),
                ("h2", "The rules the presets follow\n"),
                ("code", "  1. LOW is 0 on kick and bass. The low band is where width costs punch and\n"
                         "     where every sound system folds to mono anyway.\n"
                         "  2. STRENGTH stays under 6 on anything with weight.\n"
                         "  3. LEAD parts get very little width; the width goes to BACKING parts.\n"
                         "     Contrast is what reads as wide - a lead that is also wide is not.\n"
                         "  4. A big preset has OUTPUT -0.2 … -0.4 dB, because a wide part sounds\n"
                         "     louder. That is a level match, not a decision.\n\n"),
                ("h2", "Where it sits in the chain\n"),
                ("body", "After the EQ and the compressor, after the pan or the Virtual Stage, and before "
                 "the reverb. Width that goes into the reverb is part of the room; width added after it "
                 "is a second reverb. If a channel already has a hard pan, use less: width on a hard-"
                 "panned part mostly drags it back towards the middle.\n\n"),
                ("h2", "Check it with the Monitor switch\n"),
                ("body", "STEREO is the normal state. SIDE plays only what was ADDED, so you can hear "
                 "exactly what the plug-in is doing. MID plays the centre, which is preserved no matter "
                 "how much width is added - set it once to confirm a lead vocal or a kick is still "
                 "intact. This program always writes STEREO.\n\n"),
                ("h2", "About these presets\n"),
                ("body", "A Bandwidth user preset is a tiny plain-text file, so this program writes it "
                 "from scratch - there is no seed file to find. The 13 you made by hand (drums, brass, "
                 "strings, organ) are reproduced value for value and byte for byte. The presets for every "
                 "other instrument are starting points chosen from the rules above.\n\n"),
                ("warn", "Only the 0-200 % range of the three mix sliders is documented by the plug-in. "
                 "The other limits used here are kept inside what the factory presets prove legal, which "
                 "is the same promise the rest of this program makes: they load and play.\n"),
            ]),
            "cascadia": ("Cascadia — the delay send, and how its presets work", [
                ("h1", "A send for rhythm and movement - never for size\n"),
                ("body", "iZotope's Cascadia is a delay with an 'Unmask' processor on its output. In this "
                 "program it is a SEND at the end of the chain: one shared instance that several channels "
                 "feed, the same way the Corridor reverb works. It adds echo and movement. It cannot add "
                 "depth - a delay can never be a hall, so when a part should sit further BACK that is a "
                 "reverb send and a Distance value, not a delay.\n\n"),
                ("h2", "What Unmask does\n"),
                ("body", "Unmask listens to the dry signal and ducks the echo, band by band, wherever the "
                 "dry signal would be masked by it. That is why a busy part can take an echo at all: the "
                 "echo stays out of the way while the part plays and blooms in the gaps. So the presets "
                 "raise Unmask (30-40 %) on busy or important parts - a lead vocal, a snare, toms - and "
                 "lower it on pads (15 %), where there are no gaps and ducking would only make it pump.\n\n"),
                ("h2", "Every channel gets some space\n"),
                ("body", "Even the ones that must stay tight. For the kick, the basses, the hi-hat, ride, "
                 "cymbals and a single-note low guitar the preset is an AIR-ONLY version: a low cut at "
                 "600-900 Hz, far above the fundamental, so the echo is made of the click, the harmonics and "
                 "the top only. The weight never reaches the delay and stays exactly where it was; what "
                 "you gain is a sense of room around it. Unmask then ducks even that while the part hits. "
                 "A bass SOLO has its own preset ('Bass Guitar Solo \u00b7 Echo Pulse') as an alternative.\n\n"),
                ("h2", "The rules the presets follow\n"),
                ("code", "  1. AMOUNT is the send level and stays modest (15-35 %).\n"
                         "  2. A LOW CUT well above the bass (120-500 Hz) on every preset.\n"
                         "  3. FEEDBACK low on leads, higher on pads and effects.\n"
                         "  4. A HIGH CUT that makes each repeat darker than the one before.\n\n"),
                ("h2", "Where the presets go - two kinds of file, two folders\n"),
                ("body", "Cascadia's OWN preset browser (Classic / Creative / User presets) reads plain "
                 "'.preset' files from Documents\\iZotope\\Cascadia\\Presets - they show up under User "
                 "presets. Cubase's preset list reads '.vstpreset' files from Documents\\VST3 Presets\\"
                 "iZotope\\Cascadia. Each browser ignores the other's files, so a .vstpreset copied into "
                 "the Presets folder is simply invisible. Generate writes BOTH, so a preset is in both "
                 "places. The .preset files need no template; the .vstpreset files need one Cascadia "
                 "preset saved from Cubase (your 'radera-cascadia') as the container.\n\n"),
                ("h2", "One thing that is only partly known\n"),
                ("body", "With Tempo Sync ON, Cascadia ignores the time in milliseconds and uses an index "
                 "into its list of note values. Only one index is confirmed: 7 = 1/8. Seven of the 15 "
                 "presets you made yourself carry other indexes (4, 6 and 9). In the .vstpreset files they are "
                 "reproduced exactly as they were and marked with a warning; in the .preset files the note is "
                 "written as text, so it is taken from the stored time at 120 BPM (1/16, 1/16., 1/4). Every NEW preset either uses 7 or turns Tempo "
                 "Sync off and states a time in ms. If you save a Cascadia preset at 1/4, 1/8., 1/16 and so "
                 "on, the table can be completed and the warnings disappear.\n\n"),
                ("warn", "Ranges are not published by the plug-in. Everything written stays inside what the "
                 "57 factory presets prove legal, which is the same promise the rest of this program makes: "
                 "they load and play.\n"),
            ]),
            "vstage": ("Virtual Stage — placing the band", [
                ("h1", "One plug-in that does the pan, the width and the room\n"),
                ("body", "EVA Instruments Virtual Stage puts a source at a point inside a virtual room, and "
                 "moves EQ, delay, stereo width, balance, panning and reverb together to get it there. Three "
                 "controls carry all of it:\n\n"),
                ("code", "  POSITION   left ↔ right on the stage\n"
                         "  DISTANCE   0 = in your face  …  100 = against the back wall\n"
                         "  ROOM       Small / Medium / Large\n"
                         "  LOCK POSITION   move it front/back WITHOUT changing left/right\n\n"),
                ("h2", "Presets: a snapshot, named by its numbers\n"),
                ("body", "What this program tells you to dial in depends on the rest of the line-up: a lone "
                 "chord guitar is not placed where a rhythm+chord PAIR is placed, a ride with a hi-hat next to "
                 "it is not placed where a lone ride is, and a kit with no toms is not spread as wide as a "
                 "kit with toms. So there is no fixed 'Cello' preset. Generate ▸ Virtual Stage presets writes "
                 "the CURRENT stage - one file per ticked channel, one per copy for a ✖N part - and the file "
                 "name holds the numbers:\n\n"),
                ("code", "  3---Cello---D46---L10\n"
                         "  │   │       │    └ Position: L10 = 10 % left, R45, or Centre\n"
                         "  │   │       └ Distance 46\n"
                         "  │   └ instrument\n"
                         "  └ room: 1 Small · 2 Medium · 3 Large  (one room for the whole song)\n\n"),
                ("body", "The same numbers are always the same file, and a different line-up makes new names "
                 "instead of changing an old preset. Lock Position is ON in all of them. The kick and the "
                 "basses get none - the plug-in stays off them. The folder is "
                 "Documents\\VST3 Presets\\EVA Instruments\\Virtual Stage (File ▸ Set Virtual Stage preset "
                 "folder…). Generate ▸ Virtual Stage presets: All writes a whole library in all three rooms "
                 "instead: every instrument on its own, rhythm + chord guitar together (one of each, plus "
                 "2+1 / 1+2 / 2+2), the drum kit in seven shapes, and Toms and Cymbals for every count from "
                 "1 to 9, each count with its own L / Centre / R spread. Their Distance comes from a typical "
                 "line-up and may need a nudge in a real song. The file layout was read from your own '3---Cello' plus four test presets; "
                 "Distance is stored as twice its value, Position as 100 + the percentage.\n\n"),
                ("h2", "One song = ONE room\n"),
                ("body", "Room size is the building the band is standing in, not a per-channel flavour. Small "
                 "on the snare and Large on the overheads is not depth — it is two recordings edited together. "
                 "The program picks the room once, from the size of the arrangement, and uses it everywhere. "
                 "Closeness comes from DISTANCE, never from a smaller room.\n\n"),
                ("h2", "A drum kit is ONE object\n"),
                ("body", "It is about a metre deep and one person is hitting all of it, so every piece lives "
                 "inside a narrow window of Distance values — usually 6–8 points. Hi-hat at 30 and toms at 70 "
                 "does not make a deeper kit, it makes two kits in two rooms.\n\n"),
                ("code", "  toms present      →  they own the flanks; hats/ride pull IN\n"
                         "  no toms           →  hats/ride move OUT to cover the empty flanks\n"
                         "  hi-hat AND ride   →  opposite sides, each pulled in as if it were alone:\n"
                         "                       they take turns (hat in the song, ride at the end)\n"
                         "  only one of them  →  pulled in toward centre, or the kit leans\n"
                         "  overheads present →  widest and furthest back; they carry the air\n"
                         "  no overheads      →  whole kit FORWARD, room one size DOWN\n"
                         "  kick + snare only →  everything Centre. That is a beat, not a kit.\n\n"),
                ("h2", "What it replaces\n"),
                ("body", "Position IS the pan for that channel — leave the Cubase pan centred. And a channel "
                 "on Virtual Stage should NOT also feed the Near/Mid/Far reverb bus at the same depth: that is "
                 "two rooms at once. Either place it here or send it there.\n\n"),
                ("warn", "It stays OFF the kick and off both basses. Room on a low-end source is mud: the "
                 "reflections come back a few milliseconds late and comb-filter the exact octave the whole mix "
                 "depends on.\n\n"),
                ("h2", "The one exception: ✖2 on a bass\n"),
                ("body", "That rule is the right answer for ONE bass. Put the count up to two and the second "
                 "one stops being a bass: the ✖N plan splits a doubled bass into a foundation layer that owns "
                 "everything below 100 Hz and a character layer high-passed at 100–120 Hz. The ban exists "
                 "entirely because of the low end — and the character layer no longer HAS a low end to "
                 "comb-filter, so on that layer the plug-in becomes a legitimate way to make two basses read "
                 "as two bodies. The card offers it as an option, with the numbers, the moment the count goes "
                 "above one.\n\n"),
                ("body", "It is an option and not the plan because it turns on something this program cannot "
                 "see: whether the two are two PARTS, or one bass split into sub + character. If it is one "
                 "bass, keep both layers off — a room on half of a layered sound is a phase difference between "
                 "two copies of the same note. The condition is printed with the option so you make that call "
                 "on purpose.\n\n"),
                ("warn", "The kick never gets this exception, at any count. A layered kick is still one "
                 "transient, and the beater-click layer is the one thing in a mix that must not be delayed.\n"),
            ]),
            "presets": ("Generating & loading presets", [
                ("h1", "Generating presets (Generate menu)\n"),
                ("body", "The Generate menu writes real preset files so you don't dial them by hand:\n\n"),
                ("tip", "  • 🎛 Kirchhoff presets — one .keq per track (Selected = mix-adjusted, All = solo\n"
                 "    baseline). They show in Kirchhoff's OWN browser; tick 'also write Cubase .vstpreset' in\n"
                 "    Options to also get them in Cubase's preset selector.\n"
                 "  • 🌫 smart:reverb presets — patches Distance/Size/Width into your seed. Use 'one preset per\n"
                 "    tier (buses)' for the Near/Mid/Far/Front workflow (see the 'Reverb depth buses' topic).\n"
                 "  • 🔻 Lowtility presets — one .vstpreset per track with the exact low-cut corner + slope.\n"
                 "  • 🎪 Virtual Stage presets — one .vstpreset per ticked channel with Room, Distance and\n"
                 "    Position from the stage plan; the name holds the numbers (see the Virtual Stage topic).\n"
                 "    'All' writes the whole library (every instrument, guitar pair, toms/cymbals 1-9).\n\n"),
                ("body", "Set the target folders via File ▸ Set … preset folder. Backups + a text recipe always "
                 "go to Helpfiles\\Presets so a folder wipe can't lose them. If a file already exists you are asked whether to overwrite it (the old one is kept as .bak)."
                 " \n"),
            ]),
        }

    # ---- 🦻 HEARING PROFILE --------------------------------------------------

    def _show_hearing_dialog(self):
        """Tell the program what you can and cannot judge by ear, one octave band
        at a time. Everything else about the hearing support follows from this.
        Enter saves, Esc closes."""
        top = tk.Toplevel(self.root)
        top.title("Hearing profile")
        top.configure(bg=C_BG)
        top.resizable(True, True)
        top.transient(self.root)
        top.geometry("780x620")

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🦻  Hearing profile", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Label(hdr, text="   —  what can you actually judge by ear?",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left")

        intro = tk.Label(
            top,
            text=("This is not a hearing test and it is not medical — it is a working "
                  "preference in your own words. For each range, say whether you can "
                  "trust your ear there. The program then marks every band on every "
                  "card, caps boosts in the ranges you cannot check, decides the "
                  "'TRY / depends on the track' bands for you, and writes your own "
                  "rule sheet. If you have an audiogram: a loss of roughly 25 dB or "
                  "more in a range is 'Cannot judge'; 10–25 dB is 'Not sure'."),
            bg=C_BG, fg=C_FG_DIM, font=FONT_SMALL, wraplength=740,
            justify="left", anchor="w", padx=14, pady=8)
        intro.pack(fill="x")

        # Scrollable band list
        body = tk.Frame(top, bg=C_BG)
        body.pack(fill="both", expand=True, padx=10)
        canvas = tk.Canvas(body, bg=C_BG, bd=0, highlightthickness=0)
        vsb = tk.Scrollbar(body, orient="vertical", command=canvas.yview,
                           bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        canvas.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        inner = tk.Frame(canvas, bg=C_BG)
        win = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>", lambda e: canvas.itemconfig(win, width=e.width))

        def _wheel(e, _c=canvas):
            _c.yview_scroll(-2 if e.delta > 0 else 2, "units")
            return "break"
        canvas.bind("<MouseWheel>", _wheel)

        vars_by_band = {}
        for key, _lo, _hi, label, desc in HEARING_BANDS:
            rowf = tk.Frame(inner, bg=C_CARD, padx=10, pady=6)
            rowf.pack(fill="x", pady=(4, 0))
            head = tk.Frame(rowf, bg=C_CARD)
            head.pack(fill="x")
            tk.Label(head, text=label, bg=C_CARD, fg=C_FG,
                     font=("Segoe UI", 10, "bold"), width=8,
                     anchor="w").pack(side="left")
            tk.Label(head, text=desc, bg=C_CARD, fg=C_FG_DIM, font=FONT_SMALL,
                     wraplength=430, justify="left",
                     anchor="w").pack(side="left", fill="x", expand=True)
            v = tk.StringVar(value=self.hearing.get(key, "ok"))
            vars_by_band[key] = v
            btns = tk.Frame(rowf, bg=C_CARD)
            btns.pack(fill="x", pady=(3, 0))
            for state in HEARING_ORDER:
                glyph, colour, short, _meaning = HEARING_STATES[state]
                tk.Radiobutton(btns, text=f"{glyph} {short}", variable=v, value=state,
                               bg=C_CARD, fg=colour,
                               selectcolor=C_BG2,      # normal colour: C_BG2 = "#16213e"
                               activebackground=C_CARD, activeforeground=C_FG,
                               font=FONT_SMALL, highlightthickness=0, bd=0,
                               cursor="hand2").pack(side="left", padx=(0, 14))
        self._bind_wheel(inner, _wheel)

        # ---- Buttons ----
        btm = tk.Frame(top, bg=C_BG2, pady=8, padx=12)
        btm.pack(fill="x")

        def _preset_age():
            """The common pattern: fine low, uncertain presence, gone on top."""
            for k, want in (("125", "ok"), ("250", "ok"), ("500", "ok"),
                            ("1k", "ok"), ("2k", "weak"), ("4k", "weak"),
                            ("8k", "lost"), ("16k", "lost")):
                vars_by_band[k].set(want)

        def _preset_clear():
            for v in vars_by_band.values():
                v.set("ok")

        def _save(_e=None):
            self.hearing = {k: v.get() for k, v in vars_by_band.items()
                            if v.get() in HEARING_STATES}
            self.settings["hearing"] = dict(self.hearing)
            self._save_current_settings()
            self._on_filter_change()   # rebuild the cards with the 🦻 column
            self._refresh_summary()
            top.destroy()
            self._toast("Hearing profile saved")

        tk.Button(btm, text="Save (Enter)", command=_save,
                  bg="#2d5a3a", fg=C_BTN_FG,        # change colour here (green-ish)
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=12, pady=3,
                  cursor="hand2").pack(side="right")
        tk.Button(btm, text="Cancel (Esc)", command=top.destroy,
                  bg=C_BTN, fg=C_BTN_FG,            # normal colour: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=12, pady=3,
                  cursor="hand2").pack(side="right", padx=(0, 8))
        tk.Button(btm, text="Typical high-frequency loss", command=_preset_age,
                  bg=C_BTN, fg=C_BTN_FG,            # normal colour: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2").pack(side="left")
        tk.Button(btm, text="Clear (I hear everything)", command=_preset_clear,
                  bg=C_BTN, fg=C_BTN_FG,            # normal colour: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2").pack(side="left", padx=(8, 0))

        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.bind("<Return>", _save)

    def _show_hearing_rules(self):
        """Your personal rule sheet, generated from the profile. With no profile
        it explains what filling one in would buy you."""
        top = tk.Toplevel(self.root)
        top.title("Mixing with hearing loss — my rules")
        top.configure(bg=C_BG)
        top.resizable(True, True)
        top.transient(self.root)
        top.geometry("720x640")

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🦻  My rules", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Edit profile…", command=lambda: (top.destroy(),
                                                              self._show_hearing_dialog()),
                  bg=C_BTN, fg=C_BTN_FG,            # normal colour: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  cursor="hand2").pack(side="right", padx=(8, 0))
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")

        text_frame = tk.Frame(top, bg=C_BG)
        text_frame.pack(fill="both", expand=True, padx=10, pady=10)
        vsb = tk.Scrollbar(text_frame, bg=C_BG2, troughcolor=C_BG,
                           activebackground=C_ACCENT)
        vsb.pack(side="right", fill="y")
        txt = tk.Text(text_frame, bg=C_BG2, fg=C_FG, font=FONT_NORMAL, relief="flat",
                      bd=0, wrap="word", yscrollcommand=vsb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        vsb.config(command=txt.yview)
        txt.tag_configure("h1",   font=("Segoe UI", 12, "bold"), foreground=HEARING_COLOUR)
        txt.tag_configure("h2",   font=("Segoe UI", 10, "bold"), foreground=C_FG)
        txt.tag_configure("body", font=FONT_NORMAL,              foreground=C_FG_DIM)
        txt.tag_configure("warn", font=("Segoe UI", 9, "bold"),  foreground="#ffcf8f")

        if not self.hearing:
            txt.insert("end", "No profile yet\n", "h1")
            txt.insert("end",
                       "Open Help ▸ 🦻 Hearing profile and say, for each octave band, "
                       "whether you can judge it by ear. It takes about a minute, and "
                       "from then on:\n\n", "body")
            for line in (
                "• every band on every card is marked ✔ / ◐ / ⛔,",
                "• boosts in the ranges you cannot check are capped, so you stop "
                "boosting a band until YOU can hear it,",
                "• 'TRY / depends on the track' bands inside those ranges are decided "
                "for you instead of left as a question you cannot answer,",
                "• and this window becomes your own rule sheet — what to set by "
                "number, what to read off a meter, and which of your plug-ins decide "
                "by analysis rather than by ear.",
            ):
                txt.insert("end", line + "\n", "body")
        else:
            for heading, lines in hearing_rules(self.hearing):
                txt.insert("end", "\n" + heading + "\n", "h1")
                for line in lines:
                    txt.insert("end", "• " + line + "\n\n", "body")
            txt.insert("end", "\nAnd the honest part\n", "h1")
            txt.insert("end",
                       "None of this makes a range audible again. What it does is stop "
                       "you making decisions in a range you cannot check — which is a "
                       "different and entirely solvable problem. A mix built from "
                       "correct numbers in your dead ranges and your own ears in the "
                       "live ones will translate. A mix built by chasing what you can "
                       "hear will not.\n", "warn")

        txt.configure(state="disabled")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _show_explain(self, key):
        """Render one Explain topic in a scrollable, Esc-closable dialog."""
        data = self._explain_data().get(key)
        if not data:
            return
        title, segments = data
        top = tk.Toplevel(self.root)
        top.title(f"How it works — {title}")
        top.configure(bg=C_BG)
        top.resizable(True, True)
        top.transient(self.root)
        top.geometry("640x560")

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text=f"💡  {title}", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 13, "bold")).pack(side="left")
        tk.Button(hdr, text="Close (Esc)", bg=C_BTN, fg=C_BTN_FG,
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_SMALL, relief="flat", padx=10, pady=3,
                  command=top.destroy).pack(side="right")

        text_frame = tk.Frame(top, bg=C_BG)
        text_frame.pack(fill="both", expand=True, padx=10, pady=10)
        vsb = tk.Scrollbar(text_frame, bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        vsb.pack(side="right", fill="y")
        txt = tk.Text(text_frame, bg=C_BG2, fg=C_FG, font=FONT_NORMAL, relief="flat",
                      bd=0, wrap="word", yscrollcommand=vsb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        vsb.config(command=txt.yview)
        txt.tag_configure("h1",   font=("Segoe UI", 12, "bold"), foreground=C_ACCENT)
        txt.tag_configure("h2",   font=("Segoe UI", 10, "bold"), foreground=C_FG)
        txt.tag_configure("body", font=FONT_NORMAL,              foreground=C_FG_DIM)
        txt.tag_configure("code", font=FONT_MONO,                foreground=C_BOOST)
        txt.tag_configure("tip",  font=FONT_SMALL,               foreground=C_CHAR)
        txt.tag_configure("warn", font=("Segoe UI", 9, "bold"),  foreground="#ffcf8f")
        for style, body in segments:
            txt.insert("end", body, style)
        txt.configure(state="disabled")

        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

    def _show_help(self):
        top = tk.Toplevel(self.root)
        top.title(f"Help — {APP_NAME}")
        top.configure(bg=C_BG)
        top.resizable(True, True)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.geometry("700x600")

        hdr = tk.Frame(top, bg=C_BG3, pady=8, padx=14)
        hdr.pack(fill="x")
        tk.Label(hdr, text=f"📖  {APP_NAME} — Help",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 13, "bold")).pack(side="left")

        text_frame = tk.Frame(top, bg=C_BG)
        text_frame.pack(fill="both", expand=True, padx=10, pady=10)

        vsb = tk.Scrollbar(text_frame, bg=C_BG2, troughcolor=C_BG, activebackground=C_ACCENT)
        vsb.pack(side="right", fill="y")

        txt = tk.Text(text_frame, bg=C_BG2, fg=C_FG, font=FONT_NORMAL,
                      relief="flat", bd=0, wrap="word",
                      yscrollcommand=vsb.set,
                      insertofftime=0, insertontime=9999999)
        no_blink(txt)
        txt.pack(fill="both", expand=True)
        vsb.config(command=txt.yview)

        txt.tag_configure("h1",   font=("Segoe UI", 12, "bold"), foreground=C_ACCENT)
        txt.tag_configure("h2",   font=("Segoe UI", 10, "bold"), foreground=C_FG)
        txt.tag_configure("body", font=FONT_NORMAL,              foreground=C_FG_DIM)
        txt.tag_configure("code", font=FONT_MONO,                foreground=C_BOOST)
        txt.tag_configure("tip",  font=FONT_SMALL,               foreground=C_CHAR)

        HELP_TEXT = [
            ("h1", "What is EQ Cheat Sheet?\n"),
            ("body", "EQ Cheat Sheet is a quick-reference guide for equalisation settings in rock music production. "
             "It covers the most common instruments found in rock arrangements: drums, bass, guitars, keyboards, and wind instruments.\n\n"),

            ("h1", "✖N  How many of each — and why it matters\n"),
            ("body", "Every instrument card has a 'how many' box next to its tick (the same number as the "
             "Song Variants tab — change it in either place). Raise it above 1 and a ✖N box appears with the "
             "whole plan for having several of that part.\n\n"),
            ("h2", "The fact behind all of it\n"),
            ("body", "Two tracks of the same part do not sound like one part played louder — unless you made "
             "them identical, in which case that is exactly what they are:\n\n"),
            ("code", "  Same audio, copied   →  +6 dB, zero width. A volume knob.\n"
                     "  Two separate takes   →  +3 dB, and the differences become the width.\n"
                     "  N separate takes     →  +10·log10(N) dB in the band they share.\n\n"),
            ("body", "Three chord guitars are therefore not 'three guitars'. They are a 4.8 dB boost across "
             "200 Hz–4 kHz that you never asked for, sitting right on the vocal. The ✖N box prints that number "
             "for your count and tells you to pull each copy down by it.\n\n"),
            ("h2", "What the ✖N box gives you\n"),
            ("body", "A pan ladder computed for your count (#1 L85 · #2 Centre · #3 R85), a tone split so each "
             "copy owns a different band, a low-cut ladder so only ONE copy keeps the low end, a reverb ladder "
             "so they sit at different depths, and the bus verdict.\n\n"),
            ("tip", "Not every instrument widens. Guitars, backing vocals, pads and plucks WIDEN — spread and "
             "differentiate them. Bass, kick, lead vocal and low horns LAYER — they stay centred and split the "
             "frequency range instead. Toms, percussion and cymbals SPREAD by where they physically sit. Each "
             "card knows which of the three it is, and says so.\n\n"),

            ("h1", "🦻 Mixing when you cannot trust your ears\n"),
            ("body", "Open Help ▸ 🦻 Hearing profile and say, for each octave band, whether you can judge that "
             "range by ear: ✔ well · ◐ not sure · ⛔ not at all. It takes a minute, it is stored with your other "
             "settings, and until you fill it in nothing in the program changes.\n\n"),
            ("h2", "What it changes\n"),
            ("body", "Every band on every card gets a mark in a new 🦻 column, with a tooltip saying what to do "
             "with it. Boosts inside a range you cannot judge are CAPPED at +2 dB (+4 dB where you are only "
             "unsure), and 'TRY / depends on the track' bands in those ranges stop being a question — the "
             "program picks the value and prints DECIDED next to it.\n\n"),
            ("h2", "Why the cap is the whole point\n"),
            ("body", "If your loss at 8 kHz is 20 dB, then turning the cymbals up until YOU can hear them means "
             "you have added roughly 20 dB of cymbals for everybody else. It sounds correct to you and thin, "
             "brittle and fatiguing to them. That one mechanism is behind most 'my mixes sound harsh on other "
             "systems' problems, and listening harder cannot fix it. Cuts are capped too, for the mirror-image "
             "reason: you can gut the air of a whole mix while it still sounds clean to you.\n\n"),
            ("body", "The 🦻 My rules button (right panel, and the Help menu) generates your own rule sheet from "
             "the profile: which ranges your ear still wins in, what to set by number, what to read off a meter, "
             "and which of your own plug-ins reach their decision by ANALYSING the audio instead of asking you "
             "to listen — smart:EQ for masking, smart:comp for level, Bandwidth's presets instead of a curve you "
             "dial by ear.\n\n"),
            ("tip", "This is not a hearing test and not medical advice. It is a working preference in your own "
             "words about what you can hear today, and you can change it whenever you like.\n\n"),

            ("h1", "★ Focus plug-ins\n"),
            ("body", "The 🧩 Plugins tab pins the tools you are actually working with right now to a box at the "
             "top, in chain order, each with a line on what its job is. They are also starred in the list, "
             "sorted to the top of their own category, starred in the insert map, and have their own '★ Focus' "
             "filter. Click the ★ on any plugin row to add or remove it — the set is remembered between runs.\n\n"),

            ("h1", "🗺 The Roadmap — what feeds what\n"),
            ("body", "The right-panel 🗺 Roadmap button (also Generate ▸ Roadmap) draws the whole routing tree for "
             "the channels you have ticked: channel → sub-bus → section bus → master, with a numbered build order "
             "you can follow in Cubase one line at a time.\n\n"),
            ("h2", "The drum tree\n"),
            ("code", "  Kick + Snare                    →  Drums: Front\n"
                     "  Toms                            →  Drums: Toms\n"
                     "  Drums: Toms + Hi-Hat + Ride     →  Drums: Mid\n"
                     "  Cymbals                         →  Drums: Cymbals\n"
                     "  Drums: Cymbals + Percussion     →  Drums: Back\n"
                     "  Front + Mid + Back              →  Drums: All\n\n"),
            ("body", "Why bother: one fader per section (pull Drums: All and the whole kit steps back with its "
             "internal balance intact), and shared plug-ins — if every tom gets the same treatment, the tom "
             "plug-ins live ONCE on Drums: Toms instead of once per channel.\n\n"),
            ("body", "The rest works the same way. Two or more bass parts share a Bass bus. All guitars share a "
             "Guitars bus. The lead vocal keeps its own path while backing vocals and choir share Vocals: Back. "
             "Keys, winds and strings each get a Background bus, and those feed Background: All.\n\n"),
            ("tip", "A bus must EARN its place: at least two channels under it (a count of 3 toms counts as "
             "three). Otherwise the Roadmap dissolves it into its parent — one lonely tom is just a tom.\n\n"),
            ("h2", "What goes on a bus\n"),
            ("body", "Glue compressor (2:1, 1–3 dB), smart:EQ (this is the group slot), the section fader, and a "
             "shared reverb send if the section shares a depth. NOT the low cut — Lowtility does the high-pass "
             "once, on the channel. Two high-passes in series smear the low end.\n\n"),

            ("h1", "🎯 smart:EQ groups — when 11 buses meet 10 slots\n"),
            ("body", "smart:EQ 4 gives you 10 group slots and a full arrangement easily needs more. The 🎯 "
             "smart:EQ Groups window no longer just reports the problem: it lists the cheapest merges best-first, "
             "APPLIES them until the plan fits, and colour-codes the buses that belong together — one colour per "
             "merge. Merges it has already done are marked ✔ DONE; the ones still on the table are ○ OPTIONAL, "
             "each with what you lose by taking it.\n\n"),
            ("tip", "The cheapest merge is almost always the BACK beds: pads, keys, brass beds and string beds all "
             "do the same job back there, so Keys/Winds · BACK + Strings · BACK become one 'Beds · BACK' bus with "
             "one smart:EQ. The most expensive is Drums: All — it costs you kick/snare-vs-cymbals unmasking, so "
             "the program keeps that one for last.\n\n"),

            ("h1", "What the program does NOT print\n"),
            ("body", "If a channel has no reverb, there is no reverb line — you will not see 'No reverb (keep "
             "DRY)' on the bass. If a channel ducks nothing, there is no duck line. Absence is the information, "
             "and it keeps the cards short enough to read.\n\n"),
            ("h1", "EQ engine — Kirchhoff (Parametric Q) vs. Range\n"),
            ("body", "At the top of the window there is an 'EQ engine' selector with two modes. "
             "It changes how every instrument card and the right-hand summary present their numbers — "
             "the underlying advice is the same, only the way it is expressed differs:\n\n"),
            ("h2", "🎯 Kirchhoff EQ V" + KIRCHHOFF_VERSION + " — Parametric Q (default)\n"),
            ("body", "Tailored for a fully-parametric EQ such as Kirchhoff-EQ, where each band is one point you "
             "dial in by hand. Instead of a frequency range it gives the EXACT five things a Kirchhoff band asks for:\n\n"),
            ("code", "  Shape  — the Kirchhoff Type to pick: Bell, Flat-Top, High Shelf, or High Pass\n"
             "  Freq   — the exact centre/corner frequency to type in\n"
             "  Gain   — exact boost/cut in dB (shown as '—' for a High Pass, which has no gain)\n"
             "  Q      — exact Q value (wide ≈1 for musical boosts, narrow 2–4 for surgical cuts)\n"
             "  Slope  — dB/oct for High Pass, shelves & Bell; '—' for a Flat-Top (own type)\n\n"),
            ("h2", "Which Shape do I pick? (it is NOT always a Bell)\n"),
            ("body", "Kirchhoff has 15 filter types. We use four; the 'What it does / how to shape it' "
             "column repeats this per band:\n\n"),
            ("tip", "  • High Pass  → removing rumble / low junk below a corner. Slope is the shape.\n"
             "  • High Shelf → lifting or trimming the very top (air). Broad, gentle.\n"
             "  • Bell       → a focused or medium boost/cut at one spot (presence, a mud notch).\n"
             "  • Flat-Top   → its OWN Kirchhoff type — a flat PLATEAU for a WIDE boost/cut\n"
             "                 (≈1.5 octaves+); set the plateau width with Q, no slope to set.\n\n"),
            ("body", "Two more Kirchhoff types worth knowing (the cards point you to them): "
             "SWORD — sharper than a bell, made to dig a stubborn resonance out; and the BRICKWALL "
             "high/low pass for a truly surgical cliff.\n\n"),
            ("h2", "Does the Slope change per band, or stay the same?\n"),
            ("body", "It changes — and note Kirchhoff's slope RANGES differ per type:\n\n"),
            ("tip", "  • High Pass : 0–96 dB/oct. VARIES — 12 = gentle, 24 = tight, 48+ ≈ surgical.\n"
             "  • Shelves    : 6–96 dB/oct. ≈6 for broad 'air', ≈12 for a tonal shelf.\n"
             "  • Bell       : 12–96 dB/oct, so '12 dB/oct' shown IS the minimum/default —\n"
             "                 leave it there and shape with Q. (6 dB/oct does not exist on a bell.)\n"
             "  • Flat-Top   : its own fixed-shape type — no slope to set; width is the Q.\n\n"),
            ("body", "Golden rule baked in: boost WIDE (low Q / Flat-Top), cut NARROW (high Q), and on a High Pass "
             "let the slope do the shaping. These are baselines — trust your ears in the full mix.\n\n"),
            ("h2", "Kirchhoff Stereo Mode (Mid/Side) — air, space & clarity by numbers\n"),
            ("body", "Every Kirchhoff band can run on a chosen part of the stereo signal instead of the whole thing. "
             "Pick the band's Stereo Mode:\n\n"),
            ("tip", "  • Stereo (L+R) — the default; the band hits both channels.\n"
             "  • Left / Right  — only that one channel.\n"
             "  • Mid (M)       — only the CENTRE content (what L and R share: vocal, kick, bass, snare).\n"
             "  • Side (S)      — only the WIDE content (the L−R difference: reverb, width, stereo synths/pads).\n"
             "  • Mid/Side      — work Mid and Side separately in one instance.\n\n"),
            ("body", "This is the most NUMBER-DRIVEN way to get the three things that are hard to judge by ear. "
             "Three cheat-codes do most of the work:\n\n"),
            ("tip", "  • AIR / SPACE   → on SIDE, a high-shelf boost above ~10 kHz, +2…+3 dB.\n"
             "                    (Opens and widens the top WITHOUT making the centre harsh.)\n"
             "  • NO PORRIDGE   → on MID, cut −3…−4 dB at 200–500 Hz.\n"
             "                    (Clears the muddy centre but keeps the stereo width intact.)\n"
             "  • TIGHT LOW END → on SIDE, high-pass at ~100–150 Hz.\n"
             "                    (Forces the bass/low mids to mono so they stay solid and centred.)\n\n"),
            ("body", "The right-hand 'Selected Instruments' panel prints a ready-made '🎛 Kirchhoff M/S' line per "
             "instrument with the exact frequencies and dB to use — e.g. a string section gets 'SIDE high-shelf "
             "+3 dB @8–14 kHz; MID cut −3 dB @400–800 Hz; high-pass SIDE @100 Hz'. Mono/centre sources (kick, bass, "
             "lead vocal) have almost no Side, so there it just says to work in Stereo or Mid and keep the lows mono.\n\n"),
            ("body", "Note: this is SEPARATE from the '🎚 Pan (DAW)' line. Pan places the whole track in your DAW "
             "mixer (Cubase); Stereo Mode shapes the stereo image INSIDE the EQ. Use both.\n\n"),
            ("h2", "📏 Generic — Range (start–end)\n"),
            ("body", "The original view. Shows a frequency RANGE (e.g. 200–400 Hz) and a generic filter name "
             "(Parametric EQ / High-pass / High-shelf). Best when you 'paint' a region — for example SmartEQ-style "
             "workflows — rather than place a single exact point.\n\n"),
            ("body", "Your choice of engine is remembered between sessions.\n\n"),
            ("h1", "How to use the program\n"),
            ("h2", "Left panel — instrument tabs\n"),
            ("body", "The nine tabs (Vocals, Drums & Percussion, Bass, Guitar, Brass, Winds, Keys, Other, Strings) each contain a set of "
             "instrument cards. Brass, Winds, Keys, Other and Strings are listed A to Z, so the role stands after the instrument: "
             "'Organ (lead)', 'Organ (background)'. The Selected Instruments panel uses the same order, with the Vocals last. "
             "Each card shows:\n\n"),
            ("code", "  Frequency   — the frequency range where the EQ action happens\n"
             "  Zone         — the acoustic characteristic of that range\n"
             "  Filter       — suggested filter type (Parametric EQ, High-pass, etc.)\n"
             "  Type         — BOOST, CUT, TRY, or NEUTRAL\n"
             "  dB           — suggested gain change in decibels\n"
             "  What it does — plain-language description of the effect\n\n"),
            ("h2", "Channel-strip footnotes (read top→bottom = chain order)\n"),
            ("body", "Below the EQ bands each card prints the rest of the channel strip, in the "
             "order the plugins actually sit:\n\n"),
            ("tip", "  🔻 Low cut    — Lowtility high-pass corner + slope (FIRST in the chain).\n"
             "  🗜 Compressor  — starting tier with ratio / attack / release / gain-reduction.\n"
             "                  Sits AFTER the corrective EQ and BEFORE reverb. A limiter is\n"
             "                  NOT a channel insert — it goes on the master / a bus.\n"
             "  🎯 smart:EQ    — Front / Mid / Back priority tier for the resonance-matching.\n"
             "  🦆 Duck        — Trackspacer side-chain target, when the part should yield.\n"
             "  🌫 Reverb      — smart:reverb depth (Dry / Front / Near / Mid / Far) numbers.\n\n"),
            ("body", "Compressor tip: use Cubase's built-in Channel-Strip compressor for routine "
             "levelling (zero plugin load, recallable) and keep Neutron's Compressor for the few "
             "channels that want its visual assistant or multiband (lead vocal, bass, group bus).\n\n"),
            ("h2", "🧭 Planner — one-screen overview (Generate menu)\n"),
            ("body", "Generate → 'Planner (buses & dynamics)' opens a single scrolling table with "
             "every instrument as a row and its whole plan in columns (Low cut · Compressor · "
             "smart:EQ · Reverb · Duck), grouped by family with a suggested GROUP BUS per family "
             "and a bus budget at the bottom. Use it to decide which buses to create without "
             "paging back and forth between the instrument cards.\n\n"),
            ("h2", "Band filter toolbar\n"),
            ("body", "At the top of each instrument tab there is a filter bar with four options: "
             "All, Boost, Cut, and Try. Selecting a filter shows only bands of that type "
             "across all instrument cards in every tab simultaneously. "
             "This makes it easy to, for example, quickly review every cut you need to make "
             "(select Cut) or every enhancement boost (select Boost).\n\n"),
            ("h2", "Frequency Bands Explained\n"),
            ("body", "Click the '📐 Frequency Bands' button in the title bar (or use Help → "
             "Frequency Bands Explained...) to open a dedicated reference window. "
             "It contains:\n\n"),
            ("tip", "  • Six clickable band buttons: Sub-Bass, Bass, Lo-Mid, Midrange, Hi-Mid, Highs\n"
             "  • For each band: characteristics, instruments that live there, and the danger zone\n"
             "  • Corrective, Enhancement, and Creative EQ uses per band\n"
             "  • Additive vs. Subtractive notes specific to that frequency range\n"
             "  • 5 Essential EQ Mixing Tips: cut narrow/boost wide, carve space, HPF use, mixing with ears, context mixing\n"
             "  • Mastering EQ vs. Mixing EQ — scale of moves and approach\n\n"),
            ("body", "The window also contains a permanent section explaining Additive vs. Subtractive EQ "
             "and the three main uses of EQ (Corrective, Enhancement, Creative).\n\n"),
            ("h2", "Colour coding\n"),
            ("body", "  "),
            ("code", "GREEN (BOOST)"),
            ("body", "  — increase this frequency range\n  "),
            ("code", "RED   (CUT)  "),
            ("body", "  — reduce or remove this range\n  "),
            ("code", "BLUE  (TRY)     "),
            ("body", "  — try both directions; depends on the song and material\n  "),
            ("code", "GRAY  (NEUTRAL)"),
            ("body", " — situational; check in context\n\n"),
            ("h2", "Right panel — Selected Instruments\n"),
            ("body", "Tick the checkbox next to any instrument name (or click the instrument name) to add it to the "
             "right-hand summary panel. You can select multiple instruments at once to compare their EQ settings "
             "side by side. This is especially useful when balancing competing instruments, for example:\n\n"),
            ("tip", "  • Kick + Root Bass  →  see how they share 60–100 Hz\n"
             "  • Rhythm Guitar + Organ  →  find overlap in 300–800 Hz\n"
             "  • Piano Riff + Brass  →  manage 2–5 kHz competition\n\n"),
            ("body", "Click 'Clear all' to deselect everything.\n\n"),
            ("body", "Just under the 'Selected Instruments' title you see the song's ROOM SIZE (the Virtual Stage room, "
             "the same on every instance; a hand mark means you forced it with the 🏠 button), and 'SWAM: ...' "
             "when the song has SWAM parts (they have their own room).\n"
             "'☠ Kill MediaBay' ends Steinberg's MediaBay background process (SteinbergMediaBayServer.exe) so "
             "Cubase rebuilds its preset list the next time it starts - use it after generating SWAM / Virtual "
             "Stage presets when they do not show up. Close Cubase first (the button asks if it is still running).\n"
             "'📋 Copy info' puts everything about the song on the clipboard as text (line-up, counts, pairs, "
             "hand placements, both rooms, every SWAM Angle/Distance with the 'moved' reasons, the stage map) - "
             "paste it into a chat when you want someone to check the numbers.\n"
             "In the SWAM room the PAIRS keep their spot: parts without a pair give way first, and the members "
             "of a pair always move together.\n\n"),
            ("body", "Each instrument tab also has an 'All / none' checkbox at the right end of its 'Show bands:' "
             "toolbar. One click ticks (or clears) EVERY instrument in that tab — the whole drum kit, both "
             "basses, all the guitars. When only some of the tab is ticked the box shows a tri-state mark; "
             "clicking it then selects the whole tab.\n\n"),
            ("h2", "The advice knows what is in YOUR song\n"),
            ("body", "As soon as you tick instruments, the program treats that as the line-up and stops giving "
             "advice about instruments that are not there. A song with only bass and piano is no longer told to "
             "'duck the bass under the kick' — instead the bass card says 'No ducking needed — there is no Kick "
             "in this song', and the same goes for the summary, the 🔀 Effects duck view, the Channel Plan and "
             "the Planner. Sentences that name a partner ('split 60–100 Hz with the kick', 'pair with the kick "
             "sidechain') are rewritten the same way.\n\n"),
            ("tip", "  • Nothing ticked = reference mode: every card shows what it WOULD duck under in a full\n"
             "    arrangement, so the cheat sheet still works as a lookup.\n\n"),
            ("h2", "🔎 Focus view — the short face of the window\n"),
            ("body", "The green button in the title bar swaps the window between two layouts, and it opens "
             "in whichever one you left it in. Its label always says what the NEXT click gives you.\n\n"),
            ("tip", "  • 🔎 Focus (the normal one) — ★ Song Variants with 'Instruments in this variant'\n"
             "    on the left, '📋 Selected Instruments' on the right with its three View buttons\n"
             "    (📐 Channel Plan is one click away), the Filter row and the colour legend. 🎪 Stage\n"
             "    map stays in the title bar.\n"
             "  • ⚙ Show everything — adds back the EQ engine row, the 📚 theory tabs, the 🧩 Plugins\n"
             "    tab, ⚠ Conflicts & recommendations at the foot of the variant list, and the\n"
             "    📐 Frequency Bands / 🌫 Reverb Groups / 🎯 smart:EQ Groups / 🗺 Roadmap / 🦻 My rules\n"
             "    buttons.\n\n"),
            ("body", "Nothing is thrown away by the focus view — the panels are only unpacked, with their "
             "ticks, their text and their scroll positions untouched, and every button it hides is also on "
             "the View, Generate or Help menu. The switch is on the View menu too.\n\n"),
            ("h2", "Right-panel views (View: …)\n"),
            ("body", "The 'View:' buttons at the top of the right panel switch it between three layouts. The "
             "active one is highlighted, and your choice IS remembered between runs — as is which section "
             "filters you tick in the Instruments view. Out of the box it opens on 📋 Instruments with "
             "EQ-group + Duck + Reverb ticked:\n\n"),
            ("tip", "  • 📐 Channel Plan — the COMBINED overview: every ticked channel on one scroll\n"
             "    with its smart:EQ priority (Front/Mid/Back), reverb depth, duck source and pan together, so\n"
             "    you can plan the whole song's routing in one glance. Channels that share BOTH the same\n"
             "    smart:EQ group AND the same reverb depth get a coloured ◆ 'stem' badge — they can be bussed\n"
             "    together (one smart:EQ sub-bus + one reverb send). Low-cut and the Kirchhoff EQ table are\n"
             "    per-channel and intentionally LEFT OUT here.\n"
             "  • 📋 Instruments (default) — the full per-instrument summary (the EQ table, M/S, every\n"
             "    footnote). The 'Filter:' row under the buttons narrows every block to just the sections\n"
             "    you tick, so you can scan e.g. only Duck across 20 channels. Reset = show everything.\n"
             "    '⚙ Set & forget' is ONE box standing for four sections at once — Low cut, EQ, Comp.\n"
             "    and Pan — the settings that are dialled in once and then simply stay true.\n"
             "    🌑 SubMass has its own box: it is a FOCUS plug-in you are still dialling, and it\n"
             "    only appears on the kick and the basses anyway, so it is not one of the four.\n"
             "  • 🔀 Effects — sorts ALL instruments by ONE effect at a time (pick Low cut / Duck / Pan /\n"
             "    smart:EQ / smart:reverb at the top).\n\n"),
            ("body", "The 🗺 Roadmap, 🎯 smart:EQ Groups and 🌫 Reverb Groups buttons on the right of the View "
             "row open the planning popups: the routing tree, the group-slot plan with its merge colours, and "
             "the reverb depth buses. All the 'Selected / "
             "All' generation commands (Overview + every preset) now live in the new 'Generate' menu, next to "
             "File and Help.\n\n"),
            ("h2", "The numbers change in a full mix (important!)\n"),
            ("body", "The base value of each band is for the instrument heard on its own. As soon as other instruments "
             "share the spectrum, the right move changes: two parts may fight for 3–5 kHz, a bass and kick may collide "
             "at 60–100 Hz, or a pad may need to duck under the vocal. When you tick more than one instrument, the "
             "summary panel does this FOR you:\n\n"),
            ("tip", "  • The band list shows the EFFECTIVE values — already adjusted for the mix.\n"
             "    Any band that moved is marked with a ✎ and shown in yellow, and the block\n"
             "    header reads '✎ mix-adjusted'.\n"
             "  • ▶ Changed vs base settings — lists exactly what moved (e.g. '3–5 kHz: +3 → −1 dB\n"
             "    (yield to Lead Vocal)' or 'Body: 70 Hz → 90 Hz (let the kick own 60 Hz)').\n"
             "  • ▶ Also do (for this mix) — advice that isn't one number: sidechain, gate, a\n"
             "    bright/warm tonal split, sharing a hook, etc.\n"
             "  • 🎚 Pan (DAW) — where to place the track in your mixer.\n"
             "  • 🎛 Kirchhoff M/S — exact Mid/Side moves (air, space, de-mud) by the numbers\n"
             "    (Kirchhoff engine only). See the Stereo Mode section above.\n\n"),
            ("body", "So just dial in the values shown in the list — they are already the mix-adjusted settings. The "
             "'Changed vs base' lines are only there to tell you WHAT moved and WHY.\n\n"),
            ("h2", "🎛 Generate Kirchhoff presets (.keq)\n"),
            ("body", "In the 'Generate' menu (next to File / Help), two commands write real Kirchhoff-EQ "
             "preset files so you don't have to dial them in by hand:\n\n"),
            ("tip", "  • 🎛 Kirchhoff presets: Selected — one .keq per ticked instrument, using the MIX-ADJUSTED\n"
             "    values (clash-aware). Use this for a song's actual line-up.\n"
             "  • 🎛 Kirchhoff presets: All — the SOLO baseline preset for every instrument (as if each\n"
             "    plays alone / never competes).\n\n"),
            ("body", "Files are written to Helpfiles\\KirchhoffPresets AND copied to your Kirchhoff presets "
             "folder (set it via File ▸ Set Kirchhoff preset folder…; it defaults to "
             "%APPDATA%\\ThreeBodyTech\\KirchhoffEQ\\presets). The name carries NO date — it only says what the "
             "preset is, e.g. 'Bass_ground---Group---kick_organ.keq': the instrument, whether it's a Group "
             "(clashing) or Solo, and which instruments it clashes with. A date in the name moved every month "
             "and left every FX chain pointing at a file that no longer existed.\n\n"),
            ("body", "When a preset is generated again and the file already exists with different contents (the "
             "EQ changed), the new one takes over the SAME name — your songs get the slightly updated preset — "
             "and the old file is kept beside it as '<name>.<date_time>.bak'. Plug-ins and Cubase only list the "
             "real presets, so a .bak never shows up in a preset list; delete the .bak files whenever you like. "
             "Every other preset type (Lowtility, SubMass, Corridor, Omega, PatchWork, Bandwidth, Cascadia, Knock, "
             "smart:reverb) works the same way when you answer Overwrite to the question, and the result window lists what was "
             "replaced. Older presets that still carry a date or '0---' stay where they are; FxChainChecker's "
             "'Fix missing...' repoints a chain from the dated name to the plain one.\n\n"),
            ("body", "Smart de-duplication: a preset is keyed by its EXACT resulting EQ. If a constellation "
             "produces the same EQ for an instrument as one already made, it is REUSED, not duplicated — so "
             "hundreds of songs end up needing only a few dozen presets. A small registry.json tracks them, and "
             "each run also writes a 'song_…' text file listing which preset to load on which track.\n\n"),
            ("body", "The generation options below are in Generate ▸ Options… (they used to be checkboxes on the "
             "right panel):\n\n"),
            ("tip", "  • 'Kirchhoff: bake Mid/Side' — also sets each band's Stereo Mode (air→Side, mud→Mid). It is\n"
             "    OFF by default until the Mid/Side codes are verified in Kirchhoff; turn it on to try.\n"
             "  • 'Kirchhoff: no high-pass (Lowtility does it)' — leaves the High-Pass band OUT of the preset\n"
             "    (because Lowtility does the high-pass first in the chain). The filename gets a\n"
             "    '_(lowtility)' tag, e.g. Lead_vocal_(lowtility)---Solo.keq, so you can keep both a\n"
             "    with-HP and a no-HP version side by side.\n\n"),
            ("tip", "  • 'Kirchhoff: also write Cubase .vstpreset' (ON by default) — ALSO writes each preset as a\n"
             "    Cubase .vstpreset. IMPORTANT: Kirchhoff has TWO separate preset browsers:\n"
             "      – the plain .keq files show in KIRCHHOFF'S OWN preset menu (inside the plugin GUI,\n"
             "        where the factory 'Clean Bass' presets and your default live);\n"
             "      – the .vstpreset files show in CUBASE'S preset selector (the field by the sidechain\n"
             "        button at the top of the plugin) — the same place your hand-made presets are.\n"
             "    So with this ON, the presets appear in BOTH browsers. The .vstpreset wraps the exact\n"
             "    same EQ; it's written to …\\VST3 Presets\\Plugin Alliance\\TBTECH Kirchhoff-EQ (set via\n"
             "    File ▸ Set Kirchhoff .vstpreset folder…). It needs ONE existing .vstpreset there as a\n"
             "    template — you already have your hand-made ones, so it just works.\n\n"),
            ("body", "TIP: verify ONE generated preset loads correctly in Kirchhoff before trusting a big batch.\n\n"),
            ("h2", "🔻 Low cut (Lowtility high-pass) — FIRST in the chain\n"),
            ("body", "Each instrument card shows a '🔻 Low cut (Lowtility)' footnote with a high-pass corner "
             "(Hz) and slope (12/24/36/48 dB/oct). This is the clean-up step:\n\n"),
            ("tip", "  • Put Lowtility FIRST in the channel chain — before Kirchhoff, compression, reverb — so "
             "everything downstream works on an already-clean low end.\n"
             "  • Bass & kick keep their weight (very low corner ~30 Hz); sources with no low end (hi-hat,\n"
             "    cymbals, percussion) are cut high and steep.\n"
             "  • When Lowtility does the high-pass, SKIP Kirchhoff's High-Pass band — don't high-pass the\n"
             "    same range twice.\n"
             "  • On channels = the real per-instrument cut. On sub-buses you normally DON'T high-pass again "
             "(redundant); at most a very low ~20–30 Hz subsonic cut on the mix/master.\n\n"),
            ("body", "Generate Lowtility presets: the Generate ▸ '🔻 Lowtility presets: Selected / All' commands write a "
             "Venomode Lowtility 2 .vstpreset per instrument with the EXACT low-cut corner Hz + slope from the "
             "chart (named '<Label>---Lowcut', no date). They appear in CUBASE's preset selector. It needs ONE "
             "existing Lowtility .vstpreset in …\\VST3 Presets\\Venomode\\Lowtility 2 as a template (set via "
             "File ▸ Set Lowtility preset folder…) — you already have your own, so it just works. Only the low "
             "cut (frequencycut + slope) is set; the width module etc. stay as the template's.\n\n"),
            ("h2", "🎯 smart:EQ group placement (Front / Mid / Back)\n"),
            ("body", "If you use Sonible smart:EQ 4's cross-channel 'group' feature, it resolves masking "
             "automatically — but it needs to know WHO WINS when two members overlap. That is a priority "
             "ranking, and each instrument card (and the right panel) prints a ready-made one:\n\n"),
            ("tip", "  • ▲ FRONT — high priority: it stays present; others yield to it (lead vocal, kick,\n"
             "    snare, lead guitar, root bass).\n"
             "  • ■ MID   — supporting layer (rhythm guitars, riffs, sections, toms, hats).\n"
             "  • ▼ BACK  — low priority: carved to make room (pads, beds, background vocals, organ).\n\n"),
            ("body", "Rank the group members in smart:EQ in that order (Front highest). This is a discrete "
             "ARRANGEMENT decision — a role — which is why the cheat sheet can give it exactly (unlike trying "
             "to guess a smart:EQ curve, which is an AI black box).\n\n"),
            ("body", "smart:EQ 4's group holds at most 10 channels. The '🎯 smart:EQ Groups' button (next to "
             "the Preset buttons) opens an overview of your selected instruments laid out Front / Mid / Back, "
             "and a suggested SUB-BUS plan to stay within the 10 slots:\n\n"),
            ("tip", "  • Instruments sharing a family AND a tier go on one sub-bus = one slot (e.g. both\n"
             "    guitars together; kick + snare together).\n"
             "  • Each bass keeps its OWN bus (their low-end placement differs).\n"
             "  • Put each sub-bus into the group and rank them Front → Back. If the plan shows more than\n"
             "    10 buses, merge same-tier beds across families (e.g. all BACK pads/keys/strings on one\n"
             "    'Beds' bus) until you reach 10.\n\n"),
            ("body", "Three things it is NOT — handle these separately:\n\n"),
            ("tip", "  • NOT ducking — see the '🦆 Duck under …' footnote below.\n"
             "  • NOT panning. Where it sits left/right is the '🎚 Pan (DAW)' line; depth (front/back in the\n"
             "    image) is reverb/delay send amount. Both are stock in Cubase.\n"
             "  • NOT Mid/Side. That is the '🎛 Kirchhoff M/S' line (inside the EQ).\n\n"),
            ("h2", "🦆 Ducking (Trackspacer / Kickstart) — making parts take turns in TIME\n"),
            ("body", "smart:EQ group unmasks in the SPECTRUM, but it does not fix two parts colliding in TIME "
             "(e.g. kick + bass both hitting 60–100 Hz). For that you duck. Instruments that benefit show a "
             "'🦆 Duck under …' footnote naming the source to side-chain and the settings, for the two tools "
             "you own:\n\n"),
            ("tip", "  • Trackspacer (Wavesfactory) — a reactive EQ. Put it on the track that should YIELD,\n"
             "    feed the dominant part to its side-chain, and it carves out exactly those frequencies\n"
             "    only while that part plays. Its LOW-CUT/HIGH-CUT sliders limit the band it works in\n"
             "    (default = full range). For kick↔bass, pull HIGH-CUT down to ~150 Hz so only the lows\n"
             "    duck. The most surgical, transparent option — works for kick AND vocal side-chains.\n"
             "  • Kickstart (Cableguys/N. Romero) — a tempo-synced VOLUME duck (a beat-locked curve, no\n"
             "    routing). Quick, but only musical when the kick is steady on the beat, and it ducks the\n"
             "    whole level (broadband). Good for kick↔bass pumping; NOT for vocal side-chains (a voice\n"
             "    isn't metronomic).\n\n"),
            ("body", "Rule of thumb: duck-under-KICK → Trackspacer (high-cut to the lows) OR Kickstart; "
             "duck-under-VOCAL → Trackspacer only.\n\n"),
            ("tip", "  ⚠ START GENTLE. The Amounts in the footnotes are intentionally LOW (~10–20%).\n"
             "    Ducking is much easier to over-do than under-do: begin at the LOW end of the range\n"
             "    and raise it only until you JUST notice the masked part open up. If the ducked part\n"
             "    (a guitar, the bass) seems to DISAPPEAR or pump, you have gone too far — pull the\n"
             "    Amount back down. A value of 30–40% will usually swallow the part whole.\n\n"),
            ("h2", "🌫 Depth (front/back via reverb send)\n"),
            ("body", "Where a part sits front-to-back is set by HOW MUCH reverb it sends — not by EQ or by the "
             "smart:EQ group. The '🌫 Depth (reverb send)' footnote gives each instrument a level: DRY → NEAR → "
             "MID → FAR. Least-hassle workflow:\n\n"),
            ("tip", "  • Put ONE reverb on an FX/send channel (Sonible smart:reverb is ideal — it auto-tunes the\n"
             "    room's character to the material; stock REVerence/RoomWorks also work). Vary each track's\n"
             "    SEND by its Depth tier; do not insert a separate reverb per track.\n"
             "  • DRY = no/almost no send (kick, bass — reverb there only muddies the low end).\n"
             "  • NEAR = light send (snare, hats, rhythm parts).\n"
             "  • MID  = medium send (keys, sections, leads).\n"
             "  • FAR  = heavy send (pads, choir, string beds — they sit deepest).\n"
             "  • Leads can take reverb yet stay up front if you add PRE-DELAY (~60–120 ms) so the dry\n"
             "    transient lands first and the words/notes stay clear.\n\n"),
            ("body", "smart:reverb auto-makes the reverb SOUND good; the Depth tier is the part it can't decide "
             "for you — how far each track sits. That's the arrangement call, so the cheat sheet gives it.\n\n"),
            ("body", "With Sonible smart:reverb specifically: Distance/Size/Width and the Room/Hall/Spring/Plate "
             "character are PER INSTANCE, so each instrument's depth is its own DISTANCE knob (FRONT ≈ 15 for the "
             "lead vocal, NEAR ≈ 25, MID ≈ 50, FAR ≈ 78). Its 'group' is only a 7-channel container for cross-channel wash "
             "management. The '🌫 Reverb Groups' button (next to smart:EQ Groups) gives the EFFICIENT plan: ONE "
             "reverb bus per depth (Near/Mid/Far) — same-depth tracks share one instance, so 2–3 buses cover the "
             "whole mix (no 7-channel worry). Route each track to its depth bus (Rhythm Gtr=Near, Chord Gtr=Mid "
             "go to different buses, not a reverb per channel). Kick & bass stay DRY. Leads: add PRE-DELAY "
             "~60–120 ms so they stay up front despite the reverb.\n\n"),
            ("h2", "🌫 Generate smart:reverb presets\n"),
            ("body", "In the Generate menu, two '🌫 smart:reverb presets' commands write real "
             ".vstpreset files for Sonible smart:reverb 2. smart:reverb is an AI plugin, so the program does "
             "NOT invent its state from scratch — it takes ONE preset YOU made by ear as a SEED and changes "
             "ONLY the three knobs it legitimately knows:\n\n"),
            ("tip", "  • EXACT Distance / Size / Width for each depth tier (Front≈15, Near≈25, Mid≈50, Far≈78),\n"
             "    patched straight into your seed. Everything else — the learned reverb profile and the\n"
             "    Room/Hall character — is copied from your seed unchanged. DRY parts (kick, bass) are skipped.\n"
             "  • Per instrument (default): one '0---<name>.vstpreset' each.\n"
             "  • 'Per tier (buses)' checkbox (recommended): one '0---Reverb-FRONT/NEAR/MID/FAR' instead —\n"
             "    a few files for the bus workflow (see below). The recipe still maps each track to its tier.\n\n"),
            ("body", "Set the folder via File ▸ 'Set smart:reverb preset folder…' (defaults to "
             "Documents\\VST3 Presets\\sonible\\smartReverb2). Make ONE reverb preset by ear in the plugin and "
             "save it there as your seed (a name with 'lead'/'vocal' is picked automatically, else the newest). "
             "A text recipe + backup copies go to Helpfiles\\SoniblePresets so a folder wipe can't lose them.\n\n"),
            ("tip", "  • DON'T use smart:reverb's internal GROUP with these — every preset is a clone of one\n"
             "    instance, so the plugin can't tell them apart (the group flickers / 'add to group' is empty).\n"
             "    You don't need groups: put smart:reverb on 2–3 depth BUSES (Near/Mid/Far), load the matching\n"
             "    preset on each, and SEND each track to its depth bus. That is the efficient model anyway.\n"
             "  • If you DO want grouping/linking, make your seed on a fresh smart:reverb that is NOT in any\n"
             "    group before you save it (otherwise the stale membership is copied to every preset).\n"
             "  • VERIFY ONCE: open one preset and confirm Distance / Size / Width read the report's numbers.\n"
             "  • If a slot already exists you are asked whether to overwrite it.\n\n"),
            ("h2", "🎯 smart:EQ — add it MANUALLY, don't use a preset\n"),
            ("body", "The program does NOT generate smart:EQ presets. A cloned smart:EQ preset drags the seed's "
             "NAME and its learned EQ curve onto every track (confusing, and you get an EQ you didn't ask for). "
             "Instead:\n\n"),
            ("tip", "  • Add smart:EQ manually on the track — you get the right name and a FLAT EQ.\n"
             "  • Run its Learn/analyse so it actually does something (a flat, un-analysed smart:EQ does\n"
             "    nothing — don't leave it flat).\n"
             "  • Put competing tracks in a smart:EQ GROUP and rank them by the Front/Mid/Back tier the\n"
             "    program shows (Front wins, Back yields). That GROUP unmasking is smart:EQ's real strength.\n"
             "  • Kirchhoff + smart:EQ is fine and complementary: keep Kirchhoff (your exact cheat-sheet bands)\n"
             "    as the tonal/corrective layer; let smart:EQ handle adaptive cross-track unmasking. If that\n"
             "    feels like too much, Kirchhoff + Trackspacer (for ducking) is already a complete chain —\n"
             "    smart:EQ is optional polish, not required.\n\n"),
            ("h2", "🎚 Pan terms — 'Spread' and 'Wide L+R' explained\n"),
            ("body", "Most pan suggestions are a simple left–right position. Two of them are not a single knob "
             "setting, so here is exactly what they mean:\n\n"),
            ("tip", "  • SPREAD — used for ONE kit piece miked with several mics (the TOMS). Pan each mic where\n"
             "    that drum physically sits: floor tom hard-ish LEFT, rack toms moving toward RIGHT — a\n"
             "    left-to-right sweep across the drums. (Yes: floor tom = left, the other toms = right.)\n"
             "  • WIDE L+R — used for a STEREO PAIR (overheads / room mics): its two channels go hard LEFT\n"
             "    and hard RIGHT, giving the kit full stereo width instead of one point in the middle.\n"
             "  • WIDE STEREO — a naturally stereo source (pad, choir, doubled parts): open it well out to\n"
             "    both sides rather than placing it at one spot.\n"
             "  • OFF-CENTRE — nudged a little to one side (~20–40%, not hard) to free the centre for the\n"
             "    lead vocal, kick, snare and bass.\n\n"),
            ("body", "The same glossary appears under the 🎚 Pan list in the Effect-sorting view.\n\n"),
            ("h2", "★ Song Variants tab\n"),
            ("body", "The first tab lets you save named 'song variants' — the set of instruments a particular song "
             "uses together. Tick [✓] for each instrument that is in the mix, and set the [#] count next to it for "
             "HOW MANY of that part you have (e.g. two chord guitars, three plopp-synths). A count above 1 adds advice: "
             "duplicates of the same instrument should be panned apart and given slightly different tone / reverb so they "
             "widen instead of stacking on one spot. The tab lists band clashes and targeted tips for THAT combination, "
             "so you can see how the EQ should differ when a different mix of instruments is playing. New / Save / "
             "Save As / Rename / Duplicate / Delete manage your variants, and they are stored between sessions.\n\n"),
            ("h2", "⛓ Pair and Prio — parts that share a level\n"),
            ("body", "Two small boxes at the far right of every row. The program ranks each instrument on its own "
             "(a viola is a background part, a violin is Mid), but in a song two different parts can do ONE job: "
             "a chord guitar and a background organ playing a fairly straight line as a carpet, or a violin and a "
             "viola playing together. Give them the same PAIR number (1-9; 0 = no pair).\n\n"),
            ("code", "  Pair 1 + Pair 1, same Prio    →  one level: both take the same smart:EQ priority and\n"
                     "                                   reverb depth (the front-most of them), and on the\n"
                     "                                   Virtual Stage two of them become Siblings (a matched\n"
                     "                                   pair, one each side)\n"
                     "  Pair 1 + Pair 1, higher Prio  →  the owner gives its tier to the other, and on the stage\n"
                     "                                   the owner is a Feature and the other a Support\n"
                     "  a dry part (bass, kick)       →  keeps its own dry reverb, whoever it is paired with\n"
                     "  ✋ Stage by hand              →  always wins over what a pair works out\n\n"),
            ("body", "Prio only means something inside a pair (9 = owns it). Pairs act on the parts that are ticked, "
             "wait for Save / ⟳ Update like a tick or a count, and are saved with "
             "the song. A paired part says so in its smart:EQ and reverb notes (⛓). Putting a FRONT part such as the "
             "lead vocal or the bass in a pair pulls the others up to FRONT - pair parts that are meant to be equals.\n\n"),
            ("h2", "⟳ Update · ↩ Reset · ⚓ Ground\n"),
            ("body", "The top row is, in order: New · Rename · Duplicate · Delete · Save As… · Save · ⟳ Update. Save writes "
             "the variant to disk AND updates the right-hand panel; ⟳ Update does the same update but does NOT write the "
             "file (closing the program still saves the variant, as before). Below it, ↩ Reset and ⚓ Ground act on the "
             "LINE-UP rather than on the list of variants.\n\n"),
            ("tip", "  • The right-hand panel redraws only on Save or ⟳ Update (ticks, counts, and Pair / Prio boxes all\n"
             "    wait). After a redraw it scrolls to the instrument you changed last - wherever you changed it - and\n"
             "    it never leaves an empty area when the list gets shorter (a filter, or another view).\n"
             "  • ⟳ Update — the left side is a scratch pad. Tick, untick and change counts as much as\n"
             "    you like; the right-hand panel keeps what it has until you click this, and then it takes the\n"
             "    lot in at once. The button turns amber and counts what is waiting, and an amber line at the\n"
             "    top of the panel says the same thing — click either one. The RIGHT side never waits: change\n"
             "    something there and it goes in immediately, so you pick per action which way round you want.\n"
             "    View ▸ ⟳ Update button turns the whole thing off and puts the old live behaviour back.\n"
             "  • ↩ Reset — a BLANK left side: every box off, every count back to 1. A clean sheet to\n"
             "    build the next song on. File ▸ Clear all selections and the panel’s own Clear all do\n"
             "    exactly the same thing — same code, so they cannot drift apart.\n"
             "    It only ASKS when it cannot be taken back. With ⟳ Update holding, nothing is lost: the\n"
             "    panel still shows the line-up and the variant on disk still holds it, so clicking that\n"
             "    variant in the list on the left loads the whole thing straight back. With the hold off it\n"
             "    is written at once, and that is the one case it asks first.\n"
             "  • ⚓ Ground — the line-up you always come back to. Shift-click the button (or File ▸ Set the\n"
             "    line-up on the left as my Ground) saves the one you have; clicking it brings that one back.\n"
             "    It is a SNAPSHOT, so renaming or deleting the variant it came from cannot empty it.\n"
             "  • Nothing is lost by not clicking Update: whatever is still waiting is written into the\n"
             "    variant when you close the program, exactly as it always was — with one exception. An\n"
             "    EMPTY left side is never saved over a variant that has a line-up, so ↩ Reset followed by\n"
             "    closing the program cannot wipe it. Emptying a variant on purpose is one click on\n"
             "    ⟳ Update.\n\n"),
            ("h2", "✋ Virtual Stage by hand — role, side and counterpoles\n"),
            ("body", "View ▸ ✋ Virtual Stage by hand (also a button in the 🎪 Stage map, and the window has a "
             "🎪 Stage map… button to go back). The whole page scrolls with the mouse wheel. Everything on that "
             "stage is worked out from the line-up, and that is right for nearly all of it — but three decisions are "
             "not in the line-up at all, they are in the ARRANGEMENT, and no amount of looking at the channels can "
             "find them:\n\n"),
            ("tip", "  • Role — what does this part DO in the song? A piano riff can be the hook or the bed under\n"
             "    it, and the channel looks identical both ways. Nine steps: LEAD (furthest forward, never\n"
             "    gives way) · CO-LEAD · FEATURE · SUPPORT · DOUBLE · HARMONY · BED · TEXTURE (furthest back,\n"
             "    first to yield). Each is a Distance step and a place in the 'who yields' queue.\n"
             "  • CO-LEAD is for EQUAL partners - a duet, two main vocals, or copies #1 and #2 of one part: they\n"
             "    take opposite sides, close to the middle. DOUBLE is drawn halfway in towards the middle, just\n"
             "    behind the part it doubles. HARMONY sits behind the double.\n"
             "  • SIBLINGS — a matched stereo pair of two DIFFERENT channels (Violin + Viola): one on each side of\n"
             "    Centre as a mirror image, same Distance. Role is not read - neither has to be the Lead. If one of\n"
             "    them is already placed by hand, it stays and the other takes the mirror spot. Opposite of is the\n"
             "    looser cousin: just not the same side. A channel has one or the other.\n"
             "  • Same Role = equal focus. Two copies of one part (2 x Guitar Rhythm, 2 x Cello) that matter\n"
             "    equally: leave both on Auto. They already stand one Left, one Right, equally far out; with\n"
             "    exactly ONE other part in the family (2 x Rhythm + 1 Chord) that one takes the Centre. Eight\n"
             "    equally important parts: all eight the same Role. Lead is for ONE part at a time.\n"
             "  • Guitar and Guitar R: Role says which of them carries the song at the moment, Opposite of\n"
             "    keeps them on opposite sides. Flip the Role when the arrangement flips.\n"
             "  • The basses are not listed: Virtual Stage stays OFF a bass. A second bass (a grit layer) is\n"
             "    the 'x2 on a bass' option on the bass's own card.\n"
             "  • Side — Left / Right / Centre, for when there is a reason nothing in a mix can see.\n"
             "  • Opposite of — two parts that ANSWER each other must not both end up on the right. Set it on\n"
             "    either one of the two; it means both, and it appears on both rows.\n"
             "  • Everything you set writes its own line on the channel, starting with a hand and the word YOU,\n"
             "    and those lines are never hidden with the why-lines — the sheet must always be able to tell\n"
             "    your numbers from its own.\n"
             "  • A hand-placed channel WINS a collision (the engine moves the other one). When two hand-placed\n"
             "    channels collide, NEITHER moves and both say so: undoing a decision you made on purpose is the\n"
             "    one thing this is not allowed to do.\n"
             "  • The drum kit and the channels Virtual Stage stays OFF are not listed. The kit is laid out as\n"
             "    ONE object, and a position on a channel that is switched off would contradict the reason.\n"
             "  • Hand placements belong to the SONG, so they are saved with the variant — and they go in at\n"
             "    once, because a dialog is a decision, not a tick you are still thinking about.\n\n"),
            ("h2", "🧩 Plugins tab — your personal plugin library\n"),
            ("body", "The second tab is a GROW-OVER-TIME library of the plugins you own or want to try, so the "
             "program can remind you what you have (it's easy to forget the names), show the INSERT ORDER they "
             "sit in, and suggest one when a need comes up. Nothing here changes your audio — it's your notebook.\n\n"),
            ("tip", "  • Tag each plugin: ♥ favourite · 👍 like · 👎 dislike · · untested. A 👎 drops it out of\n"
             "    the suggestions and the inserts map, so the program offers other options instead.\n"
             "  • The [all]/[many]/[few] tag = on how many channels it sits. Click it to cycle. It drives the\n"
             "    ()/(()) notation in the inserts map: plain = (almost) every channel, (Name) = many, ((Name)) = few.\n"
             "  • ➕ Add plugin — record one of your own (name, vendor, kind, scope, like/dislike, link, note).\n"
             "    ✎ edits a row, 🗑 deletes one you added (built-in seed entries can't be deleted, only re-tagged).\n"
             "  • 🔗 opens the plugin's website. 'Show:' filters by status or kind.\n"
             "  • The library was seeded with your own lists (favourites, the mastering tools, and the big "
             "'want to test' list with links). Your tags and edits are always kept and saved automatically.\n\n"),
            ("h2", "🧩 Insert order map (in the 📐 Channel Plan)\n"),
            ("body", "The Channel Plan view shows an 'Insert order' map: your core tools + everything you marked "
             "♥/👍, sorted top-to-bottom the way they sit on a channel strip — e.g. Lowtility → Kirchhoff → "
             "(smart:EQ) → ((Trackspacer)) → (smart:reverb) — plus any of your other liked plugins in their right "
             "place, with the ()/(()) scope notation. Sends (delay/reverb) are shown at the end; auto-mastering "
             "tools (limiters/comps you only use on the master) are listed separately on a 'master bus only' line. "
             "Low-cut and the Kirchhoff EQ are listed in the order but their exact numbers stay in the cards / "
             "Instruments view.\n\n"),
            ("h2", "🔎 'Try this' suggestions (in the 📐 Channel Plan)\n"),
            ("body", "Below the channels, the Channel Plan offers a few optional ideas based on what you ticked — "
             "e.g. with a lead/hook it suggests trying a DELAY; with a pad, a WIDTH tool; with guitars, a little "
             "SATURATION. Each idea gives a RANGE and what to listen for (it never guesses exact numbers): what "
             "'good' sounds like and what 'too much' sounds like. It then names YOUR plugins of that kind (skipping "
             "any you 👎). If you have none of that kind, it says so — that's the cue to add or audition one. "
             "These are ideas, never rules.\n\n"),
            ("h2", "Tip boxes\n"),
            ("body", "Each instrument card has a 💡 Tip section at the bottom with practical mixing advice: "
             "sidechain suggestions, common pitfalls, and context-specific notes.\n\n"),
            ("h2", "Settings are saved automatically\n"),
            ("body", "The program remembers which instruments you had checked, the window size, the divider position, "
             "and the active tab. These are restored the next time you launch the program.\n\n"),
            ("h1", "General EQ principles for rock\n"),
            ("body",
             "• High-pass everything that doesn't need low end — guitars, overheads, winds, percussion.\n"
             "• The mud zone (200–500 Hz) is where most instruments compete. Cut carefully in that range.\n"
             "• Kick and bass share 60–100 Hz — sidechain-compress the bass against the kick.\n"
             "• Piano riffs and vocals compete in 1–4 kHz — automate the riff up between vocal phrases.\n"
             "• Organ and rhythm guitar share 200–800 Hz — pan them apart and use different EQ curves.\n"
             "• Filler or melody is a ROLE, and six pairs of cards say which: Organ (background) /\n"
             "  Organ (lead), Brass / Brass (lead), String Section / Strings (lead), Accordion /\n"
             "  Accordion (lead), Flute (background) / Flute, Violin (background) / Violin. They want opposite\n"
             "  EQ — the bed keeps the body, the width and the air, the lead trades all three for\n"
             "  the 1–3 kHz note core. Never mix a melody with the pad recipe; it is the commonest\n"
             "  reason a tune is loud and still inaudible. Note the last two: a Flute or Violin card\n"
             "  is already a SOLO card, so there the BED is the one with the separate name.\n"
             "• dB suggestions are starting points only. Always use your ears in the actual mix.\n\n"),
        ]

        txt.config(state="normal")
        for tag, content in HELP_TEXT:
            txt.insert("end", content, tag)
        txt.config(state="disabled")

        tk.Button(top, text="Close (Esc)",
                  bg=C_BTN, fg=C_BTN_FG,   # change: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_NORMAL, relief="flat", padx=14, pady=4,
                  command=top.destroy).pack(pady=(0, 10))

    # ---- ABOUT --------------------------------------------------------------

    def _show_about(self):
        import webbrowser

        top = tk.Toplevel(self.root)
        top.title(f"About {APP_NAME}")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())

        # Header
        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🎛", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text=APP_NAME,
                 bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(hdr, text="EQ reference guide for rock music production",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20)

        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

        DOC_URL = (
            "https://docs.google.com/document/d/"
            "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")

        doc_lbl = tk.Label(top, text="📄  View documentation",
                           bg=C_BG3, fg=C_ACCENT,
                           font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
        doc_lbl.pack(pady=(6, 2))
        doc_lbl.bind("<Button-1>", lambda e: open_url(DOC_URL))
        doc_lbl.bind("<Enter>",    lambda e: doc_lbl.configure(fg="#b4d4ff"))
        doc_lbl.bind("<Leave>",    lambda e: doc_lbl.configure(fg=C_ACCENT))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(14, 0))

        tk.Label(top, text="☕  If you enjoy this program, a small gift is always welcome!",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate_frame = tk.Frame(top, bg="#252535", padx=16, pady=10)
        donate_frame.pack(fill="x", padx=20, pady=(0, 6))

        REVOLUT_URL = "https://revolut.me/lars72oeh"
        PAYPAL_URL  = "https://paypal.me/issusbarn"
        WISE_URL    = "https://wise.com/pay/me/larsdenniso"

        for label, url, icon in [
            ("Revolut", REVOLUT_URL, "💳"),
            ("PayPal",  PAYPAL_URL,  "🅿"),
            ("Wise",    WISE_URL,    "🌍"),
        ]:
            btn = tk.Label(donate_frame, text=f"{icon}  {label}",
                           bg="#252535", fg=C_ACCENT,
                           font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
            btn.pack(pady=2)
            btn.bind("<Button-1>", lambda e, u=url: open_url(u))
            btn.bind("<Enter>",    lambda e, b=btn: b.configure(fg="#b4d4ff"))
            btn.bind("<Leave>",    lambda e, b=btn: b.configure(fg=C_ACCENT))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(10, 0))

        tk.Label(top, text=f"Version {APP_VERSION}",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(pady=(8, 0))

        tk.Button(top, text="Close (Esc)",
                  bg=C_BTN, fg=C_BTN_FG,   # change: C_BTN = "#0f3460"
                  activebackground=C_BG, activeforeground=C_FG,
                  font=FONT_NORMAL, relief="flat", padx=14, pady=4,
                  command=top.destroy).pack(pady=(10, 14))


# *************** DEL 06 - CRASH CATCHER & MAIN ******************************

def main():
    global SETTINGS_FILE

    base = get_base_dir()
    cfg_dir = get_helpfiles_dir("EQ_CheatSheet")
    SETTINGS_FILE = os.path.join(cfg_dir, "settings.json")

    # Tidy old top-level preset folders into Helpfiles/Presets/ (runs once).
    migrate_helpfiles_presets()

    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "LarsIssu.EQ_CheatSheet.1")
    except Exception:
        pass

    root = tk.Tk()
    root.title(APP_NAME)

    app = EQApp(root)

    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()


def crash_handler():
    """Top-level crash catcher — writes log and shows a message box."""
    try:
        main()
    except Exception:
        tb = traceback.format_exc()
        write_crash_log(tb)
        try:
            import tkinter.messagebox as mb
            mb.showerror(
                "EQ Cheat Sheet — Fatal Error",
                f"An unexpected error occurred.\n\n{tb}\n\n"
                f"A crash log has been written to:\n{get_log_path()}"
            )
        except Exception:
            print("FATAL:", tb)
        sys.exit(1)


if __name__ == "__main__":
    crash_handler()
