# -*- coding: utf-8 -*-
# =============================================================================
# ALLT I PROGRAMMET SKA ALLTID VARA PA ENGELSKA - ALDRIG SVENSKA!
# ALL TEXT IN THIS PROGRAM MUST ALWAYS BE IN ENGLISH - NEVER SWEDISH!
# =============================================================================
#
#   MusicSite  -  build a self-hosted music page from a shared cloud folder
#   Created by  Lars "Issu" Olsson
#
#   WHAT IT DOES
#   ------------
#   You keep your music in ONE shared main folder in the cloud (Google Drive,
#   an S3 bucket, a plain web folder, or a local disk folder).  Inside it you
#   make sub-folders:
#
#       <main folder>/MP3/     Dagen_utan_morgon.mp3
#       <main folder>/Cover/   Dagen_utan_morgon.jpg
#       <main folder>/Text/    Dagen_utan_morgon.txt      (optional lyrics)
#
#   MusicSite reads the main folder, matches the files by NAME (not by link),
#   and writes ONE self-contained index.html with a real audio player.
#   You upload that single file to your own server.  Done.
#
#   Moving to another host later = copy the MP3/ Cover/ Text/ folders there,
#   paste the new main address, press Fetch, press Build, re-upload one file.
#
# =============================================================================
# ToDo  (what this program does / what is planned)
# -----------------------------------------------------------------------------
#   DONE  Source drivers: Google Drive share link, HTTP folder, S3-compatible
#         bucket, local disk folder.
#   DONE  Google Drive listing with NO API key (embeddedfolderview), plus an
#         optional API key path for large / stubborn folders.
#   DONE  Name matching audio <-> cover <-> lyrics, with fuzzy fallback and a
#         report of every guess it had to make.
#   DONE  Track editor: title, artist, year, description, lyrics, hide, order.
#   DONE  Site editor: title, artist, tagline, about, accent colour, theme,
#         footer links, downloads on/off, lyrics on/off, search on/off.
#   DONE  HTML generator: one self-contained page, sticky player, keyboard
#         control, deep links (#track), Media Session, light/dark/auto.
#   DONE  Optional "download covers into the output folder" for hosts that
#         throttle image hotlinking.
#   DONE  Project save/load (.msite json) with automatic timestamped .bak.
#   DONE  Settings remembered, window geometry remembered.
#   DONE  Crash catcher + diagnostics window + log file.
#   DONE  Help and About, both closable with ESC.
#   DONE  Upload check (tab 5): the folders on THIS disk against the ones in
#         the cloud - what is new, what has changed, what is only online.
#         A group may have SEVERAL local folders (a fresh export lands where
#         you were working, not in the tidy library folder); the newer copy
#         of a doubled name wins and the report says so.  Songs, covers and
#         lyrics are always compared - the three "Hide from the list" boxes
#         only decide what is worth looking at.
#   DONE  The cloud's answers are remembered (Helpfiles/MusicSite/
#         cloud_memory.json), so a comparison of 550 files went from 74
#         seconds to 2.  The listing is still read fresh every time; only
#         the one-question-per-file part is remembered, and a file whose id
#         or day changed asks about itself.  "Clean comparison" (Shift+F6)
#         asks about every file again; everything copied to Temp_to_drive is
#         marked as on its way up and re-asked until it appears.
#         Exact size and time from Google Drive with no API key at all
#         (HEAD of the download link), and everything that has to go up is
#         copied into Temp_to_drive/MP3, /Cover, /Text ready to drag over.
#   DONE  Words out of his OWN lyric files (tab 1, "Lyric file(s) here"):
#         several songs per file, split by a line of dashes, found by their
#         heading.  Chord rows in every shape he writes them, the running
#         order and his private notes - including everything under an
#         (ORIGINAL) marker, which is the old version of the words - are
#         never published.  "Check" shows every dropped line with a reason.
#         Measured on his own 431-song file: 3 658 chord rows, 61 running
#         orders and 319 notes dropped, and all 71 songs on his page found
#         their words.
#   DONE  Versions of a song share the original's cover: automatically when
#         the name is the original's plus a tail in brackets, and by hand
#         with "Share cover" on the Tracks tab (mark several rows).  His 71
#         tracks went from 7 without a cover to none.
#   DONE  A file already lying in Temp_to_drive is not copied there again -
#         it gets its own status, WAITING, is not ticked, and survives
#         "empty Temp_to_drive first" until it has actually gone up.
#   DONE  "Choose lines" on the Tracks tab: the song line by line, ticked =
#         published, with the reason beside every dropped row.  His picks
#         are kept per track (lyrics_keep / lyrics_drop, matched on the text
#         of the line) and applied again after every Fetch, so correcting a
#         rule is a click and it stays corrected.
#   DONE  Preview opens in HIS browser.  A file:/// address matches nothing
#         in DefaultHub's table (no rule owns .html), so it used to fall
#         through to Windows' default browser; open_in_browser() asks the
#         table what opens a LINK and hands the page to that program.
#   DONE  "Lyrics by" per track (Tracks tab), and a name in front of a lyric
#         file - "Malin Östh | ...\0---Malins.txt" - credits every song out
#         of that file automatically.  The page prints "Words: <name>" under
#         the title, and a name typed by hand is never overwritten.
#   DONE  Two files of the same name in the cloud (Drive ADDS a copy instead
#         of replacing): the newer one is used on the page and in the
#         comparison, and both places say the old copy should be deleted.
#         A file uploaded today is listed as "9:44 am" - read as today at
#         that minute, so a fresh upload is recognised at once.
#   DONE  "I have uploaded these" - a half-tick for files he knows are up
#         there although the program cannot see it.  They stop nagging, but
#         the mark holds only while the file here is unchanged, a name that
#         is not in the cloud folder at all is exposed at once, and "Clean
#         comparison" checks every mark for real and says out loud which
#         ones were wrong.  A mark cleans itself away once the cloud agrees.
#   DONE  The words are read from the lyric files when a PROJECT IS OPENED,
#         not only on Fetch.  A project saved before the files were pointed
#         at used to open with empty Words/text boxes and no explanation
#         (his: "innan sista versionen kom lyrics upp ... nu är de borta").
#         71 of 71 filled in 0.1 s, and it never touches what he typed.
#   DONE  A box at the bottom of the page for his own words about what the
#         music costs and how to pay for it if you want to - heading, text
#         (paragraphs) and payment links, all editable on the Site tab, plus
#         a switch for the "Built with MusicSite" line.  Revolut/PayPal/Wise
#         are only a starting point, exactly as in the About dialog.
#         About/footer text is rendered as paragraphs now, not one lump.
#   DONE  The Tracks editor saves into the track it was LOADED for, not
#         into whichever row is selected at that moment.  Clicking another
#         row used to fire the old box's FocusOut AFTER the selection had
#         already moved, so the old track's title, artist, words and
#         "Lyrics by" were written into the row just clicked (Avfall came
#         out as a second Badkar).  Changing row now commits the old one
#         first, and "dirty" is only set when something really changed.
#   DONE  A lyric file that has been MOVED is found again by its name
#         (Lyrics\\ became Text\\ and every song lost its words without a
#         word of explanation).  The program looks beside the old place,
#         in the 'Local folder(s)' and in their Text / Lyrics sub-folders,
#         and rewrites the line in the box for you.
#   DONE  A title that is a copy of another track's (the old wrong-row bug)
#         is put back to the file's own name on the next Fetch, and the
#         Tracks tab has "Title from file" for doing it by hand.
#   DONE  After a Fetch the tracks that are no longer in the cloud are named
#         in a message, not only in the report.
#   DONE  File > New project keeps your folders (addresses, lyric files,
#         local folders, Temp_to_drive) so you only edit what changed, and
#         File > Delete project removes the project file - a copy goes to
#         Backups first.  The folders are also remembered between runs.
#   DONE  A song that stands in TWO lyric files (his big all-songs file
#         and a writer's own file) takes the words and the credit from the
#         file that HAS a writer - before, the first file in the box won
#         and "Bara pa latsas" was never credited to Malin.
#   DONE  ONE credits file for everybody who helped (Source tab, "Credits
#         file"): one line per credit,  Song title | Name, role  - e.g.
#         "Bara på låtsas | Malin Östh, lyrics" or "Besk glögg | Mikael
#         Swahn, gitarr".  Role "lyrics" is the "Words: ..." line under
#         the title; any other role is printed as "role: name".  It is the
#         ONLY place credits come from (a hand-typed "Lyrics by" still
#         wins), read when the project opens, on Fetch and on "Read".
#         "Read" also lists every line that matches no song on the page,
#         so a misspelt title shows at once.
#   DONE  Page: a click on a cover shows it big (click, X or Esc closes) -
#         like the pencil shows the words.  The title and the play button
#         still play; a track without a cover still plays from the picture.
#   DONE  Page: a letter index.  A row of the letters the titles really
#         start with (# for digits, A-Z, Å Ä Ö, then any other alphabet
#         that is present - Cyrillic, Greek ...) sits above the list and
#         scrolls away with it.  Once it is out of sight a small round
#         button (A-Ö) appears at the corner; it opens the same letters on
#         demand and closes by itself - nothing sticks to the top and
#         nothing slides along.  Shown from 12 tracks up, follows search
#         and group filters.
#   DONE  Page: contributors.  One credit (just "Words: Malin Östh") stays
#         on the line under the title; with two or more the line stays
#         short and a small button beside the pencil opens a panel with
#         every credit, role in one column and name in the next - same
#         idea as the words.  The big cover and the player show them all.
#   DONE  Build says WHERE and WHEN: the status line carries the full path and
#         the clock time, and when the output folder is not the program's
#         own Helpfiles\MusicSite\Site the Build tab says so (a build had
#         been landing on C:\ while he was looking at the same-named folder
#         on X:\ and saw an old file).
#   DONE  Nothing is overwritten without a copy first: the old page and the
#         old project go to Helpfiles\\MusicSite\\Backups as
#         BACKUP_2026_10_01_143914_index.html (date AND time to the second,
#         so two builds in one minute no longer share one backup).  The
#         page itself is written to a temp file and swapped in, so a build
#         that dies half-way cannot leave half a page.
#   DONE  The page is in ALPHABETICAL order by default (Site tab, "Order on
#         the page"): numbers first in number order, then A-Z, then Å Ä Ö,
#         then other alphabets - the same order the letter index uses.  A
#         new song (Camaleot) used to land at the end of the hand-made
#         order and show up between "42" and "161 kisses tall".  "My own
#         order" keeps the Tracks tab order.  "Sort by title" on the Tracks
#         tab uses the same order.
#   DONE  The output folder is remembered.  It used to live only in the
#         project file, and a project that had not been saved (changing the
#         folder did not even mark it as changed) opened again with the OLD
#         folder.  Now the last folder used is kept in settings.json and
#         wins when a project is opened; the project file keeps a copy.
#         The five latest folders are quick links under the Output folder
#         box (Build tab).
#   DONE  "More about this song" (v1.10.0): per track a date (a full date, a
#         month or just a year - typed as you like), who the song is about,
#         and a list of EARLIER RELEASES (cassette, vinyl, CD ... as many as
#         it has been on, each with the release's name and year).  On the
#         page a small round "?" button opens a popup with it; the button
#         exists only for songs that have something to show.  Nothing here
#         is guessed or filled in by Fetch - it is all typed, and Fetch
#         keeps it.
#   DONE  "Set cover..." on the Tracks tab (v1.10.1): a wrong cover (a song
#         that was handed another song's picture) is fixed by hand - pick a
#         picture from this PC, or "No cover", or give it back to the
#         automatic matching.  A cover set by hand (track field cover_hand)
#         is never replaced by Fetch, and "Share cover" now protects the
#         receiving tracks the same way.
#   DONE  "Set cover..." now lists the files in the cloud's Cover folder
#         (remembered from the last Fetch in the project, cover_files):
#         pick the right one by name - the page then links to it like any
#         other cover, nothing extra to upload.  A cover picked by name is
#         looked up again by that name on every Fetch, so a re-uploaded file
#         with a new Drive id still works.  A picture from this PC is the
#         fallback only: the page then needs the covers folder uploaded.
#   DONE  Build with downloaded covers/audio remembers where each local file
#         came from (covers/_sources.json, mp3/_sources.json): a cover whose
#         source changed is fetched again instead of "already here" keeping
#         the old wrong picture under the same file name.
#   DONE  (v1.11.0) Tags in the mp3 files (DEL 08d): title, band, album, year,
#         words by, composer, comment, the published words and optionally the
#         cover are written into every mp3 in the 'Local folder(s)' - before
#         every comparison (tick box on the Upload tab) or by hand ('Tag
#         mp3...').  A file that is already right is not touched; the first
#         original is kept in Backups\MP3_originals.  Needs: pip install mutagen
#   DONE  (v1.11.0) WAV to MP3 (DEL 08e) with ffmpeg and remembered settings,
#         so WaveForge is not needed for that job; new mp3s are tagged at once.
#   DONE  (v1.12.0) DISCOGRAPHY (tab 6, DEL 08f / 11b): the releases of the
#         band - title, group, year, when/where recorded, format, release
#         date, copies and the whole tracklist - imported from the CSV table
#         ("Musik---Soundfont - Diskografi.csv": one COLUMN per release, the
#         column order is the release number #1, #2 ...) and edited in the
#         tab (add, delete, move, change).  Build writes discography.html
#         next to the music page: one card per release with the anchor #rN,
#         every song that is on the music page is a link back to it.  On the
#         music page each song gets its release numbers (#3 #9) in front of
#         the "?" button; a click opens discography.html scrolled to that
#         release.  The numbers are found AUTOMATICALLY by matching the
#         titles (like lyrics and covers); the tab lists what was matched
#         by similarity so a wrong guess is easy to spot.
#   DONE  (v1.12.0) ABOUT ME (tab 7, DEL 11c): a separate about.html with a
#         title, a text and an optional picture - empty until he fills it in.
#         All pages get the same small menu (Music / Discography / About).
#   DONE  (v1.12.0) Backups are named <name>_<yyyy_mm_dd>.<ext> (the date as
#         a SUFFIX); a second backup the same day also gets the time
#         (<name>_<yyyy_mm_dd>_<hhmmss>.<ext>).  Every page is backed up
#         before it is replaced, the project before it is saved.
#   DONE  (v1.13.0) ANDROID APP BOX at the top of the page (Site tab): a card
#         with a download button for the MusicSite Player app (.apk), a short
#         text, install steps and the page's own address with a Copy button
#         (for the app's Settings).  A Google Drive share link is turned into
#         a direct download.  Heading, text, button and address are his own.
#   DONE  (v1.14.0) BACKUP SOURCES (Source tab, "Backup source(s)"): the same
#         MP3 / Cover files in another place (second Drive folder, web
#         folder).  Fetch finds each song's files there by name
#         (track["alt"]); the page gets a switch Original | <name> that
#         re-points audio + covers (?src=<id>, remembered in the browser).
#         The Android player ignores "alt" for now (ToDo: fall back to it).
#   DONE  (v1.15.0, 2026-11-12) PROFILES: MusicSite_Issu (ISSUS BARN) and MusicSite_Loss (LOSS) are the same
#         program under two file names (or --profile X); each has its own Helpfiles\MusicSite_<profile> folder,
#         log, taskbar group and server folders (DEL 02).  MusicSite_Issu copies the old Helpfiles\MusicSite once.
#         A project that points at the other profile's output folder is refused.
#   DONE  (v1.15.1) File > Profile: lists the profiles (Helpfiles\MusicSite_*), opens one in a new window (same program,
#         --profile), "New profile..." makes a new group.  No file copies needed for new groups.
#   DONE  (v1.15.0) SEND TO SERVERS (Build tab, F10, DEL 12C / 16B): the small files go to Webdock (ssh/scp, folder swap,
#         settings read from AppSite); marker file per profile.
#   DONE  (v1.17.0, 2026-11-22) QR CODE in the "Android app" box of the page: the QR holds the APK download address (same as the
#         button), so a visitor on a computer scans it with the phone.  Own QR maker (qr_matrix / qr_svg, no pip module; checked:
#         every mask x many sizes decoded by zbar).  Hidden on phones / touch screens (CSS).  The Android app got the opposite
#         (MusicSitePlayer 1.7: Settings > QR code to the web page).
#   DONE  (v1.16.0, 2026-11-14) HTG IS GONE (the old FTP web server was dropped): the HTG send, its FTP login lookup and its
#         settings are removed.  Webdock is the one server; the send code takes the server from ONE function (srv_servers()),
#         so a second Webdock (backup) later is a list entry, not a rewrite.  NEW: "Update everything" (F11) = Fetch ->
#         Save -> Build -> Send in one press, and headless_update() does the same without a window - AppSite's DO EVERYTHING
#         button calls it for every profile (DEL 12D).
#   TODO  (future) A reserve address in MusicSitePlayer (second site address if the first does not answer).
#   TODO  (future) Read ID3 tags from local files to prefill title/year.
#   TODO  (future) Other formats than mp3 in the converter (AAC, FLAC).
# =============================================================================

# *****************************************************************************
# DEL 01 - IMPORTS
# *****************************************************************************
import os
import io
import re
import sys
import json
import html
import time
import queue
import shutil
import base64
import ctypes
import difflib
import platform
import threading
import traceback
import unicodedata
import webbrowser
import urllib.parse
import urllib.request
import urllib.error
from datetime import datetime, timedelta
from email.utils import parsedate_to_datetime
from concurrent.futures import ThreadPoolExecutor

import tkinter as tk
from tkinter import ttk, filedialog, messagebox, colorchooser
import os
import sys
import subprocess


# ---- 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


# *************** 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_in_browser(path_or_url) -> None:
    """Open a PAGE with my own browser - the one DefaultHub names for links.

    The preview is a file on this disk, and a file:/// address matches no
    rule in the table: it is not http, and nobody has claimed .html.  So it
    fell through to "whatever Windows calls the default browser" - which is
    exactly what it must not do.  Asking the table what opens a LINK and
    handing that program the page keeps it in the family, and it follows
    along by itself the day the browser in DefaultHub is a different one.
    """
    p = str(path_or_url or "").strip()
    if not p:
        return
    url = p if "://" in p else "file:///" + os.path.abspath(p).replace(
        "\\", "/")
    try:
        if _launch_my_app(_target_for("https://example.com"), url):
            return
    except Exception:
        pass
    open_url(url)


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


# -----------------------------------------------------------------------------


APP_NAME = "MusicSite"
APP_VERSION = "1.17.0"
APP_DATE = "2026-11-22"

# The two extra pages written next to the music page (DEL 11b / 11c).
DISCO_FILE = "discography.html"
ABOUT_FILE = "about.html"
APP_ID = "IssuTools.MusicSite.1"   # (a profile adds its name below: own taskbar group)

USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
              "(KHTML, like Gecko) Chrome/124.0 Safari/537.36")


# *****************************************************************************
# DEL 02 - PATHS  (always relative to the program / exe, never to the cwd)
# *****************************************************************************
def program_dir() -> str:
    """Folder of the .py file, or of the .exe when frozen by PyInstaller."""
    if getattr(sys, "frozen", False):
        return _program_home()
    return _program_home()


def program_name() -> str:
    if getattr(sys, "frozen", False):
        return os.path.splitext(os.path.basename(sys.executable))[0]
    return os.path.splitext(os.path.basename(__file__))[0]


BASE_DIR = program_dir()
PROG = program_name()


# ---- PROFILES (v1.15.0, 2026-11-12) -----------------------------------------
# One program, several separate music sites (Lars: ISSUS BARN and LOSS are two
# different groups with their own styles, texts and songs).  The profile is the
# part of the program's FILE NAME after "MusicSite_":
#       MusicSite_Issu.py / MusicSite_Issu.exe   -> profile "Issu"  (title ISSUS BARN)
#       MusicSite_Loss.py / MusicSite_Loss.exe   -> profile "Loss"  (title LOSS)
#       MusicSite.py                              -> no profile (old behaviour)
# or  MusicSite.py --profile Loss  (the same, without copying the file).
# Each profile has its OWN folder Helpfiles\MusicSite_<profile>\ (settings, projects, backups,
# default Site folder, cloud memory), its own log and its own taskbar group, so
# one profile can never overwrite the other's files.  The server folders are
# separate too (DEL 12C).  Letters, digits, - and _ only; anything else = no profile.
PROFILE_PREFIX = "MusicSite_"
PROFILE_TITLES = {"issu": "ISSUS BARN", "loss": "LOSS"}


def _clean_profile(name: str) -> str:
    name = (name or "").strip()
    return name if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,30}", name) else ""


def _find_profile() -> str:
    if "--profile" in sys.argv:                       # MusicSite.py --profile Loss
        i = sys.argv.index("--profile")
        val = sys.argv[i + 1] if i + 1 < len(sys.argv) else ""
        del sys.argv[i:i + 2]                          # other code never sees it
        if _clean_profile(val):
            return _clean_profile(val)
    if PROG.lower().startswith(PROFILE_PREFIX.lower()):
        return _clean_profile(PROG[len(PROFILE_PREFIX):])
    return ""


PROFILE = _find_profile()
PROFILE_TITLE = PROFILE_TITLES.get(PROFILE.lower(), PROFILE.upper()) if PROFILE else ""
HELP_FOLDER = (PROFILE_PREFIX + PROFILE) if PROFILE else "MusicSite"
APP_TITLE = ("MusicSite - " + PROFILE_TITLE) if PROFILE else "MusicSite"   # window title; message boxes keep APP_NAME
APP_ID = APP_ID + (("." + PROFILE) if PROFILE else "")                   # own taskbar group per profile

HELP_ROOT = os.path.join(BASE_DIR, "Helpfiles")
HELP_DIR = os.path.join(HELP_ROOT, HELP_FOLDER)       # program's own helpfiles (per profile)
LEGACY_HELP_DIR = os.path.join(HELP_ROOT, "MusicSite")  # where Lars's one and only site lived before profiles
LOG_DIR = os.path.join(HELP_ROOT, "0---Empty")        # logs only
PROJ_DIR = os.path.join(HELP_DIR, "Projects")
BAK_DIR = os.path.join(HELP_DIR, "Backups")
OUT_DIR_DEFAULT = os.path.join(HELP_DIR, "Site")
# Where the upload check puts the files that have to go up.  It is NOT made
# by ensure_dirs - it appears the first time it is actually used, so an empty
# folder never sits there pretending there is something to upload.
STAGE_DIR_DEFAULT = os.path.join(HELP_DIR, "Temp_to_drive")
ICON_DIR = os.path.join(BASE_DIR, "Icons")

SETTINGS_FILE = os.path.join(HELP_DIR, "settings.json")
LOG_FILE = os.path.join(LOG_DIR, HELP_FOLDER + "_log.txt")


def _swap_prefix(obj, old: str, new: str):
    """Copy of a json value with every string that starts with the folder `old` re-pointed to `new`."""
    if isinstance(obj, str):
        o = os.path.normcase(os.path.normpath(old))
        s = os.path.normcase(os.path.normpath(obj)) if obj else obj
        if obj and (s == o or s.startswith(o + os.sep)):
            return new + os.path.normpath(obj)[len(os.path.normpath(old)):]
        return obj
    if isinstance(obj, list):
        return [_swap_prefix(v, old, new) for v in obj]
    if isinstance(obj, dict):
        return {k: _swap_prefix(v, old, new) for k, v in obj.items()}
    return obj


def migrate_legacy_helpfiles() -> str:
    """Profile "Issu" inherits the old Helpfiles\\MusicSite folder, ONCE, as a COPY (the old folder stays as it
    was).  Paths inside the copied settings and projects are re-pointed to the new folder, so the new profile
    never writes into the old one.  Returns a message ('' = nothing done)."""
    if PROFILE.lower() != "issu" or os.path.exists(HELP_DIR) or not os.path.isdir(LEGACY_HELP_DIR):
        return ""
    try:
        shutil.copytree(LEGACY_HELP_DIR, HELP_DIR)
        n = 0
        for dp, dns, fns in os.walk(HELP_DIR):
            if os.path.basename(dp).lower() == "backups":
                dns[:] = []
                continue
            for fn in fns:
                if fn.lower().endswith((".msite", ".json")):
                    p = os.path.join(dp, fn)
                    try:
                        with open(p, "r", encoding="utf-8") as f:
                            data = json.load(f)
                        new = _swap_prefix(data, LEGACY_HELP_DIR, HELP_DIR)
                        if new != data:
                            with open(p, "w", encoding="utf-8") as f:
                                json.dump(new, f, indent=2, ensure_ascii=False)
                            n += 1
                    except Exception:
                        pass
        return "Copied %s to %s (%d files re-pointed)" % (LEGACY_HELP_DIR, HELP_DIR, n)
    except Exception as exc:
        return "Could not copy the old Helpfiles folder: %s" % exc


def ensure_dirs() -> None:
    for d in (HELP_ROOT, HELP_DIR, LOG_DIR, PROJ_DIR, BAK_DIR, OUT_DIR_DEFAULT,
              ICON_DIR):
        try:
            os.makedirs(d, exist_ok=True)
        except Exception:
            pass


MIGRATION_NOTE = migrate_legacy_helpfiles()
ensure_dirs()


# *****************************************************************************
# DEL 03 - CRASH CATCHER, LOG, DIAGNOSTICS
# *****************************************************************************
_LOG_LOCK = threading.Lock()


def log(msg: str, level: str = "INFO") -> None:
    """Append one line to the log file.  Never raises."""
    line = "%s  %-7s %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                            level, msg)
    try:
        with _LOG_LOCK:
            with open(LOG_FILE, "a", encoding="utf-8") as f:
                f.write(line + "\n")
    except Exception:
        pass


def log_exception(where: str, exc: BaseException) -> str:
    text = "".join(traceback.format_exception(type(exc), exc,
                                              exc.__traceback__))
    log("EXCEPTION in %s\n%s" % (where, text), "ERROR")
    return text


class CrashGuard:
    """Installs global handlers so nothing dies silently."""

    root = None          # set once the main window exists
    last_traceback = ""

    @classmethod
    def install(cls):
        sys.excepthook = cls._sys_hook
        try:
            threading.excepthook = cls._thread_hook
        except Exception:
            pass

    @classmethod
    def _sys_hook(cls, etype, value, tb):
        cls.last_traceback = "".join(traceback.format_exception(etype, value,
                                                               tb))
        log("UNCAUGHT\n" + cls.last_traceback, "FATAL")
        cls._show(cls.last_traceback)

    @classmethod
    def _thread_hook(cls, args):
        cls.last_traceback = "".join(traceback.format_exception(
            args.exc_type, args.exc_value, args.exc_traceback))
        log("THREAD CRASH\n" + cls.last_traceback, "FATAL")

    @classmethod
    def tk_callback(cls, exc, val, tb):
        """Bound to Tk's report_callback_exception."""
        cls.last_traceback = "".join(traceback.format_exception(exc, val, tb))
        log("TK CALLBACK\n" + cls.last_traceback, "ERROR")
        cls._show(cls.last_traceback)

    @classmethod
    def _show(cls, text):
        try:
            if cls.root is not None and cls.root.winfo_exists():
                show_diagnostics(cls.root, text)
                return
        except Exception:
            pass
        try:
            sys.stderr.write(text)
        except Exception:
            pass


def collect_diagnostics(extra: str = "") -> str:
    """A copy-paste friendly report of the environment + last crash."""
    lines = []
    add = lines.append
    add("%s %s  (%s)" % (APP_NAME, APP_VERSION, APP_DATE))
    add("Time            : " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    add("Python          : " + sys.version.replace("\n", " "))
    add("Platform        : %s %s" % (platform.system(), platform.release()))
    add("Frozen (exe)    : %s" % bool(getattr(sys, "frozen", False)))
    add("Program dir     : " + BASE_DIR)
    add("Helpfiles dir   : " + HELP_DIR)
    add("Log file        : " + LOG_FILE)
    add("Tk version      : %s" % tk.TkVersion)
    add("")
    if extra:
        add("---- Traceback ----")
        add(extra.rstrip())
        add("")
    add("---- Last 40 log lines ----")
    try:
        with open(LOG_FILE, "r", encoding="utf-8", errors="replace") as f:
            tail = f.readlines()[-40:]
        lines.extend(x.rstrip() for x in tail)
    except Exception:
        add("(no log file yet)")
    return "\n".join(lines)


# *****************************************************************************
# DEL 04 - COLOURS  (all button colours are written out in plain words so they
#                    are trivial to change: "grey" -> "red", "white" -> "blue")
# *****************************************************************************
C_BG = "#1c1c24"        # window background
C_BG2 = "#23232e"       # panels
C_BG3 = "#2a2a38"       # dialogs / cards
C_FG = "#e8e8f0"        # normal text
C_FG_DIM = "#9a9aa8"    # secondary text
C_ACCENT = "#7fc4ff"    # links / headings
C_SEP = "#3a3a4a"       # separator lines
C_FIELD = "#15151c"     # entry background
C_OK = "#6fd08c"
C_WARN = "#e8c46a"
C_ERR = "#ef7b7b"

BTN_MAIN = "lightgreen"     # primary action buttons
BTN_NORM = "gainsboro"      # ordinary buttons
BTN_WARN = "khaki"          # careful buttons
BTN_DANGER = "lightcoral"   # destructive buttons
BTN_INFO = "lightblue"      # help / info buttons
BTN_FG = "black"            # text colour on all of the above


# *****************************************************************************
# DEL 05 - SMALL WIDGET HELPERS  (no blinking cursors anywhere)
# *****************************************************************************
def no_blink(w):
    """Force a solid, non-blinking caret on any Entry/Text widget."""
    try:
        w.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass
    return w


def mk_entry(parent, **kw):
    kw.setdefault("bg", C_FIELD)
    kw.setdefault("fg", C_FG)
    kw.setdefault("insertbackground", C_FG)
    kw.setdefault("relief", "flat")
    kw.setdefault("highlightthickness", 1)
    kw.setdefault("highlightbackground", C_SEP)
    kw.setdefault("highlightcolor", C_ACCENT)
    e = tk.Entry(parent, insertofftime=0, insertontime=9999999, **kw)
    assert e.cget("insertofftime") == 0
    return e


def mk_text(parent, **kw):
    kw.setdefault("bg", C_FIELD)
    kw.setdefault("fg", C_FG)
    kw.setdefault("insertbackground", C_FG)
    kw.setdefault("relief", "flat")
    kw.setdefault("highlightthickness", 1)
    kw.setdefault("highlightbackground", C_SEP)
    kw.setdefault("highlightcolor", C_ACCENT)
    kw.setdefault("wrap", "word")
    t = tk.Text(parent, insertofftime=0, insertontime=9999999, **kw)
    assert t.cget("insertofftime") == 0
    return t


def mk_button(parent, text, cmd, colour=BTN_NORM, width=None, **kw):
    kw.setdefault("activebackground", colour)
    b = tk.Button(parent, text=text, command=cmd, bg=colour, fg=BTN_FG,
                  relief="raised", bd=1, padx=8, pady=2,
                  font=("Segoe UI", 9), **kw)
    if width:
        b.configure(width=width)
    return b


def mk_label(parent, text, **kw):
    kw.setdefault("bg", parent.cget("bg"))
    kw.setdefault("fg", C_FG)
    kw.setdefault("font", ("Segoe UI", 9))
    return tk.Label(parent, text=text, **kw)


def bind_mousewheel(widget, target=None):
    """Mouse wheel scrolling for canvases / text areas."""
    target = target or widget

    def _on(ev):
        try:
            target.yview_scroll(int(-1 * (ev.delta / 120)), "units")
        except Exception:
            pass
        return "break"

    widget.bind("<MouseWheel>", _on)
    widget.bind("<Button-4>", lambda e: target.yview_scroll(-1, "units"))
    widget.bind("<Button-5>", lambda e: target.yview_scroll(1, "units"))


def toast(parent, message, ms=1000, colour=C_OK):
    """Small 'it worked' popup that disappears by itself after ~1 second."""
    try:
        top = tk.Toplevel(parent)
        top.overrideredirect(True)
        top.configure(bg=C_SEP)
        frame = tk.Frame(top, bg=C_BG3, padx=18, pady=10)
        frame.pack(padx=1, pady=1)
        tk.Label(frame, text=message, bg=C_BG3, fg=colour,
                 font=("Segoe UI", 10, "bold")).pack()
        top.update_idletasks()
        px = parent.winfo_rootx() + parent.winfo_width() // 2
        py = parent.winfo_rooty() + parent.winfo_height() // 2
        top.geometry("+%d+%d" % (px - top.winfo_width() // 2,
                                 py - top.winfo_height() // 2))
        top.attributes("-topmost", True)
        top.after(ms, top.destroy)
    except Exception as exc:
        log_exception("toast", exc)


def dialog_setup(top, parent, on_escape=None):
    """grab_set(), focus_force(), <Escape> - in that order, every time."""
    top.transient(parent)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())


def show_diagnostics(parent, extra=""):
    """Diagnostics window - environment + last traceback + log tail."""
    top = tk.Toplevel(parent)
    top.title("MusicSite - Diagnostics")
    top.configure(bg=C_BG3)
    top.geometry("880x560")

    tk.Label(top, text="Diagnostics", bg=C_BG3, fg=C_ERR,
             font=("Segoe UI", 14, "bold")).pack(pady=(12, 2))
    tk.Label(top, text="Copy this text if you need to report a problem.",
             bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9, "italic")).pack()

    wrap = tk.Frame(top, bg=C_BG3)
    wrap.pack(fill="both", expand=True, padx=14, pady=10)
    sb = tk.Scrollbar(wrap)
    sb.pack(side="right", fill="y")                 # scrollbar FIRST
    txt = mk_text(wrap, yscrollcommand=sb.set, font=("Consolas", 9))
    txt.pack(side="left", fill="both", expand=True)
    sb.configure(command=txt.yview)
    bind_mousewheel(txt)

    report = collect_diagnostics(extra or CrashGuard.last_traceback)
    txt.insert("1.0", report)

    row = tk.Frame(top, bg=C_BG3)
    row.pack(fill="x", padx=14, pady=(0, 12))

    def copy_it():
        top.clipboard_clear()
        top.clipboard_append(txt.get("1.0", "end-1c"))
        toast(top, "Copied to clipboard")

    mk_button(row, "Copy", copy_it, BTN_NORM, width=12).pack(side="left")
    mk_button(row, "Open log folder",
              lambda: open_in_explorer(LOG_DIR), BTN_NORM,
              width=16).pack(side="left", padx=6)
    mk_button(row, "Close", top.destroy, BTN_INFO,
              width=12).pack(side="right")
    dialog_setup(top, parent)


def open_in_explorer(path):
    try:
        if platform.system() == "Windows":
            open_path(path)                       # noqa: S606
        else:
            open_url("file://" + path)
    except Exception as exc:
        log_exception("open_in_explorer", exc)


# *****************************************************************************
# DEL 06 - NAME MATCHING
#   "Dagen_utan_morgon.mp3"  ==  "Dagen utan morgon.jpg"  ==  "01 - Dagen
#   utan morgon.txt".  Everything is reduced to a comparison key.
# *****************************************************************************
AUDIO_EXT = (".mp3", ".m4a", ".aac", ".ogg", ".oga", ".opus", ".flac", ".wav",
             ".wma")
IMAGE_EXT = (".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif")
TEXT_EXT = (".txt", ".md", ".text")

_TRACKNO_RE = re.compile(r"^\s*(\d{1,3})\s*[\.\-_)]*\s+")
_TRACKNO_BARE_RE = re.compile(r"^\s*(\d{1,3})\s*[\.\-_)]\s*")


def split_ext(name):
    base, ext = os.path.splitext(name)
    return base, ext.lower()


def strip_tracknumber(base):
    """Return (clean_name, number_or_None)."""
    m = _TRACKNO_RE.match(base) or _TRACKNO_BARE_RE.match(base)
    if m:
        try:
            n = int(m.group(1))
        except Exception:
            n = None
        return base[m.end():], n
    return base, None


def looks_like_track_numbering(names):
    """Is this folder REALLY numbered 01, 02, 03 ... ?

    A single "161_kisses_tall.mp3" or "1985.mp3" is a title that happens to
    start with digits - not a track number.  Stripping those silently ruins
    the title, so the decision is made for the whole folder at once: it only
    counts as track numbering when most files carry a small, distinct,
    sequence-like number.
    """
    total, nums = 0, []
    for n in names:
        base, _ = split_ext(n)
        total += 1
        clean, num = strip_tracknumber(base)
        if num is not None and clean.strip():
            nums.append(num)
    if total < 3 or len(nums) < 3:
        return False
    if len(nums) < total * 0.6:                # most files must carry one
        return False
    if len(set(nums)) < len(nums) * 0.8:       # a real order barely repeats
        return False
    if max(nums) > max(60, total * 2):         # 161 is not a track number
        return False
    return True


def norm_key(name, drop_number=True):
    """Comparison key: no extension, no separators, no case."""
    base, _ = split_ext(name)
    base = unicodedata.normalize("NFC", base)
    if drop_number:
        base, _ = strip_tracknumber(base)
    base = base.replace("_", " ").replace("-", " ").replace(".", " ")
    base = re.sub(r"\s+", " ", base).strip().casefold()
    return base


def pretty_title(name, drop_number=True):
    """Human title from a file name - keeps the original capitalisation."""
    base, _ = split_ext(name)
    base = unicodedata.normalize("NFC", base)
    if drop_number:
        base, _ = strip_tracknumber(base)
    base = base.replace("_", " ")
    base = re.sub(r"\s+", " ", base).strip()
    return base or "Untitled"


def slugify(text):
    s = unicodedata.normalize("NFKD", text)
    s = "".join(c for c in s if not unicodedata.combining(c))
    s = re.sub(r"[^A-Za-z0-9]+", "-", s).strip("-").lower()
    return s or "track"


def best_match(key, candidates, cutoff=0.84):
    """Exact -> prefix/contains -> fuzzy.  Returns (chosen_key, how) or None."""
    if key in candidates:
        return key, "exact"
    for c in candidates:
        if c.startswith(key) or key.startswith(c):
            return c, "prefix"
    for c in candidates:
        if key and (key in c or c in key):
            return c, "contains"
    close = difflib.get_close_matches(key, list(candidates), n=1,
                                      cutoff=cutoff)
    if close:
        return close[0], "fuzzy"
    return None


# *****************************************************************************
# DEL 07 - SOURCE DRIVERS
#   Every driver answers one question: "what files are in the sub-folder
#   named X, and what is the direct URL of each one?"
# *****************************************************************************
def parse_groups(text, fallback_address=""):
    """Read the 'main folder(s)' box.

    One group per line.  Either just an address, or 'Name | address' when you
    want to choose the heading yourself.  Blank lines and lines starting with
    # are ignored.  One single unnamed line = the old single-folder behaviour,
    with no headings on the page at all.
    """
    groups = []
    for line in (text or "").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "|" in line:
            name, addr = line.split("|", 1)
            name, addr = name.strip(), addr.strip()
        else:
            name, addr = "", line
        if addr:
            groups.append({"name": name, "address": addr})
    if not groups and fallback_address:
        groups.append({"name": "", "address": fallback_address.strip()})
    return groups


class RemoteFile:
    # mtime is 0 when the source does not say, and 'exact' is False when it
    # only says the DAY (Google Drive's folder listing does exactly that).
    # The upload check needs to know the difference, so it is carried here
    # instead of being guessed later.
    __slots__ = ("name", "ident", "url", "size", "is_dir", "mtime", "exact")

    def __init__(self, name, ident="", url="", size=0, is_dir=False,
                 mtime=0.0, exact=False):
        self.name = name
        self.ident = ident
        self.url = url
        self.size = size
        self.is_dir = is_dir
        self.mtime = mtime
        self.exact = exact

    def __repr__(self):
        return "<RemoteFile %s>" % self.name


class SourceError(Exception):
    pass


def http_get(url, timeout=30, binary=False):
    # Accept-Language is not cosmetic here: Google Drive writes the "last
    # modified" column of its folder listing in the language you ask for, and
    # the upload check has to parse those dates.  Pin it to English.
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT,
                                               "Accept": "*/*",
                                               "Accept-Language": "en-US,en"})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        data = resp.read()
    if binary:
        return data
    for enc in ("utf-8", "cp1252", "latin-1"):
        try:
            return data.decode(enc)
        except Exception:
            continue
    return data.decode("utf-8", "replace")


def head_info(url, timeout=25):
    """Ask a host for the SIZE and DATE of a file without downloading it.

    Returns (size, mtime, ok).  size 0 / mtime 0.0 mean "the host did not say".

    This is what makes the upload check work with Google Drive without any
    API key at all: a plain HEAD of the download link answers with the exact
    Content-Length and a real Last-Modified, even though the folder listing
    only shows the day.  Proven against a live public folder 2026-09-05.

    Some hosts refuse HEAD, so a one-byte ranged GET is the fallback - it
    reports the full length in Content-Range.
    """
    hdrs = {"User-Agent": USER_AGENT, "Accept": "*/*"}

    def _read(req):
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            h = resp.headers
            size = int(h.get("Content-Length") or 0)
            rng = h.get("Content-Range") or ""
            if "/" in rng:
                try:
                    size = int(rng.rsplit("/", 1)[1])
                except Exception:
                    pass
            lm = h.get("Last-Modified") or ""
        ts = 0.0
        if lm:
            try:
                ts = parsedate_to_datetime(lm).timestamp()
            except Exception:
                ts = 0.0
        return size, ts

    try:
        return _read(urllib.request.Request(url, headers=hdrs,
                                            method="HEAD")) + (True,)
    except Exception:
        pass
    try:
        h2 = dict(hdrs)
        h2["Range"] = "bytes=0-0"
        return _read(urllib.request.Request(url, headers=h2)) + (True,)
    except Exception:
        return 0, 0.0, False


_MONTH_FORMATS = ("%b %d, %Y", "%b %d %Y", "%b %d", "%d %b %Y", "%d %b")


def parse_listing_date(text):
    """A date the way a folder listing writes it -> (epoch, exact).

    Google Drive prints "Aug 31" for this year and "Aug 31, 2025" for older
    files - the DAY only, never the time.  A day is turned into the LAST
    moment of that day on purpose: with only a day to go on, the honest
    question is "is my file newer than anything that day could mean", and
    exact=False tells the comparison to be careful about it.
    """
    # a narrow no-break space sits between the minutes and am/pm
    text = (text or "").replace(" ", " ").replace("\xa0", " ")
    text = re.sub(r"\s+", " ", text).strip().rstrip(".")
    if not text:
        return 0.0, False
    now = datetime.now()
    # A file touched TODAY is listed as a time of day - "9:44 am", "13:05" -
    # and never as a date.  That is more exact than a day, not less: it is
    # today at that minute.
    m = re.fullmatch(r"(\d{1,2})[:.](\d{2})\s*([ap])\.?m\.?", text, re.I)
    if m:
        hour = int(m.group(1)) % 12 + (12 if m.group(3).lower() == "p" else 0)
        return now.replace(hour=hour, minute=int(m.group(2)), second=0,
                           microsecond=0).timestamp(), True
    m = re.fullmatch(r"(\d{1,2})[:.](\d{2})", text)
    if m and int(m.group(1)) < 24:
        return now.replace(hour=int(m.group(1)), minute=int(m.group(2)),
                           second=0, microsecond=0).timestamp(), True
    for fmt in _MONTH_FORMATS:
        try:
            d = datetime.strptime(text, fmt)
        except ValueError:
            continue
        if "%Y" not in fmt:
            d = d.replace(year=now.year)
            if d > now + timedelta(days=1):        # "Dec 20" seen in January
                d = d.replace(year=now.year - 1)
        return d.replace(hour=23, minute=59, second=59).timestamp(), False
    # a full ISO stamp (Drive API, files.json manifests)
    try:
        t = text.replace("Z", "+00:00")
        return datetime.fromisoformat(t).timestamp(), True
    except Exception:
        return 0.0, False


# ---------------------------------------------------------------- Google Drive
GDRIVE_FOLDER_PATTERNS = [
    re.compile(r"/folders/([A-Za-z0-9_\-]{10,})"),
    re.compile(r"[?&]id=([A-Za-z0-9_\-]{10,})"),
    re.compile(r"/d/([A-Za-z0-9_\-]{10,})"),
]

GDRIVE_AUDIO_STYLES = {
    "usercontent (recommended)":
        "https://drive.usercontent.google.com/download?id={id}&export=download",
    "drive.google.com/uc":
        "https://drive.google.com/uc?export=download&id={id}",
    "docs.google.com/uc":
        "https://docs.google.com/uc?export=download&id={id}",
}

GDRIVE_IMAGE_STYLES = {
    "thumbnail (recommended)":
        "https://drive.google.com/thumbnail?id={id}&sz=w1000",
    "lh3 googleusercontent":
        "https://lh3.googleusercontent.com/d/{id}=w1000",
    "usercontent download":
        "https://drive.usercontent.google.com/download?id={id}&export=view",
}


def gdrive_folder_id(text):
    text = (text or "").strip()
    if not text:
        return ""
    for pat in GDRIVE_FOLDER_PATTERNS:
        m = pat.search(text)
        if m:
            return m.group(1)
    if re.fullmatch(r"[A-Za-z0-9_\-]{10,}", text):
        return text
    return ""


class GoogleDriveSource:
    """Reads a PUBLIC ('anyone with the link') Drive folder.

    Two ways in:
      1. embeddedfolderview  - no API key at all, works for normal folders.
      2. Drive API v3 + key  - needs a free API key, more reliable / paged.
    """

    kind = "gdrive"

    def __init__(self, main_address, api_key="",
                 audio_style="usercontent (recommended)",
                 image_style="thumbnail (recommended)"):
        self.folder_id = gdrive_folder_id(main_address)
        if not self.folder_id:
            raise SourceError(
                "Could not find a Google Drive folder id in:\n%s\n\n"
                "Paste the share link of the MAIN folder, for example\n"
                "https://drive.google.com/drive/folders/1AbC...xyz?usp=sharing"
                % main_address)
        self.api_key = (api_key or "").strip()
        self.audio_tpl = GDRIVE_AUDIO_STYLES.get(
            audio_style, list(GDRIVE_AUDIO_STYLES.values())[0])
        self.image_tpl = GDRIVE_IMAGE_STYLES.get(
            image_style, list(GDRIVE_IMAGE_STYLES.values())[0])
        self._cache = {}
        self._titles = {}

    # -- listing ------------------------------------------------------------
    def _list_api(self, folder_id):
        out = []
        token = ""
        while True:
            q = urllib.parse.quote("'%s' in parents and trashed = false"
                                   % folder_id)
            url = ("https://www.googleapis.com/drive/v3/files"
                   "?q=%s&key=%s&pageSize=1000"
                   "&fields=nextPageToken,files(id,name,mimeType,size,"
                   "modifiedTime)"
                   "&supportsAllDrives=true&includeItemsFromAllDrives=true"
                   % (q, urllib.parse.quote(self.api_key)))
            if token:
                url += "&pageToken=" + urllib.parse.quote(token)
            data = json.loads(http_get(url))
            for f in data.get("files", []):
                is_dir = f.get("mimeType") == "application/vnd.google-apps.folder"
                ts, exact = parse_listing_date(f.get("modifiedTime", ""))
                out.append(RemoteFile(f.get("name", ""), f.get("id", ""),
                                      "", int(f.get("size") or 0), is_dir,
                                      ts, exact))
            token = data.get("nextPageToken", "")
            if not token:
                break
        return out

    # The one message that solves 9 problems out of 10.
    NOT_SHARED_HELP = (
        "Google Drive would not show the contents of that folder.\n\n"
        "By far the most common cause: the folder is not shared.\n"
        "Drive answers exactly the same way for 'does not exist' and for\n"
        "'exists but is private', so this is the first thing to check.\n\n"
        "Fix it like this:\n"
        "  1. Open the MAIN folder in Google Drive.\n"
        "  2. Right-click it and choose Share.\n"
        "  3. Under 'General access' pick 'Anyone with the link'.\n"
        "  4. Leave the role as 'Viewer'.\n"
        "  5. Copy the link and paste it here again.\n\n"
        "The sub-folders MP3 / Cover / Text inherit that setting, so you\n"
        "only have to do it once, on the main folder.\n\n"
        "Other things worth checking:\n"
        "  * that the link points at the MAIN folder, not at MP3 itself\n"
        "  * that the folder is not inside a Shared drive with extra limits\n"
        "  * for very large folders, add a Drive API key on the Source tab")

    def _list_embedded(self, folder_id):
        url = ("https://drive.google.com/embeddedfolderview?id=%s#list"
               % folder_id)
        try:
            page = http_get(url)
        except urllib.error.HTTPError as exc:
            # 404 = missing OR private, 403 = refused.  Same advice for both.
            if exc.code in (403, 404):
                raise SourceError(self.NOT_SHARED_HELP)
            raise SourceError("Google Drive answered HTTP %s.\n\n"
                              "Wait a moment and try again." % exc.code)
        except urllib.error.URLError as exc:
            raise SourceError("Could not reach Google Drive.\n\n"
                              "Check your internet connection.\n\n%s"
                              % exc.reason)
        # An EMPTY folder that is shared perfectly well still returns a page
        # with no "flip-entry" in it.  Telling the user "not shared" then is
        # simply wrong, so the two cases are told apart by the listing shell
        # ("flip-entries" / "flip-contents"), which is present either way.
        m_title = re.search(r"<title>(.*?)</title>", page, re.S)
        if m_title:
            self._titles[folder_id] = html.unescape(m_title.group(1)).strip()
        if "flip-entry" not in page:
            if "flip-entries" in page or "flip-contents" in page:
                return []                          # shared, just empty
            raise SourceError(self.NOT_SHARED_HELP)
        out = []
        chunks = page.split('class="flip-entry"')
        for chunk in chunks[1:]:
            m_id = re.search(r'id="entry-([A-Za-z0-9_\-]+)"', chunk)
            if not m_id:
                m_id = re.search(r'entry-([A-Za-z0-9_\-]{10,})', chunk)
            m_title = re.search(
                r'class="flip-entry-title"[^>]*>(.*?)</div>', chunk,
                re.S)
            m_href = re.search(r'href="([^"]+)"', chunk)
            # Drive DOES print a date in the listing - "Aug 31" - but only the
            # day, and no size at all.  Both are taken for what they are worth
            # here; the exact numbers come from head_info() when the upload
            # check asks for them.
            m_mod = re.search(
                r'class="flip-entry-last-modified"[^>]*>\s*<div>(.*?)</div>',
                chunk, re.S)
            if not (m_id and m_title):
                continue
            name = html.unescape(re.sub(r"<[^>]+>", "", m_title.group(1))).strip()
            href = m_href.group(1) if m_href else ""
            is_dir = "/folders/" in href
            ts, exact = (parse_listing_date(
                html.unescape(m_mod.group(1)).strip()) if m_mod
                else (0.0, False))
            out.append(RemoteFile(name, m_id.group(1), "", 0, is_dir,
                                  ts, exact))
        return out

    def list_children(self, folder_id):
        if folder_id in self._cache:
            return self._cache[folder_id]
        errors = []
        if self.api_key:
            try:
                items = self._list_api(folder_id)
                self._cache[folder_id] = items
                return items
            except Exception as exc:
                errors.append("API key: %s" % exc)
                log("Drive API listing failed: %s" % exc, "WARN")
        try:
            items = self._list_embedded(folder_id)
        except SourceError:
            raise
        except Exception as exc:
            errors.append("public listing: %s" % exc)
            raise SourceError("Could not read the Drive folder.\n\n"
                              + "\n".join(errors))
        self._cache[folder_id] = items
        return items

    # -- interface ----------------------------------------------------------
    def root_items(self):
        return self.list_children(self.folder_id)

    def subfolder(self, name):
        """Find a sub-folder by name (case-insensitive, tolerant)."""
        want = norm_key(name, drop_number=False)
        for it in self.root_items():
            if it.is_dir and norm_key(it.name, drop_number=False) == want:
                return it
        for it in self.root_items():
            if it.is_dir and want in norm_key(it.name, drop_number=False):
                return it
        return None

    def list_folder(self, name):
        sub = self.subfolder(name)
        if sub is None:
            return None                       # caller reports "not found"
        return [f for f in self.list_children(sub.ident) if not f.is_dir]

    def audio_url(self, f):
        return self.audio_tpl.format(id=f.ident)

    def image_url(self, f):
        return self.image_tpl.format(id=f.ident)

    def raw_url(self, f):
        return ("https://drive.usercontent.google.com/download"
                "?id=%s&export=download" % f.ident)

    def probe(self, f):
        """Exact size + date for ONE file.  No API key needed."""
        return head_info(self.raw_url(f))

    def key(self):
        return "gdrive:" + self.folder_id

    def folder_title(self):
        """The folder's own name in Drive - used as an automatic heading."""
        try:
            if self.folder_id not in self._titles:
                self.root_items()
        except Exception:
            pass
        return self._titles.get(self.folder_id, "")

    def describe(self):
        return "Google Drive folder %s%s" % (
            self.folder_id, "  (API key in use)" if self.api_key else "")


# ------------------------------------------------------------------ HTTP folder
class HttpFolderSource:
    """A plain web folder.

    Works with:
      * a normal directory listing (Apache / nginx autoindex / Caddy)
      * a files.json manifest:  ["a.mp3", "b.mp3"]  or  [{"name": "a.mp3"}]
    """

    kind = "http"

    def __init__(self, main_address, **_):
        base = (main_address or "").strip()
        if not base:
            raise SourceError("Enter the address of the main folder, "
                              "for example https://example.com/music/")
        if not re.match(r"^https?://", base):
            base = "https://" + base
        self.base = base.rstrip("/") + "/"

    def _folder_url(self, name):
        return self.base + urllib.parse.quote(name.strip("/")) + "/"

    def list_folder(self, name):
        furl = self._folder_url(name)
        # 1) manifest
        for manifest in ("files.json", "index.json"):
            try:
                data = json.loads(http_get(furl + manifest, timeout=15))
                out = []
                for item in data:
                    if isinstance(item, str):
                        out.append(RemoteFile(item, "", furl +
                                              urllib.parse.quote(item)))
                    elif isinstance(item, dict) and item.get("name"):
                        n = item["name"]
                        ts, exact = parse_listing_date(
                            str(item.get("modified") or
                                item.get("mtime") or ""))
                        out.append(RemoteFile(n, "",
                                              item.get("url") or
                                              furl + urllib.parse.quote(n),
                                              int(item.get("size") or 0),
                                              False, ts, exact))
                if out:
                    return out
            except Exception:
                pass
        # 2) directory listing
        try:
            page = http_get(furl, timeout=25)
        except urllib.error.HTTPError as exc:
            if exc.code in (403, 404):
                return None
            raise SourceError("HTTP %s for %s" % (exc.code, furl))
        except Exception as exc:
            raise SourceError("Could not open %s\n%s" % (furl, exc))

        out, seen = [], set()
        for m in re.finditer(r'href="([^"?#]+)"', page, re.I):
            href = html.unescape(m.group(1))
            if href.startswith(("/", "..", "http://", "https://", "mailto:")):
                continue
            if href.endswith("/"):
                continue
            fname = urllib.parse.unquote(href.split("/")[-1])
            if not fname or fname in seen:
                continue
            seen.add(fname)
            out.append(RemoteFile(fname, "", furl + href))
        return out

    def audio_url(self, f):
        return f.url

    def image_url(self, f):
        return f.url

    def raw_url(self, f):
        return f.url

    def probe(self, f):
        return head_info(f.url)

    def key(self):
        return "http:" + self.base

    def folder_title(self):
        return urllib.parse.unquote(self.base.rstrip("/").split("/")[-1])

    def describe(self):
        return "Web folder " + self.base


# ------------------------------------------------------------ S3 / object store
class S3Source:
    """Any public S3-compatible bucket (Scaleway, OVH, Backblaze B2, MinIO...).

    The main address is the public bucket URL, e.g.
      https://my-music.s3.fr-par.scw.cloud
    """

    kind = "s3"

    def __init__(self, main_address, **_):
        base = (main_address or "").strip()
        if not base:
            raise SourceError("Enter the public bucket URL.")
        if not re.match(r"^https?://", base):
            base = "https://" + base
        self.base = base.rstrip("/")

    def list_folder(self, name):
        prefix = name.strip("/") + "/"
        url = ("%s/?list-type=2&prefix=%s&max-keys=1000"
               % (self.base, urllib.parse.quote(prefix)))
        try:
            xml = http_get(url, timeout=25)
        except Exception as exc:
            raise SourceError("Could not list the bucket:\n%s" % exc)
        if "<Key>" not in xml and "<ListBucketResult" not in xml:
            return None
        out = []
        # one <Contents> block per object: it carries the size and the date
        # as well as the key, and the upload check wants all three
        for blob in re.findall(r"<Contents>(.*?)</Contents>", xml, re.S):
            m_key = re.search(r"<Key>(.*?)</Key>", blob, re.S)
            if not m_key:
                continue
            k = html.unescape(m_key.group(1))
            if k.endswith("/"):
                continue
            fname = k.split("/")[-1]
            if not fname:
                continue
            m_size = re.search(r"<Size>(\d+)</Size>", blob)
            m_mod = re.search(r"<LastModified>(.*?)</LastModified>", blob,
                              re.S)
            ts, exact = parse_listing_date(m_mod.group(1).strip()
                                           if m_mod else "")
            out.append(RemoteFile(fname, "", "%s/%s"
                                  % (self.base,
                                     urllib.parse.quote(k, safe="/")),
                                  int(m_size.group(1)) if m_size else 0,
                                  False, ts, exact))
        return out or None

    def audio_url(self, f):
        return f.url

    def image_url(self, f):
        return f.url

    def raw_url(self, f):
        return f.url

    def probe(self, f):
        return head_info(f.url)

    def key(self):
        return "s3:" + self.base

    def folder_title(self):
        return self.base.split("//")[-1].split(".")[0]

    def describe(self):
        return "S3 bucket " + self.base


# ----------------------------------------------------------------- Local folder
class LocalFolderSource:
    """A folder on this computer.  Useful to build and test before uploading.

    The generated page then points at relative paths (MP3/... , Cover/...),
    so you can upload the whole folder to any web host.
    """

    kind = "local"

    def __init__(self, main_address, **_):
        p = (main_address or "").strip().strip('"')
        if not p or not os.path.isdir(p):
            raise SourceError("Not a folder:\n%s" % p)
        self.base = os.path.abspath(p)

    def list_folder(self, name):
        d = os.path.join(self.base, name)
        if not os.path.isdir(d):
            for entry in os.listdir(self.base):
                if entry.casefold() == name.casefold() and \
                        os.path.isdir(os.path.join(self.base, entry)):
                    d = os.path.join(self.base, entry)
                    break
            else:
                return None
        out = []
        for entry in sorted(os.listdir(d)):
            full = os.path.join(d, entry)
            if os.path.isfile(full):
                try:
                    st = os.stat(full)
                    size, mtime = st.st_size, st.st_mtime
                except OSError:
                    size, mtime = 0, 0.0
                out.append(RemoteFile(entry, full, full, size,
                                      False, mtime, True))
        return out

    def audio_url(self, f):
        # The real path on disk.  A relative one would break the moment the
        # output folder sits somewhere else - or the moment a second group
        # with a different base folder joins in.  build_site copies these
        # into the output folder instead.
        return f.url

    def image_url(self, f):
        return f.url

    def raw_url(self, f):
        return f.url

    def probe(self, f):
        try:
            st = os.stat(f.url)
            return st.st_size, st.st_mtime, True
        except OSError:
            return 0, 0.0, False

    def key(self):
        return "local:" + self.base.casefold()

    def folder_title(self):
        return os.path.basename(self.base.rstrip("\\/")) or self.base

    def describe(self):
        return "Local folder " + self.base


SOURCE_TYPES = {
    "Google Drive (share link)": GoogleDriveSource,
    "Web folder (http/https)": HttpFolderSource,
    "S3 bucket (public)": S3Source,
    "Local folder (this PC)": LocalFolderSource,
}


def make_source(type_name, address, api_key="", audio_style="",
                image_style=""):
    cls = SOURCE_TYPES.get(type_name)
    if cls is None:
        raise SourceError("Unknown source type: %s" % type_name)
    if cls is GoogleDriveSource:
        return cls(address, api_key=api_key, audio_style=audio_style,
                   image_style=image_style)
    return cls(address)


# ------------------------------------------------------------ backup sources
# ToDo: a BACKUP source holds the SAME files (same file names, same MP3 /
# Cover sub-folders) somewhere else - a second Drive folder when the first is
# full, a folder on a web server.  Fetch finds every song's file there BY
# NAME and keeps the addresses in track["alt"][<id>]; the built page gets a
# switch "Download from: Original | Backup" that re-points the audio and the
# covers.  A web page cannot see whether a Drive file still exists, so the
# page never switches by itself - the visitor presses the button.
def guess_source_type(address):
    """Which SOURCE_TYPES entry an address belongs to (a backup line has no type box)."""
    a = (address or "").strip()
    if re.match(r"^([A-Za-z]:[\\/]|\\\\)", a):
        return "Local folder (this PC)"
    if re.match(r"^https?://", a, re.I):
        if "drive.google.com" in a or "docs.google.com" in a:
            return "Google Drive (share link)"
        if "amazonaws.com" in a.lower():
            return "S3 bucket (public)"
        return "Web folder (http/https)"
    return "Google Drive (share link)"


def parse_backups(text):
    """Read the 'Backup source(s)' box.  One backup per line:  Name | address  (one address per section, in the same order as the
    main folders, when the main box has several lines:  Name | address 1 | address 2).  A line with only an address gets the
    name 'Backup N'.  Blank lines and lines starting with # are ignored.  -> [{"id", "name", "addresses"}]"""
    out, taken = [], {"main"}
    for line in (text or "").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        parts = [p.strip() for p in line.split("|")]
        if len(parts) == 1:
            name, addrs = "Backup %d" % (len(out) + 1), parts
        else:
            name, addrs = parts[0], parts[1:]
        addrs = [a for a in addrs if a]
        if not addrs:
            continue
        base = slugify(name) if name else "backup"
        cand, n = base, 2
        while cand in taken:
            cand = "%s-%d" % (base, n)
            n += 1
        taken.add(cand)
        out.append({"id": cand, "name": name or "Backup", "addresses": addrs})
    return out


def scan_backups(cfg, groups, tracks, rep, say=None):
    """Find every track's audio file and cover on each backup source, BY FILE NAME.  Sets track["alt"] = {backup id: {"audio": url,
    "cover": url}} (a track that is not found there has no entry; a backup that could not be read keeps what it had)."""
    say = say or (lambda m: None)
    backups = parse_backups(cfg.get("backups", ""))
    ids = {b["id"] for b in backups}
    for t in tracks:
        t["alt"] = {k: v for k, v in (t.get("alt") or {}).items() if k in ids}
    for b in backups:
        for gi, g in enumerate(groups):
            gname = g.get("resolved_name", "")
            mine = [t for t in tracks if t.get("group", "") == gname]
            label = "Backup '%s'%s" % (b["name"], (" / " + gname) if gname else "")
            if gi < len(b["addresses"]):
                addr = b["addresses"][gi]
            else:
                rep("%s: no address for this section - the page keeps the original links for it." % label)
                continue
            say("Reading %s ..." % label)
            try:
                src = make_source(guess_source_type(addr), addr, cfg.get("api_key", ""), cfg.get("audio_style", ""),
                                  cfg.get("image_style", ""))

                def names(folder):
                    items = src.list_folder(folder) if folder.strip() else None
                    return {f.name.casefold(): f for f in (items or [])}
                audio, covers = names(cfg.get("audio_folder", "MP3")), names(cfg.get("cover_folder", "Cover"))
            except SourceError as exc:
                rep("%s: FAILED - %s  (what was found before is kept)" % (label, str(exc).splitlines()[0]))
                continue
            except Exception as exc:
                rep("%s: FAILED - %s  (what was found before is kept)" % (label, exc))
                continue
            got = missing = with_cover = 0
            lost = []
            for t in mine:
                af = audio.get((t.get("audio_name") or "").casefold())
                cf = covers.get((t.get("cover_name") or "").casefold()) if t.get("cover_name") else None
                if af is None:
                    t["alt"].pop(b["id"], None)
                    missing += 1
                    lost.append(t.get("audio_name") or t.get("title", "?"))
                    continue
                alt = {"audio": src.audio_url(af)}
                if cf is not None:
                    alt["cover"] = src.image_url(cf)
                    with_cover += 1
                t["alt"][b["id"]] = alt
                got += 1
            rep("%s: %d of %d song(s) found, %d with a cover%s" % (label, got, len(mine), with_cover,
                                                                      ("; NOT FOUND: " + ", ".join(lost[:8]) +
                                                                       (" ..." if len(lost) > 8 else "")) if lost else ""))
            if not audio:
                rep("   (nothing in the '%s' sub-folder there - is the address the MAIN folder, like the original one?)"
                    % cfg.get("audio_folder", "MP3"))


def probe_embeddable(url, dest="audio", timeout=25):
    """Ask for a file exactly the way a browser <audio> / <img> tag will.

    This matters more than it looks.  A plain download can succeed while the
    very same URL is refused to a web page, because the browser always adds
    'Sec-Fetch-Site: cross-site' to requests for files on another site, and
    some hosts answer 403 to that on purpose.

    Google Drive does exactly this for audio: a download works, embedding on
    your own page does not.  Its image/thumbnail endpoint is fine.

    Returns (ok, detail).
    """
    if not re.match(r"^https?://", url or ""):
        return True, "local file - nothing to check"
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": ("audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,*/*;q=0.5"
                   if dest == "audio" else "image/avif,image/webp,*/*"),
        "Sec-Fetch-Dest": dest,
        "Sec-Fetch-Mode": "no-cors",
        "Sec-Fetch-Site": "cross-site",
        "Range": "bytes=0-2047",
    }
    want = "audio" if dest == "audio" else "image"
    try:
        req = urllib.request.Request(url, headers=headers)
        with urllib.request.urlopen(req, timeout=timeout) as r:
            ctype = (r.headers.get("Content-Type") or "").lower()
            r.read(2048)
            if want in ctype or "octet-stream" in ctype:
                return True, "HTTP %s, %s" % (r.status, ctype)
            return False, ("HTTP %s, but the host answered with '%s' instead "
                           "of %s data" % (r.status, ctype or "?", want))
    except urllib.error.HTTPError as exc:
        if exc.code in (403, 401):
            return False, ("HTTP %s - the host refuses to let another web "
                           "page embed this file" % exc.code)
        return False, "HTTP %s" % exc.code
    except Exception as exc:
        return False, "%s: %s" % (type(exc).__name__, exc)


HOTLINK_WARNING = (
    "The audio files are hosted somewhere that will not let your own web "
    "page play them.\n\n"
    "Google Drive is the usual case. It hands the file over to a download, "
    "but answers 403 Forbidden when a browser asks for it on behalf of an "
    "<audio> player on another site. Every Drive link format behaves the "
    "same way, so switching the link style will not help - this is a "
    "deliberate limit on Google's side, not a broken link.\n\n"
    "Covers and lyrics are NOT affected. Only the sound is.\n\n"
    "Three ways forward:\n\n"
    "  1. Put the audio on your own web server - the one you upload the\n"
    "     page to. On the Site tab set 'Audio handling' to 'Download the\n"
    "     audio into the output folder', press Build, and upload the whole\n"
    "     folder. MusicSite fetches your own files for you.\n\n"
    "  2. Point the Source at your web server instead ('Web folder'), with\n"
    "     MP3/ Cover/ Text/ inside it. Nothing else changes.\n\n"
    "  3. Use an object store built for this: Scaleway or OVH (France),\n"
    "     Infomaniak kDrive (Switzerland), Hetzner (Germany), Backblaze B2,\n"
    "     or your own Nextcloud. Use the 'S3 bucket' source type.\n\n"
    "The page will still be built, so you can look at it - but the play\n"
    "buttons will not produce sound until the audio moves.")


def fetch_text_file(src, f, limit=200000):
    """Download a lyrics/description file and return it as text."""
    try:
        if isinstance(src, LocalFolderSource):
            with open(f.url, "rb") as fh:
                data = fh.read(limit)
        else:
            data = http_get(src.raw_url(f), timeout=25, binary=True)[:limit]
        for enc in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):
            try:
                return data.decode(enc)
            except Exception:
                continue
        return data.decode("utf-8", "replace")
    except Exception as exc:
        log("Could not read text file %s: %s" % (f.name, exc), "WARN")
        return ""


# *****************************************************************************
# DEL 08 - PROJECT MODEL  (tracks + site settings, saved as one .msite file)
# *****************************************************************************
DEFAULT_SITE = {
    "site_title": "My Music",
    "artist": "",
    "tagline": "",
    "about": "",
    "accent": "#e8663a",
    "theme": "auto",                 # auto | dark | light
    "show_downloads": True,
    "show_lyrics": True,
    "show_search": True,
    "show_shuffle": True,
    "autoplay_next": True,
    "footer_text": "",
    "links": [],                     # [{"label": "...", "url": "..."}]
    # The box at the bottom of the page: your own words about what the music
    # costs, and the ways somebody can pay if they want to.  Every part of it
    # is yours to write - nothing here is fixed in the program.
    "show_support": True,
    "support_title": "If you like it",
    "support_text": (
        "The music here is free.  Listen to as much of it as you like, and "
        "download whatever you want to keep.\n\n"
        "If you think it is worth something, you decide what - and which "
        "way suits you.  Any of the links below reaches me.  And if you "
        "would rather just listen, that is perfectly fine too."),
    "support_links": [
        {"label": "Revolut", "url": "https://revolut.me/lars72oeh"},
        {"label": "PayPal", "url": "https://paypal.me/issusbarn"},
        {"label": "Wise", "url": "https://wise.com/pay/me/larsdenniso"},
    ],
    "show_made": True,               # the "Built with MusicSite" line
    # The Android app box at the top of the page (DEL 11).  The address may be
    # a Google Drive "share" link - the page gets the direct-download form.
    "show_app": True,
    "app_title": "Get the Android app",
    "app_text": (
        "There is a free app for Android phones and tablets.  It plays every "
        "song on this page - also with the screen off - and lets you save "
        "songs on the phone to listen without a connection.  You can search "
        "by title, words, who wrote them, who else took part and who a song "
        "is dedicated to, and the discography and the about page are in it "
        "too."),
    "app_url": "https://drive.google.com/file/d/"
               "1YPAoh85isJeE8c9O_6FIne4E7tR38yS4/view?usp=sharing",
    "app_button": "Download the app (APK)",
    "cover_mode": "remote",          # remote | local  (download covers)
    "audio_mode": "remote",          # remote | local  (download the mp3s)
    "player_mode": "auto",           # auto | player | download
    "page_filename": "index.html",
    "sort_mode": "alpha",            # alpha | own  (order on the page)
    # ---- the extra pages (DEL 11b / 11c) ---------------------------------
    "show_discography": True,        # discography.html + the #N numbers
    "disco_title": "Discography",
    "disco_intro": "",               # a few words above the releases
    "show_aboutpage": True,          # about.html
    "aboutpage_title": "About me",
    "aboutpage_text": "",            # empty = a "coming soon" line
    "aboutpage_image": "",           # optional picture address
}
# the site settings that belong to the extra pages (a new project keeps them)
PAGE_SITE_KEYS = ("show_discography", "disco_title", "disco_intro",
                  "show_aboutpage", "aboutpage_title", "aboutpage_text",
                  "aboutpage_image")

DEFAULT_SOURCE = {
    "type": "Google Drive (share link)",
    "address": "",
    "folders": "",                   # one group per line: "Name | address"
    "backups": "",                   # one BACKUP source per line: "Name | address [| address 2 ...]" (parse_backups)
    "audio_folder": "MP3",
    "cover_folder": "Cover",
    "text_folder": "Text",
    "api_key": "",
    "audio_style": "usercontent (recommended)",
    "image_style": "thumbnail (recommended)",
    "drop_track_numbers": True,
    "fuzzy_cutoff": 0.84,
    # his own lyric files on this computer, one path per line: the chords
    # and his private notes in them are never published (DEL 08b)
    "lyrics_files": "",
    # the ONE file with everybody else's credits (DEL 08c)
    "credits_file": "",
    # ---- upload check (DEL 09b) ----------------------------------------
    # The folders on THIS disk that the cloud folders are a copy of.  One
    # line per group, same order as 'folders', or "Name | C:\\path".
    "local_folders": "",
    "deep_check": True,        # ask the cloud for exact size + date
    # songs, covers and lyrics are ALWAYS compared - these two only decide
    # what is worth showing in the list afterwards
    "hide_cover": False,
    "hide_text": False,
    "tolerance_min": 5,        # clock slack before "newer" is believed
    "stage_dir": "",           # empty = STAGE_DIR_DEFAULT
    # ---- tags in the mp3 files (DEL 08d) -------------------------------
    "auto_tag": True,          # tag the local mp3s before every comparison
    "tag_cover": False,        # also put the cover picture inside the file
    "tag_keep_original": True,  # copy the untouched file once, before 1st edit
}


class Track(dict):
    """A track is a plain dict so it saves to JSON without any ceremony."""

    FIELDS = ("key", "title", "artist", "year", "description", "lyrics",
              "audio_url", "audio_name", "cover_url", "cover_name",
              "text_name", "hidden", "order", "match_note", "duration",
              "group", "lyrics_src", "lyrics_keep", "lyrics_drop",
              "lyrics_by", "lyrics_by_src", "credits",
              "made", "about_person", "released", "cover_hand")

    @staticmethod
    def new(key="", title="Untitled"):
        return Track({
            "key": key, "title": title, "artist": "", "year": "",
            "description": "", "lyrics": "", "audio_url": "",
            "audio_name": "", "cover_url": "", "cover_name": "",
            "text_name": "", "hidden": False, "order": 0,
            "match_note": "", "duration": "", "group": "",
            "lyrics_src": "", "lyrics_keep": [], "lyrics_drop": [],
            "lyrics_by": "", "lyrics_by_src": "", "credits": [],
            # the "?" popup on the page: when it was made (a date, a month
            # or just a year), who it is about, and every earlier release
            # [{"medium": "Cassette", "title": "...", "when": "1994"}]
            "made": "", "about_person": "", "released": [],
            # True = the cover was chosen by hand ("Set cover..." / "Share
            # cover"); Fetch leaves it alone, even an empty one
            "cover_hand": False,
            # the same song's files on the BACKUP sources (Fetch fills it):
            # {backup id: {"audio": url, "cover": url}}
            "alt": {},
        })


class Project:
    def __init__(self):
        self.path = ""
        self.source = dict(DEFAULT_SOURCE)
        self.site = dict(DEFAULT_SITE)
        self.tracks = []
        self.cover_files = []            # the cloud's Cover folder, last Fetch
        self.discography = []            # the releases, #1 first (DEL 08f)
        self.last_pages = []             # every page the last build wrote
        self.output_dir = OUT_DIR_DEFAULT
        self.dirty = False
        self.last_warning = ""

    # -- persistence --------------------------------------------------------
    def to_dict(self):
        return {
            "app": APP_NAME, "version": APP_VERSION,
            "saved": datetime.now().isoformat(timespec="seconds"),
            "source": self.source, "site": self.site,
            "output_dir": self.output_dir,
            "cover_files": self.cover_files,
            "discography": [dict(r) for r in self.discography],
            "tracks": [dict(t) for t in self.tracks],
        }

    def load(self, path):
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
        self.source = dict(DEFAULT_SOURCE)
        self.source.update(data.get("source", {}))
        self.site = dict(DEFAULT_SITE)
        self.site.update(data.get("site", {}))
        self.output_dir = data.get("output_dir") or OUT_DIR_DEFAULT
        self.cover_files = list(data.get("cover_files") or [])
        raw = [r for r in (data.get("discography") or [])
               if isinstance(r, dict)]
        self.discography = [new_release(r) for r in raw]
        if raw and not any("hidden" in r for r in raw):
            # a list from before releases could be hidden: the other group's
            # releases (Loss) stay off the Issus barn page until he decides
            hide_foreign_groups(self.discography)
        self.tracks = []
        for i, t in enumerate(data.get("tracks", [])):
            tr = Track.new()
            tr.update(t)
            tr["order"] = t.get("order", i)
            self.tracks.append(tr)
        self.tracks.sort(key=lambda t: t.get("order", 0))
        self.path = path
        self.dirty = False

    def save(self, path=None):
        path = path or self.path
        if not path:
            raise ValueError("No project path")
        for i, t in enumerate(self.tracks):
            t["order"] = i
        # a copy of the previous version BEFORE it is overwritten
        if os.path.isfile(path):
            try:
                make_backup(path)
            except Exception as exc:
                log_exception("project backup", exc)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(self.to_dict(), f, indent=2, ensure_ascii=False)
        os.replace(tmp, path)
        self.path = path
        self.dirty = False
        log("Project saved: %s (%d tracks)" % (path, len(self.tracks)))


def make_backup(path):
    """Copy PATH into Backups with the date as a SUFFIX.

    index.html -> index_2026_10_27.html.  When that name is taken (a second
    backup the same day) the time is added too: index_2026_10_27_143015.html,
    and a counter after that if even the second is taken.  Never onto an
    existing backup.  Returns the backup's path.
    """
    name = os.path.basename(path)
    stem, ext = os.path.splitext(name)
    now = datetime.now()
    day = now.strftime("%Y_%m_%d")
    dest = os.path.join(BAK_DIR, "%s_%s%s" % (stem, day, ext))
    if os.path.exists(dest):
        stamp = "%s_%s" % (day, now.strftime("%H%M%S"))
        dest = os.path.join(BAK_DIR, "%s_%s%s" % (stem, stamp, ext))
        n = 2
        while os.path.exists(dest):
            dest = os.path.join(BAK_DIR, "%s_%s-%d%s" % (stem, stamp, n, ext))
            n += 1
    shutil.copy2(path, dest)
    prune_backups(name)
    return dest


def prune_backups(prefix, keep=40):
    """Keep the newest KEEP backups of one file.  The suffix names
    (<name>_<date>[_<time>].<ext>), the older BACKUP_<stamp>_<name> ones and
    the oldest <name>_<stamp>.bak ones all count together."""
    stem, ext = os.path.splitext(prefix)
    new_style = re.compile(r"^%s_\d{4}_\d{2}_\d{2}(_\d{6})?(-\d+)?%s$"
                           % (re.escape(stem), re.escape(ext)))
    try:
        files = sorted((f for f in os.listdir(BAK_DIR)
                        if new_style.match(f)
                        or (f.startswith("BACKUP_") and f.endswith("_" + prefix))
                        or (f.startswith(prefix + "_") and f.endswith(".bak"))),
                       key=lambda f: os.path.getmtime(os.path.join(BAK_DIR, f)),
                       reverse=True)
        for old in files[keep:]:
            os.remove(os.path.join(BAK_DIR, old))
    except Exception:
        pass


# *****************************************************************************
# DEL 08f - DISCOGRAPHY  (the releases, and which songs were on which)
#   A release is a plain dict (saved in the .msite under "discography"):
#   its number (#1, #2 ...) is its POSITION in the list, so putting one in
#   another place renumbers everything and the page follows by itself.
#   "tracks" is a list of lines: a song title, or a side marker "A)" / "B)".
#   The songs on the music page get their release numbers by matching titles
#   (match_discography) - nothing is linked by hand, the same way lyrics and
#   covers find their songs.
# *****************************************************************************
RELEASE_FIELDS = ("title", "group", "year", "dates", "where", "format",
                  "released", "copies", "count", "note", "credits")
SIDE_MARK_RE = re.compile(r"^\s*([A-Za-z])\s*\)\s*$")
# a song may end with *  **  *1  *2 ...  (several: "* *2" or "*1, *2") and a
# line in the release's credits box may start with the same mark: that credit
# then belongs to the marked songs only; an unmarked credit is for them all
SONG_MARK_TAIL_RE = re.compile(r"\s*((?:\*+\d*)(?:[\s,]*\*+\d*)*)\s*$")
CREDIT_MARK_HEAD_RE = re.compile(r"^\s*((?:\*+\d*)(?:[\s,]*\*+\d*)*)\s+(\S.*)$")
DMY_RE = re.compile(r"^\s*(\d{1,2})\s*/\s*(\d{1,2})\s+(\d{4})\s*$")

# row labels of his CSV table (Swedish as he wrote it, English accepted too)
CSV_LABELS = {
    "grupp": "group", "group": "group", "band": "group",
    "titel": "title", "title": "title",
    "år": "year", "ar": "year", "year": "year",
    "datum": "dates", "dates": "dates", "date": "dates",
    "var": "where", "where": "where",
    "format": "format",
    "släppt": "released", "slappt": "released", "released": "released",
    "exemplar": "copies", "copies": "copies",
    "låtar": "count", "latar": "count", "songs": "count", "tracks": "count",
}


def norm_date(text):
    """'1/12 1989' -> '1989-12-01' (day/month year, the way the table has
    it).  Anything else - a year, 'Autumn', '1991-02-01' - is left alone."""
    text = str(text or "").strip()
    m = DMY_RE.match(text)
    if m:
        d, mo, y = int(m.group(1)), int(m.group(2)), int(m.group(3))
        if 1 <= d <= 31 and 1 <= mo <= 12:
            return "%04d-%02d-%02d" % (y, mo, d)
    return text


def normalize_tracks(lines):
    """The tracklist the way it is kept: trimmed lines, ONE blank line is
    allowed (none at the ends), and a blank line is put above every side
    marker except the first line - so  B)  always stands apart from side A
    (a release that begins with a lone  B)  gets none)."""
    out = []
    for x in lines:
        x = str(x).strip()
        if not x:
            if out and out[-1] != "":
                out.append("")
            continue
        if SIDE_MARK_RE.match(x) and out and out[-1] != "":
            out.append("")
        out.append(x)
    while out and out[-1] == "":
        out.pop()
    return out


def split_song_marks(line):
    """'Hej gay *1' -> ('Hej gay', ['*1']);  no mark -> (line, [])."""
    line = str(line or "")
    m = SONG_MARK_TAIL_RE.search(line)
    if not m or not line[:m.start()].strip():
        return line.strip(), []
    return line[:m.start()].strip(), re.findall(r"\*+\d*", m.group(1))


def split_credit_marks(line):
    """'*1 Bo Berg, guitar' -> (['*1'], 'Bo Berg, guitar'); no mark -> ([], line)."""
    m = CREDIT_MARK_HEAD_RE.match(str(line or ""))
    if not m:
        return [], str(line or "").strip()
    return re.findall(r"\*+\d*", m.group(1)), m.group(2).strip()


def new_release(src=None):
    """A release with every field present (text), tracks as a list of lines,
    and 'hidden' (True = left out of the pages, number kept)."""
    r = {k: "" for k in RELEASE_FIELDS}
    r["tracks"] = []
    r["hidden"] = False
    if isinstance(src, dict):
        for k in RELEASE_FIELDS:
            r[k] = str(src.get(k, "") or "").strip()
        r["released"] = norm_date(r["released"])
        r["tracks"] = normalize_tracks(src.get("tracks") or [])
        r["hidden"] = bool(src.get("hidden"))
    return r


def hide_foreign_groups(releases):
    """Hide every release that is not by the main group (the group most of
    the releases belong to - Issus barn, not Loss).  Returns how many were
    hidden.  Only used when a list has no choice made yet."""
    groups = [r.get("group", "") for r in releases if r.get("group")]
    if not groups:
        return 0
    main = max(set(groups), key=groups.count)
    n = 0
    for r in releases:
        if r.get("group") and r["group"] != main:
            r["hidden"] = True
            n += 1
    return n


def parse_discography_csv(path):
    """His table: ONE COLUMN PER RELEASE, left to right = #1, #2 ...

    The first rows are labelled in column A (Grupp, Titel, År, Datum, Var,
    Format, Släppt, Exemplar, Låtar); the row after them holds the side each
    list starts with (A) / B)); every row below is the next song of each
    release, and a cell "B)" in the middle of a list starts the B side.
    Returns a list of releases.  ValueError when it is not such a table.
    """
    import csv
    text = read_text_any(path)
    rows = [r for r in csv.reader(io.StringIO(text))]
    width = max((len(r) for r in rows), default=0)
    rows = [r + [""] * (width - len(r)) for r in rows]

    labelled, first_free = {}, 0
    for i, r in enumerate(rows):
        lab = CSV_LABELS.get(unicodedata.normalize("NFC", r[0]).strip()
                             .casefold())
        if not lab or lab in labelled:
            break
        labelled[lab] = i
        first_free = i + 1
    if "title" not in labelled:
        raise ValueError("This does not look like the discography table: "
                         "no row called 'Titel' (title) at the top.")

    start = first_free
    side_row = None
    if start < len(rows) and any(SIDE_MARK_RE.match(c) for c in rows[start][1:]):
        side_row = rows[start]
        start += 1

    out = []
    for j in range(1, width):
        rel = new_release()
        for lab, i in labelled.items():
            rel[lab] = rows[i][j].strip()
        lines = []
        if side_row is not None and SIDE_MARK_RE.match(side_row[j]):
            lines.append(side_row[j].strip())
        for r in rows[start:]:
            cell = r[j].strip()
            if cell:
                lines.append(cell)
        rel["tracks"] = lines
        if rel["title"] or lines:
            out.append(new_release(rel))        # tidies dates and tracklist
    if not out:
        raise ValueError("The table has no releases in it.")
    hide_foreign_groups(out)                    # Loss is not on the Issus barn page
    return out


def disco_layout(release):
    """The tracklist ready to show:
    [("side", "Side A") | ("gap",) | ("track", n, title, line index, marks)].

    A side heading is only worth showing when there really are two sides;
    a lone 'B)' at the top of a CD would just be noise.  The line index is
    the song's place in release["tracks"] (what match_discography keys on);
    marks are the *, *1 ... after the title (the title is without them).
    A blank line is a small gap, except next to a side heading.
    """
    lines = release.get("tracks") or []
    nsides = sum(1 for x in lines if SIDE_MARK_RE.match(x))
    out, n = [], 0
    for li, x in enumerate(lines):
        m = SIDE_MARK_RE.match(x)
        if m:
            if nsides >= 2:
                out.append(("side", "Side " + m.group(1).upper()))
            continue
        if not x.strip():
            if out and out[-1][0] == "track":
                out.append(("gap",))
            continue
        n += 1
        title, marks = split_song_marks(x)
        out.append(("track", n, title, li, marks))
    while out and out[-1][0] == "gap":
        out.pop()
    # a gap right above a heading is the heading's own space
    return [e for i, e in enumerate(out)
            if not (e[0] == "gap" and i + 1 < len(out)
                    and out[i + 1][0] == "side")]


def disco_song_count(release):
    return sum(1 for x in (release.get("tracks") or [])
               if x.strip() and not SIDE_MARK_RE.match(x))


def release_label(release):
    """'Predikar kärlek - LP, 1989' (used in tooltips and the report)."""
    tail = ", ".join(x for x in (release.get("format", ""),
                                 release.get("year", "")) if x)
    return (release.get("title") or "(no title)") + (" - " + tail if tail
                                                     else "")


def disco_key(text):
    """Title -> comparison key: no case, no punctuation, one space."""
    s = unicodedata.normalize("NFC", str(text or "")).casefold()
    return re.sub(r"\s+", " ", re.sub(r"[\W_]+", " ", s)).strip()


def disco_base_key(text):
    """The same without a bracket at the end: 'Weep (final version)' -> weep."""
    return disco_key(re.sub(r"\s*[\(\[][^\)\]]*[\)\]]\s*$", "",
                            str(text or "")))


def match_discography(releases, tracks, include_hidden=False):
    """Which songs on the page were on which release.  A hidden release
    counts for nothing (unless INCLUDE_HIDDEN), but keeps its number.

    Returns (rel_of, link_of, how):
      rel_of   {track index: [release numbers]}   (#1 = first release)
      link_of  {(release index, line index): track index}
      how      [(kind, release number, line, track title)] for every match that
               was NOT an exact title - so a wrong guess is easy to spot.
    Order of trust: the same title; the same title when the release's line has
    a bracket at the end ('Weep (final version)' = the song 'Weep'); a title
    cut off with '...'; then a close spelling (never when only a digit
    differs: 'Andreas' is not 'Andreas 2').
    """
    keys = {}                                 # key -> [track index]
    for i, t in enumerate(tracks):
        if t.get("hidden"):
            continue
        keys.setdefault(disco_key(t.get("title")), []).append(i)
    key_list = [k for k in keys if k]

    rel_of, link_of, how = {}, {}, []
    for ri, rel in enumerate(releases):
        if rel.get("hidden") and not include_hidden:
            continue
        for li, line in enumerate(rel.get("tracks") or []):
            if SIDE_MARK_RE.match(line):
                continue
            line = split_song_marks(line)[0]       # without the * marks
            k = disco_key(line)
            if not k:
                continue
            kind, hit = "", keys.get(k)
            if hit:
                kind = "exact"
            if not hit:
                bk = disco_base_key(line)
                if bk and bk != k and bk in keys:
                    hit, kind = keys[bk], "base title"
            if not hit and re.search(r"(\.\.\.|…)\s*$", line):
                stem = disco_key(re.sub(r"(\.\.\.|…)\s*$", "", line))
                if len(stem) >= 10:
                    cand = [kk for kk in key_list if kk.startswith(stem)]
                    if len(cand) == 1:
                        hit, kind = keys[cand[0]], "cut off"
            if not hit and len(k) >= 6:
                nodigit = re.sub(r"\d+", "", k).strip()
                for kk in difflib.get_close_matches(k, key_list, n=3,
                                                    cutoff=0.86):
                    if re.sub(r"\d+", "", kk).strip() == nodigit:
                        continue               # 'andreas' vs 'andreas 2'
                    hit, kind = keys[kk], "similar"
                    break
            if not hit:
                continue
            for idx in hit:
                nums = rel_of.setdefault(idx, [])
                if ri + 1 not in nums:
                    nums.append(ri + 1)
            link_of[(ri, li)] = hit[0]
            if kind != "exact":
                how.append((kind, ri + 1, line,
                            tracks[hit[0]].get("title", "")))
    for nums in rel_of.values():
        nums.sort()
    return rel_of, link_of, how


# *****************************************************************************
# DEL 08b - LYRICS FILES  (one big file with every song in it)
#
#   His words do not live one-file-per-song.  They live in a handful of big
#   files where the songs are separated by a line of dashes, the title is on
#   top in CAPITALS - and under the words stand the CHORDS, the running
#   order of the song, and older versions of lines he has since rewritten.
#   All of that is for him, not for the web page:
#
#       DAGS ATT SOMNA IN            <- title
#                                       (blank)
#       Vid första glaset ...        <- the words, these are published
#       ...
#       Vers : Cx16 D#x8 Gx8         <- his chords          NOT published
#       (ORIGINAL)                   <- and everything      NOT published
#       Vid första glaset ...           under it is the     NOT published
#       Vid andra glaset ...            older version       NOT published
#
#   Measured on his own file (431 songs, 9 600 lines): 3 658 chord lines,
#   61 running orders and 319 private notes are dropped, 5 638 lines of
#   words are kept, and ten lines in the whole file are judged wrongly -
#   all of them chord rows written half in prose ("Synth: (samma som grund,
#   fast R: = Dx4 ...)").  "Check the lyrics" shows every dropped line so
#   nothing has to be taken on faith.
# *****************************************************************************
LYRIC_SEP = re.compile(r"^[-*=_]{8,}[ \t\r]*$", re.M)

# a label at the start of a chord row: "V:", "Int:", "St1:", "Vers :", "Gång 2:"
LYRIC_LABEL = re.compile(r"^\s*([A-Za-zÅÄÖåäö0-9#½.'/+\- ]{1,14}?)\s*:\s*(.*)$")
CHORD_LABELS = {
    "int", "in", "v", "vers", "verse", "r", "ref", "refr", "st", "stick",
    "o", "out", "outro", "i", "s", "x", "hh", "vh", "bas", "bas-r", "brygga",
    "b", "slut", "solo", "intro", "mellanspel", "kör", "coda", "gång", "ggr",
    "del", "takt", "a", "c", "d", "e", "f", "g", "h", "synth", "piano",
    "marimba", "gitarr", "trummor", "orgel", "stråkar", "cello", "fiol",
    "flöjt", "melodi", "sång", "start",
}
# one chord or tab token: A, Bm, F#x8, D#, 3+x4, 0+, A+D+F#, |, ., x4, X, ½, ↑
_CHORD = r"[A-H](?:\#|b)?(?:m|maj|min|dim|sus|aug|add|M)?\d*"
_FRET = r"\d+[+\-]*(?:m|maj)?"
# a repeat count may be written x8, X8, x1,5 or X3.5 - halves and all
_TIMES = r"[xX]\d+(?:[.,]\d+)?"
CHORD_TOKEN = re.compile(
    r"^(?:%s(?:\+%s)*\+?|%s|[xX]\d*|%s|[xX]\?+|\?+|[|,.\-/½↑↓()]+)"
    r"(?:%s|[xX]\?+)?[,.]*$" % (_CHORD, _CHORD, _FRET, _TIMES, _TIMES))
# a run of note names: DEFE, ACDC, .AAAAAAGG, B***
NOTE_RUN = re.compile(r"^[.,*|↑↓]*[A-H][A-H#b.,*|↑↓x0-9]{1,}$")
LYRIC_WORDY = re.compile(r"[A-Za-zÅÄÖÜÉåäöüéÆØæøÀ-ÿ]{3,}")
PARENS = re.compile(r"\([^()]*\)")
# proof that a row is about music and not about life
CHORD_PROOF = re.compile(r"[|↑↓½]|[xX]\d|[A-H](?:#|b)|[A-H]m\b|\bx\?|\d[+\-]")
# words that turn up INSIDE a chord row and mean nothing else there
CHORD_WORDS = {
    "tom", "alla", "gitarr", "utan", "men", "och", "med", "samma", "som",
    "sedan", "del", "gang", "gången", "mongoackord", "cakewalk", "finns",
    "ackord", "extra", "borttaget", "original", "ggr", "takt", "takter",
    "bara", "hela", "slut", "fade", "out", "solo", "riff", "bas", "intro",
    "stick", "vers", "ref", "refr", "refräng", "brygga", "outro", "obs",
    "resp", "ändrat", "halvtoner", "kör", "mellanspel", "sången", "andra",
    "första", "tredje",
}
# the running order of a song: "Int, V, R, St1, ½St1, St2"
_ITEM = r"(?:½|\d+x)?(?:[A-Za-zÅÄÖåäö]{1,6}\d*|\d{1,2})"
LYRIC_STRUCTURE = re.compile(r"^\s*%s(?:\s*[,+]\s*%s)+\s*,?\s*$"
                             % (_ITEM, _ITEM))
LYRIC_SECTION = re.compile(
    r"(?<![A-Za-zÅÄÖåäö])(int|v|r|st|out|o|i|s|ref)\d*(?![A-Za-zÅÄÖåäö])",
    re.I)
# notes to himself.  ORIGINAL also means "everything below is the old version"
PRIVATE_MARK = re.compile(
    r"^\s*\(?\s*(original(text)?|orginal|borttaget|struket|extra\??|tom|"
    r"x\d+\s+tom|\?\?\s*tom|mongoackord|(finns\s+)?i(n)?\s+cakewalk)"
    r"\s*\)?\s*[.:]?\s*$", re.I)
OLD_VERSION_MARK = re.compile(r"^\s*\(?\s*(original(text)?|orginal)\s*\)?\s*$",
                              re.I)

LYRIC_KEEP = ("lyric", "blank")


def read_text_any(path):
    """Read a text file whatever it was saved as.

    His lyric files are a mixture: the big chord file is UTF-16, Malin's is
    Windows-1252.  Guessing wrong turns every 'å' into mojibake, so the BOM
    decides when there is one and the rest is tried in turn.
    """
    with open(path, "rb") as f:
        raw = f.read()
    if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
        return raw.decode("utf-16")
    if raw[:3] == b"\xef\xbb\xbf":
        return raw.decode("utf-8-sig")
    for enc in ("utf-8", "cp1252", "latin-1"):
        try:
            return raw.decode(enc)
        except UnicodeDecodeError:
            continue
    return raw.decode("utf-8", "replace")


def _is_chord_label(lab):
    low = (lab or "").strip().casefold().rstrip(".")
    if not low:
        return False
    if low.isdigit() or re.fullmatch(r"\d+x", low):
        return True
    first = low.split()[0] if " " in low else low      # "Gång 2", "Vers 3"
    for cand in (low, first):
        if cand in CHORD_LABELS or cand.rstrip("0123456789+ ") in CHORD_LABELS:
            return True
    return False


def chordish(text):
    """Does this row read as chords, frets and bar lines rather than words?

    Scored, not all-or-nothing: his chord rows carry stray remarks
    ("| X alla (förutom under sången)"), arrows, stars and fret numbers, and
    one unknown token must not turn a chord row back into a line of words.
    """
    body = (text or "").strip()
    for _ in range(4):                         # brackets inside brackets
        new = PARENS.sub(" ", body)
        if new == body:
            break
        body = new
    body = re.sub(r"^\s*[^:\s]{1,10}\s*:\s*", "", body)
    toks = body.split()
    if not toks:
        inner = (text or "").strip()
        return bool(inner.startswith("(") and inner.endswith(")")
                    and CHORD_PROOF.search(inner))
    chords = words = 0
    for tk in toks:
        bare = tk.strip("↑↓*|,.()/-:")
        if not bare:
            chords += 1
        elif CHORD_TOKEN.match(bare) or CHORD_TOKEN.match(tk) or \
                NOTE_RUN.match(tk):
            chords += 1
        elif bare.casefold().rstrip("0123456789") in CHORD_WORDS:
            pass                               # neutral
        elif any(ch.isalpha() for ch in bare):
            # anything with a letter in it that is not a chord is a word -
            # "Ja, ja, ja, ja" is a line of song, and so is a whole verse in
            # Russian, which no A-Z rule would ever recognise
            words += 1
        else:
            chords += 1
    if words or not chords:
        return False
    return bool(CHORD_PROOF.search(body)) or chords > 2


def classify_lyric_line(line, state):
    """One row -> 'lyric', 'blank', 'chord', 'structure' or 'note'."""
    s = (line or "").strip()
    if not s:
        return "blank", ""
    if state.get("old_version"):
        return "note", "under (ORIGINAL)"
    if PRIVATE_MARK.match(s):
        return "note", "a note to himself"
    m = LYRIC_LABEL.match(line)
    if m and _is_chord_label(m.group(1)):
        rest = m.group(2).strip()
        if not rest or chordish(rest) or (rest.startswith("(")
                                          and rest.endswith(")")):
            return "chord", "chords"
    if chordish(s):
        return "chord", "chords"
    # an indented row right under chords is the rest of that chord row
    if state.get("after_chord") and re.match(r"^[ \t]{3,}\S", line) and \
            not re.search(r"[a-zåäöé]{3,}", s):
        return "chord", "the chords continue"
    plain = PARENS.sub(" ", s).replace("|", " ").strip().rstrip(",")
    if LYRIC_STRUCTURE.match(plain) and LYRIC_SECTION.search(plain):
        return "structure", "the running order"
    return "lyric", ""


def analyse_lyrics(body, title=""):
    """Every line of one song, in the order they stand in the file.

    Each row is {"line", "kind", "why", "keep"} - "keep" is what the rules
    decided.  Keeping the whole song in one list, judged line by line, is
    what makes it possible to show him the song afterwards and let him move
    a single line across when a rule got it wrong.
    """
    state = {"after_chord": False, "old_version": False}
    rows = []
    first = True
    for line in (body or "").splitlines():
        kind, why = classify_lyric_line(line, state)
        state["after_chord"] = kind in ("chord", "structure") or \
            (kind == "blank" and state.get("after_chord"))
        if kind == "note" and OLD_VERSION_MARK.match(line.strip()):
            state["old_version"] = True
        if kind in LYRIC_KEEP and first and title and line.strip() and \
                norm_key(line.strip(), False) == norm_key(title, False):
            # the heading, written on top of the block and again on the page
            kind, why = "title", "the page prints the title itself"
        if line.strip():
            first = False
        rows.append({"line": line.rstrip(), "kind": kind, "why": why,
                     "keep": kind in LYRIC_KEEP})
    return rows


def lyrics_from_rows(rows, keep=(), drop=()):
    """The published words, with his own corrections applied.

    'keep' and 'drop' are lines he moved across by hand in "Choose lines".
    They are matched on the text of the line, so they survive the song being
    rewritten around them; a line that occurs twice moves both times, which
    is what you want for a chorus.
    """
    keep_set = {x.strip() for x in (keep or []) if x.strip()}
    drop_set = {x.strip() for x in (drop or []) if x.strip()}
    out = []
    for r in rows:
        text = r["line"]
        stripped = text.strip()
        take = r["keep"]
        if stripped and stripped in keep_set:
            take = True
        if stripped and stripped in drop_set:
            take = False
        if take:
            out.append(text)
    while out and not out[0].strip():
        out.pop(0)
    while out and not out[-1].strip():
        out.pop()
    tidy, blanks = [], 0
    for line in out:                           # never more than one gap
        if line.strip():
            blanks = 0
            tidy.append(line)
        else:
            blanks += 1
            if blanks < 2:
                tidy.append("")
    return "\n".join(tidy)


def clean_lyrics(body, title="", keep=(), drop=()):
    """Split one song into what may be published and what may not.

    Returns (text, dropped) where dropped is [(kind, why, line), ...].
    """
    rows = analyse_lyrics(body, title)
    text = lyrics_from_rows(rows, keep, drop)
    published = set()
    for line in text.splitlines():
        if line.strip():
            published.add(line.strip())
    dropped = [(r["kind"], r["why"], r["line"]) for r in rows
               if r["kind"] not in LYRIC_KEEP and r["kind"] != "title"
               and r["line"].strip() not in published]
    return text, dropped


def lyric_title_keys(title):
    """Every name one song heading could be looked up under."""
    keys = []
    for form in (title,
                 re.split(r"\s+[-–]\s+", title)[0],       # "BADKAR - TILL ..."
                 re.sub(r"\s*\([^()]*\)\s*$", "", title)):  # "... (long ver)"
        k = norm_key(form, False)
        if k and k not in keys:
            keys.append(k)
    return keys


def parse_lyrics_files(text):
    """Read the 'Lyric file(s)' box: one file per line, optionally credited.

    Same shape as everywhere else in this program:

        B:\\Texter\\mina.txt
        Malin Östh | B:\\Texter\\0---Malins.txt

    A name in front means "everything in this file is written by that
    person", and each song out of it carries the credit onto the page.
    """
    out = []
    for line in (text or "").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "|" in line:
            who, path = line.split("|", 1)
            out.append((who.strip(), path.strip().strip('"')))
        else:
            out.append(("", line.strip('"')))
    return out


def build_lyrics_index(paths, say=None):
    """Read the lyric files and index every song in them by title.

    'paths' may be plain paths or (credit, path) pairs.
    """
    say = say or (lambda m: None)
    index, report, songs = {}, [], 0
    for path in paths:
        credit = ""
        if isinstance(path, (tuple, list)):
            credit, path = (path + ("", ""))[:2] if len(path) < 2 else path[:2]
        path = (path or "").strip().strip('"')
        if not path:
            continue
        if not os.path.isfile(path):
            report.append("! There is no file %s" % path)
            continue
        say("Reading %s ..." % os.path.basename(path))
        try:
            text = read_text_any(path)
        except Exception as exc:
            report.append("! Could not read %s (%s)" % (path, exc))
            continue
        here = 0
        for block in LYRIC_SEP.split(text):
            lines = block.splitlines()
            title = next((x.strip() for x in lines if x.strip()), "")
            if not title:
                continue
            rows = analyse_lyrics(block, title)
            body = lyrics_from_rows(rows)
            if not body.strip():
                continue
            here += 1
            dropped = [(r["kind"], r["why"], r["line"]) for r in rows
                       if not r["keep"] and r["kind"] != "title"]
            entry = {"title": title, "text": body, "dropped": dropped,
                     "rows": rows, "file": path, "credit": credit}
            for k in lyric_title_keys(title):
                have = index.get(k)
                # the same song in two files: the one with a WRITER wins,
                # otherwise the first one in the box does as before
                if have is None or (credit and not have.get("credit")):
                    index[k] = entry
        songs += here
        report.append("%s: %d song(s)%s"
                      % (os.path.basename(path), here,
                         "  (words by %s)" % credit if credit else ""))
    return index, report, songs


def fill_lyrics(tracks, index):
    """Give tracks the words out of the lyric files.  Returns (found, missing).

    Used both when reading the source and when a project is opened: the
    words live in his files, not in the project, so a project saved before
    the files were pointed at would otherwise open with empty boxes and
    nothing but a Fetch would explain why.
    """
    found, missing = [], []
    for t in tracks:
        name = t.get("audio_name") or t.get("title", "")
        if t.get("lyrics_src") == "hand":
            # his own words stay - but the file still says who wrote it
            entry, how = find_lyrics(index, name)
            if entry and entry.get("credit") and \
                    t.get("lyrics_by_src") != "hand":
                t["lyrics_by"] = entry["credit"]
                t["lyrics_by_src"] = "file"
            continue
        entry, how = find_lyrics(index, name)
        if not entry:
            if name:
                missing.append(name)
            continue
        keeps = t.get("lyrics_keep") or []
        drops = t.get("lyrics_drop") or []
        if keeps or drops:
            t["lyrics"] = lyrics_from_rows(entry["rows"], keeps, drops)
            t["lyrics_src"] = "picked"
        else:
            t["lyrics"] = entry["text"]
            t["lyrics_src"] = "file"
        if entry.get("credit") and t.get("lyrics_by_src") != "hand":
            t["lyrics_by"] = entry["credit"]
            t["lyrics_by_src"] = "file"
        found.append(t.get("title") or name)
    return found, missing


def find_lyrics(index, name, cutoff=0.86):
    """Look one song up in the index.  Returns (entry, how) or (None, '')."""
    if not index:
        return None, ""
    for key in lyric_title_keys(split_ext(name)[0].replace("_", " ")):
        if key in index:
            return index[key], "exact"
    # "Besk_glögg_(with_guitars).mp3" -> "besk glögg"
    keys = lyric_title_keys(split_ext(name)[0].replace("_", " "))
    for key in keys:
        close = difflib.get_close_matches(key, list(index), n=1, cutoff=cutoff)
        if close:
            return index[close[0]], "close name"
    return None, ""


# ---- a lyric file that is no longer where the box says -----------------------
def find_moved_file(path, roots=()):
    """Look for a file that has been moved, by its NAME.  '' = not found.

    Searched, in this order: the folder the path pointed at, its
    neighbours (Lyrics\\ turned into Text\\ is the typical case), then
    each of ROOTS with its Text / Lyrics / Texter sub-folders.
    """
    name = os.path.basename((path or "").strip().strip('"'))
    if not name:
        return ""
    spots = []
    here = os.path.dirname((path or "").strip().strip('"'))
    up = os.path.dirname(here)
    if here:
        spots.append(here)
    if up and os.path.isdir(up):
        spots.append(up)
        try:
            spots += [os.path.join(up, d) for d in sorted(os.listdir(up))
                      if os.path.isdir(os.path.join(up, d))]
        except OSError:
            pass
    for r in roots:
        r = (r or "").strip().strip('"')
        if not r:
            continue
        spots.append(r)
        for sub_ in ("Text", "Lyrics", "Texter", "Texts"):
            spots.append(os.path.join(r, sub_))
    seen = set()
    for d in spots:
        k = os.path.normcase(os.path.normpath(d))
        if k in seen:
            continue
        seen.add(k)
        f = os.path.join(d, name)
        if os.path.isfile(f):
            return f
    return ""


def heal_lyric_files_text(text, roots=()):
    """The 'Lyric file(s)' box text with every missing file pointed at the
    place it was moved to.  Returns (new_text, [(old, new), ...])."""
    out, changes = [], []
    for line in (text or "").splitlines():
        s = line.strip()
        if s and not s.startswith("#"):
            who, p = (s.split("|", 1) if "|" in s else ("", s))
            p = p.strip().strip('"')
            if p and not os.path.isfile(p):
                found = find_moved_file(p, roots)
                if found:
                    found = found.replace("\\", "/")
                    changes.append((p, found))
                    line = ("%s | %s" % (who.strip(), found)) if who.strip() \
                        else found
        out.append(line)
    return "\n".join(out), changes


# *****************************************************************************
# DEL 08c - CREDITS FILE  (who else helped with which song)
#
#   One plain text file, one credit per line:
#
#       Song title | Name, role
#       Bara på låtsas | Malin Östh, lyrics
#       Besk glögg | Mikael Swahn, gitarr; Tony R, inspiration
#
#   The title is matched like a lyric heading (case, the (brackets) at the
#   end and small typos do not matter).  The same song may have several
#   lines, and one line may hold several credits separated by ";".  Role
#   "lyrics" (or words / text / texter) becomes "Words: <name>" under the
#   title, every other role is printed as "<role>: <name>".  A credit
#   without a comma is printed as the bare name.
# *****************************************************************************
CREDITS_FILE_HEAD = """# MusicSite credits - ONE line per credit:
#
#     Song title | Name, role
#
# role "lyrics" gives "Words: <name>" under the title; any other role
# (gitarr, inspiration, ...) is printed as "role: name" on the page.
# Several credits on one line are separated by ";", and the same song may
# have several lines.  Lines starting with # are ignored.
#
#     Besk glögg | Mikael Swahn, gitarr; Tony R, inspiration
#
"""
LYRICS_ROLES = {"lyrics", "lyric", "words", "text", "texter", "låttext"}


def parse_credits(text):
    """-> ([(title, name, role)], [lines that could not be read])"""
    rows, bad = [], []
    for line in (text or "").splitlines():
        s = line.strip().lstrip("\ufeff")
        if not s or s.startswith("#"):
            continue
        if "|" not in s:
            bad.append(s)
            continue
        title, rest = s.split("|", 1)
        title = title.strip()
        got = False
        for part in rest.split(";"):
            part = part.strip()
            if not part:
                continue
            if "," in part:
                name, role = part.rsplit(",", 1)
            else:
                name, role = part, ""
            if name.strip() and title:
                rows.append((title, name.strip(), role.strip()))
                got = True
        if not got:
            bad.append(s)
    return rows, bad


def build_credits_index(path):
    """Read the credits file -> (index, report).  The index is shaped like
    the lyric index (key -> entry) so find_lyrics() can look songs up in it."""
    index, report = {}, []
    path = (path or "").strip().strip('"')
    if not path:
        return index, report
    if not os.path.isfile(path):
        return index, ["! There is no credits file %s" % path]
    try:
        rows, bad = parse_credits(read_text_any(path))
    except Exception as exc:
        return index, ["! Could not read the credits file (%s)" % exc]
    entries = {}
    for title, name, role in rows:
        keys = lyric_title_keys(title)
        if not keys:
            continue
        e = entries.get(keys[0])
        if e is None:
            e = {"title": title, "credits": [], "used": False}
            entries[keys[0]] = e
            for k in keys:
                index.setdefault(k, e)
        if {"name": name, "role": role} not in e["credits"]:
            e["credits"].append({"name": name, "role": role})
    report.append("Credits file: %d credit(s) for %d song(s)."
                  % (len(rows), len(entries)))
    for b in bad:
        report.append("! Credits line without 'Title | Name, role': " + b)
    return index, report


def credit_texts(track):
    """The credits that are NOT the words, as the page prints them."""
    out = []
    for c in track.get("credits") or []:
        role, name = c.get("role", ""), c.get("name", "")
        if not name or role.casefold() in LYRICS_ROLES:
            continue
        out.append("%s: %s" % (role, name) if role else name)
    return out


def credit_objs(track):
    """The credits that are NOT the words, as {role, name} for the page."""
    return [{"role": c.get("role", ""), "name": c.get("name", "")}
            for c in track.get("credits") or []
            if c.get("name") and c.get("role", "").casefold()
            not in LYRICS_ROLES]


def apply_credits(tracks, index):
    """Give every track the credits the file has for it.  The file is the
    master: a track it no longer mentions loses the credits it gave, but a
    "Lyrics by" typed by hand is never touched.  Returns how many tracks
    have credits now; the entries that found a song are marked 'used'."""
    n = 0
    for t in tracks:
        entry, _how = find_lyrics(index, t.get("audio_name")
                                  or t.get("title", "")) if index else (None, "")
        t["credits"] = list(entry["credits"]) if entry else []
        words = ", ".join(c["name"] for c in t["credits"]
                          if c.get("role", "").casefold() in LYRICS_ROLES)
        if entry:
            entry["used"] = True
            n += 1
        if t.get("lyrics_by_src") == "hand":
            continue
        if words:
            t["lyrics_by"], t["lyrics_by_src"] = words, "credits"
        elif t.get("lyrics_by_src") == "credits":
            t["lyrics_by"], t["lyrics_by_src"] = "", ""
    return n


def credits_unused(index):
    seen, out = set(), []
    for e in index.values():
        if id(e) not in seen:
            seen.add(id(e))
            if not e["used"]:
                out.append(e["title"])
    return out


# *****************************************************************************
# DEL 08d - MP3 TAGS  (title, band, words ... written INTO the local mp3 files)
#   WaveForge makes the mp3, MusicSite knows everything about the song.  This
#   puts what MusicSite knows into the file itself (ID3 tags), so it follows
#   the file to the phone, the car, the player and the cloud:
#
#       title                 TIT2   the Tracks tab (or the file name)
#       artist / band         TPE1 + TPE2   the track's artist, else the Site tab
#       album                 TALB   the track's group, else the site title
#       year                  TDRC   "Year", else the year in "Made"
#       words by              TEXT   "Lyrics by" / the credits file
#       composer              TCOM   a credit with the role music / composer
#       comment               COMM   the description + the other credits
#       the words             USLT   only what the page publishes (no chords,
#                                    no private notes), and only when "Show
#                                    lyrics" is on for the page
#       cover picture         APIC   optional, scaled down to 700 px
#
#   The audio is never touched - only the tag at the start of the file.  A
#   file whose tags are already right is NOT written at all (so its date and
#   size stay as they were and the upload check stays quiet).  Before a file
#   is changed for the FIRST time its untouched original is copied to
#   Backups\MP3_originals.  Fields with nothing to say are left as they are.
# *****************************************************************************
try:
    import mutagen
    from mutagen.id3 import (ID3, ID3NoHeaderError, TIT2, TPE1, TPE2, TALB,
                             TDRC, TEXT, TCOM, COMM, USLT, APIC)
    MUTAGEN_OK = True
except Exception:                      # not installed: the rest still works
    MUTAGEN_OK = False

TAG_LANG = "XXX"                       # ID3's "language unknown"
COMPOSER_ROLES = {"music", "musik", "composer", "composed", "kompositör",
                  "kompositor", "låtskrivare", "latskrivare"}
BAK_MP3_DIR = os.path.join(BAK_DIR, "MP3_originals")
TAG_COVER_PX = 700


def tag_year(track):
    for src in (track.get("year", ""), track.get("made", "")):
        m = re.search(r"(?<!\d)(1[89]\d\d|20\d\d)(?!\d)", str(src or ""))
        if m:
            return m.group(1)
    return ""


def tag_wanted(track, site, with_lyrics=True):
    """What the tags of this song should say -> {frame id: text}.
    A frame with nothing to say is simply absent (and left alone)."""
    w = {}
    title = (track.get("title") or "").strip()
    artist = (track.get("artist") or site.get("artist") or "").strip()
    album = (track.get("group") or site.get("site_title") or "").strip()
    if title:
        w["TIT2"] = title
    if artist:
        w["TPE1"] = artist
        w["TPE2"] = artist
    if album:
        w["TALB"] = album
    year = tag_year(track)
    if year:
        w["TDRC"] = year
    by = (track.get("lyrics_by") or "").strip()
    if by:
        w["TEXT"] = by
    comp = [c.get("name", "").strip() for c in track.get("credits") or []
            if c.get("role", "").strip().casefold() in COMPOSER_ROLES
            and c.get("name", "").strip()]
    if comp:
        w["TCOM"] = ", ".join(comp)
    note = [(track.get("description") or "").strip()]
    others = [x for x in credit_texts(track)
              if (x.split(":", 1)[0].strip().casefold() not in COMPOSER_ROLES)]
    if others:
        note.append("; ".join(others))
    note = "\n".join(x for x in note if x)
    if note:
        w["COMM"] = note
    words = (track.get("lyrics") or "").replace("\r\n", "\n").strip()
    if with_lyrics and words:
        w["USLT"] = words
    return w


def _tag_sig(fr):
    """Something comparable for one frame (for 'is it already right?')."""
    fid = fr.FrameID
    if fid in ("COMM", "USLT"):
        return str(fr.text).replace("\r\n", "\n").strip()
    if fid == "APIC":
        import hashlib
        return hashlib.md5(fr.data).hexdigest()
    return " / ".join(str(x) for x in fr.text)


def _tag_drop(tags, fid):
    """Remove OUR frame of this kind, but not somebody else's: a COMM or USLT
    with a description of its own (iTunes' normalisation etc.) stays."""
    for key in list(tags.keys()):
        fr = tags[key]
        if fr.FrameID != fid:
            continue
        if fid in ("COMM", "USLT") and getattr(fr, "desc", ""):
            continue
        if fid == "APIC" and getattr(fr, "type", 3) != 3:
            continue
        del tags[key]


def _tag_have(tags, fid):
    out = []
    for key in tags.keys():
        fr = tags[key]
        if fr.FrameID != fid:
            continue
        if fid in ("COMM", "USLT") and getattr(fr, "desc", ""):
            continue
        if fid == "APIC" and getattr(fr, "type", 3) != 3:
            continue
        out.append(_tag_sig(fr))
    return out


_COVER_CACHE = {}


def tag_cover_key(name):
    """Only letters and digits count, so 'En_expatrierad_själslig' finds the
    cover 'En_expatrierad,_själslig' (and 'Ensam_på_en_planet' finds
    'Ensam_(på_en_planet)').  '' for an empty name."""
    s = unicodedata.normalize("NFC", split_ext(name or "")[0]).casefold()
    return "".join(ch for ch in s if ch.isalnum())


def tag_cover_bytes(path):
    """-> (jpeg/png bytes, mime) or (None, why).  Scaled down so 93 songs do
    not grow by 93 big pictures."""
    if path in _COVER_CACHE:
        return _COVER_CACHE[path]
    out = (None, "unreadable")
    try:
        try:
            from PIL import Image
            im = Image.open(path)
            im = im.convert("RGB")
            im.thumbnail((TAG_COVER_PX, TAG_COVER_PX))
            buf = io.BytesIO()
            im.save(buf, "JPEG", quality=85)
            out = (buf.getvalue(), "image/jpeg")
        except ImportError:
            ext = split_ext(path)[1]
            with open(path, "rb") as f:
                data = f.read()
            if ext in (".jpg", ".jpeg") and len(data) < 600000:
                out = (data, "image/jpeg")
            elif ext == ".png" and len(data) < 600000:
                out = (data, "image/png")
            else:
                out = (None, "too big and Pillow is not installed")
    except Exception as exc:
        out = (None, str(exc))
    _COVER_CACHE[path] = out
    return out


def tag_one_file(path, wanted, cover=None, write=True, backup_dir=""):
    """Bring ONE mp3 up to date.  -> (status, note)

    status: 'same' (nothing to do), 'written', 'would' (check only), 'error'.
    """
    try:
        try:
            tags = ID3(path)
        except ID3NoHeaderError:
            tags = ID3()
        diff = []
        for fid, text in wanted.items():
            if text and _tag_sig_text(text) not in _tag_have(tags, fid):
                diff.append(fid)
        if cover is not None:
            import hashlib
            if hashlib.md5(cover[0]).hexdigest() not in _tag_have(tags, "APIC"):
                diff.append("APIC")
        if not diff:
            return "same", ""
        names = ", ".join(diff)
        if not write:
            return "would", "would write " + names
        if backup_dir:
            os.makedirs(backup_dir, exist_ok=True)
            dst = os.path.join(backup_dir, os.path.basename(path))
            if not os.path.exists(dst):            # the FIRST original only
                shutil.copy2(path, dst)
        for fid in diff:
            _tag_drop(tags, fid)
            if fid == "APIC":
                tags.add(APIC(encoding=1, mime=cover[1], type=3, desc="",
                              data=cover[0]))
                continue
            text = wanted[fid]
            if fid == "COMM":
                tags.add(COMM(encoding=1, lang=TAG_LANG, desc="", text=[text]))
            elif fid == "USLT":
                tags.add(USLT(encoding=1, lang=TAG_LANG, desc="", text=text))
            else:
                cls = {"TIT2": TIT2, "TPE1": TPE1, "TPE2": TPE2, "TALB": TALB,
                       "TDRC": TDRC, "TEXT": TEXT, "TCOM": TCOM}[fid]
                tags.add(cls(encoding=1, text=[text]))
        tags.save(path, v2_version=3)        # v2.3: Explorer and phones read it
        return "written", "wrote " + names
    except PermissionError:
        return "error", "cannot write - the file is open in another program?"
    except Exception as exc:
        return "error", "%s: %s" % (type(exc).__name__, exc)


def _tag_sig_text(text):
    return str(text).replace("\r\n", "\n").strip()


class TagResult:
    def __init__(self):
        self.items = []              # (name, status, note)
        self.report = []
        self.error = ""
        self.cancelled = False

    def counts(self):
        c = {}
        for _n, st, _note in self.items:
            c[st] = c.get(st, 0) + 1
        return c


def tag_local_mp3s(cfg, tracks, site, write=True, with_cover=False,
                   keep_original=True, say=None, cancel=None,
                   only_files=None):
    """Tag every mp3 in the 'Local folder(s)' box (the permanent library AND
    any other folder listed there - a fresh export lands where you were
    working).  The song data comes from the project's tracks; a song that is
    not in the project yet (a brand-new export) gets its data straight from
    the lyric files and the credits file, so new songs are tagged too."""
    res = TagResult()
    say = say or (lambda m: None)
    cancel = cancel or (lambda: False)
    rep = res.report.append
    if not MUTAGEN_OK:
        res.error = ("The 'mutagen' package is not installed.\n\n"
                     "Install it once with:   pip install mutagen")
        return res
    bases = []
    for line in (cfg.get("local_folders") or "").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "|" in line:
            line = line.split("|", 1)[1]
        line = line.strip().strip('"')
        if line and line not in bases:
            bases.append(line)
    # only_files = exactly these mp3 files (just converted ones), wherever
    # they landed; their library folder is the parent of the MP3 folder
    explicit = {}
    if only_files:
        bases = []
        for p in only_files:
            d = os.path.dirname(p)
            base = os.path.dirname(d) if os.path.basename(d).casefold() == \
                ((cfg.get("audio_folder") or "MP3").strip() or "MP3"
                 ).casefold() else d
            if base not in bases:
                bases.append(base)
            explicit.setdefault(base, {})[os.path.basename(p).casefold()] = \
                {"name": os.path.basename(p), "path": p}
    if not bases:
        res.error = ("No local folder.\n\nPut the folder your mp3 files live "
                     "in - the one with MP3 / Cover / Text inside it - in the "
                     "'Local folder(s)' box first.")
        return res

    folder = (cfg.get("audio_folder") or "MP3").strip() or "MP3"
    cover_folder = (cfg.get("cover_folder") or "").strip()
    with_lyrics = bool(site.get("show_lyrics", True))

    lyr_pairs = parse_lyrics_files(cfg.get("lyrics_files", ""))
    lyr_index, lyr_report, _n = build_lyrics_index(lyr_pairs, say)
    for line in lyr_report:
        if line.startswith("!"):
            rep(line)
    cidx, creport = build_credits_index(cfg.get("credits_file", ""))
    for line in creport:
        if line.startswith("!"):
            rep(line)

    by_name = {}
    for t in tracks:
        for nm in (t.get("audio_name"), ):
            if nm:
                by_name[nm.casefold()] = t

    for base in bases:
        if cancel():
            res.cancelled = True
            return res
        rep("")
        if not os.path.isdir(base):
            rep("! There is no folder %s - skipped." % base)
            continue
        if only_files:
            files, where, note = explicit.get(base, {}), base, ""
        else:
            files, where, note = local_files(base, folder, (".mp3",))
        rep("=== %s ===" % where)
        flat = bool(note)
        if flat:
            rep("(no '%s' sub-folder, so only the songs the project knows "
                "are touched)" % folder)
        covers = {}
        if with_cover and cover_folder:
            cfiles, _w, _n = local_files(base, cover_folder, IMAGE_EXT)
            for f in cfiles.values():
                covers.setdefault(split_ext(f["name"])[0].casefold(), f)
                covers.setdefault(norm_key(f["name"], False), f)
                covers.setdefault(tag_cover_key(f["name"]), f)
        label = re.sub(r"[^A-Za-z0-9]+", "_", base).strip("_")[-50:]
        bdir = os.path.join(BAK_MP3_DIR, label) if keep_original else ""
        n = 0
        nocov = []
        for key in sorted(files):
            if cancel():
                res.cancelled = True
                return res
            f = files[key]
            name = f["name"]
            tr = by_name.get(name.casefold())
            if tr is None and flat:
                continue
            if tr is not None and tr.get("hidden"):
                res.items.append((name, "skipped", "hidden on the page"))
                continue
            if tr is None:
                tr = Track.new(norm_key(name), pretty_title(name))
                tr["audio_name"] = name
                fill_lyrics([tr], lyr_index)
                if cidx:
                    apply_credits([tr], cidx)
            wanted = tag_wanted(tr, site, with_lyrics)
            cover = None
            if with_cover and covers:
                cf = None
                for k in (split_ext(tr.get("cover_name") or "")[0].casefold(),
                          split_ext(name)[0].casefold(),
                          norm_key(name, False),
                          tag_cover_key(tr.get("cover_name") or ""),
                          tag_cover_key(name),
                          tag_cover_key(re.sub(r"\s*[\(\[][^()\[\]]*[\)\]]\s*$",
                                               "", split_ext(name)[0]))):
                    if k and k in covers:
                        cf = covers[k]
                        break
                if cf:
                    data, mime = tag_cover_bytes(cf["path"])
                    if data:
                        cover = (data, mime)
                    else:
                        rep("%s: cover not used (%s)" % (name, mime))
            if with_cover and cover is None:
                nocov.append(name)
            st, why = tag_one_file(f["path"], wanted, cover, write, bdir)
            res.items.append((name, st, why))
            n += 1
            if n % 10 == 0:
                say("Tagging ... %d" % n)
        if with_cover:
            if not cover_folder:
                rep("! No cover picture was put in: the cover folder name on "
                    "the Source tab is empty.")
            elif nocov:
                rep("! No cover picture found in %s for %d song(s) - they "
                    "got no picture: %s%s"
                    % (os.path.join(base, cover_folder), len(nocov),
                       ", ".join(nocov[:8]), " ..." if len(nocov) > 8 else ""))
    c = res.counts()
    rep("")
    rep("%d file(s): %d %s, %d already right, %d skipped, %d failed."
        % (len(res.items), c.get("written", 0) + c.get("would", 0),
           "to change" if not write else "changed", c.get("same", 0),
           c.get("skipped", 0), c.get("error", 0)))
    for name, st, why in res.items:
        if st in ("written", "would", "error"):
            rep("  %s  %s%s" % ({"written": "WROTE", "would": "WOULD",
                                 "error": "FAILED"}[st], name,
                                "  - " + why if why else ""))
    return res


# *****************************************************************************
# DEL 08e - WAV -> MP3  (so WaveForge is not needed for this part)
#   ffmpeg does the work, with the same settings WaveForge offers for mp3:
#   CBR / VBR / ABR, bitrate, sample rate, mono/stereo, loudness.  The last
#   settings used are remembered (settings.json, key "wav2mp3").
#   The mp3 is written under a temporary name and swapped in when it is
#   finished, so a stopped or failed conversion never leaves half a file or
#   destroys the mp3 that was already there.
# *****************************************************************************
WAV_EXT = (".wav", ".wave", ".flac", ".aif", ".aiff")
WAV2MP3_DEFAULT = {
    "mode": "CBR",             # CBR | VBR | ABR
    "bitrate": "192",          # kbps, CBR and ABR
    "vbr_q": "4",              # 0 (best) ... 9 (smallest), VBR
    "sample_rate": "0",        # 0 = as the original
    "channels": "0",           # 0 = as the original, 1 = mono, 2 = stereo
    "normalize": False,        # loudnorm, same as WaveForge
    "existing": "newer",       # skip | overwrite | newer (only if wav is newer)
    "tag_after": True,         # write the tags into the new mp3s at once
    "out_dir": "",             # empty = the MP3 folder of the first local folder
    "last_wav_dir": "",
    "recurse": True,
    "hide_have": True,
    "ffmpeg": "",              # picked by hand when it cannot be found
}


def find_ffmpeg(hint=""):
    """ffmpeg.exe: the hand-picked one, Helpfiles\\1---Movie, then PATH."""
    cands = []
    if hint:
        cands.append(hint)
    for name in ("ffmpeg.exe", "ffmpeg"):
        cands.append(os.path.join(HELP_ROOT, "1---Movie", name))
    for c in cands:
        if c and os.path.isfile(c):
            return c
    return shutil.which("ffmpeg") or ""


def mp3_command(ffmpeg, src, dst, opt):
    """The ffmpeg command for ONE file (dst is written as an mp3 whatever
    its name ends in)."""
    cmd = [ffmpeg, "-y", "-hide_banner", "-loglevel", "error", "-i", src,
           "-vn", "-codec:a", "libmp3lame"]
    mode = opt.get("mode", "CBR")
    if mode == "VBR":
        cmd += ["-q:a", str(opt.get("vbr_q", "4"))]
    else:
        cmd += ["-b:a", str(opt.get("bitrate", "192")) + "k"]
    if mode == "ABR":
        cmd += ["-abr", "1"]
    sr = str(opt.get("sample_rate", "0")).split()[0]
    ch = str(opt.get("channels", "0")).split()[0]
    if opt.get("normalize"):
        # WaveForge asks for I=-3, which ffmpeg refuses ("Result too large":
        # the range is -70 ... -5).  -14 LUFS is the usual level for music.
        cmd += ["-af", "loudnorm=I=-14:TP=-1.5:LRA=11"]
        if sr in ("", "0"):
            sr = "44100"            # loudnorm would otherwise resample to 192k
    if sr and sr != "0":
        cmd += ["-ar", sr]
    if ch and ch != "0":
        cmd += ["-ac", ch]
    cmd += ["-id3v2_version", "3", "-f", "mp3", dst]
    return cmd


def wav_status(src, out_dir):
    """-> (status, dst): 'new' (no mp3 yet), 'newer' (the wav is newer than
    the mp3 there) or 'have' (an mp3 is there and it is at least as new)."""
    dst = os.path.join(out_dir, split_ext(os.path.basename(src))[0] + ".mp3")
    if not os.path.isfile(dst):
        return "new", dst
    try:
        if os.path.getmtime(src) > os.path.getmtime(dst) + 2:
            return "newer", dst
    except OSError:
        pass
    return "have", dst


def convert_to_mp3(ffmpeg, src, dst, opt):
    """Convert one file.  -> (ok, note)"""
    tmp = dst + ".part"
    try:
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        kw = {}
        if sys.platform == "win32":
            kw["creationflags"] = subprocess.CREATE_NO_WINDOW
        r = subprocess.run(mp3_command(ffmpeg, src, tmp, opt),
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           **kw)
        if r.returncode != 0 or not os.path.isfile(tmp):
            err = r.stderr.decode("utf-8", "replace").strip().splitlines()
            raise RuntimeError(" | ".join(err[-3:]) or "ffmpeg failed")
        os.replace(tmp, dst)
        return True, ""
    except Exception as exc:
        try:
            if os.path.exists(tmp):
                os.remove(tmp)
        except OSError:
            pass
        return False, str(exc)


def find_wavs(paths, recurse=True):
    """Files and folders -> the audio files in them (sorted, no doubles)."""
    out, seen = [], set()
    for p in paths:
        if os.path.isdir(p):
            if recurse:
                walker = os.walk(p)
            else:
                walker = [(p, [], sorted(os.listdir(p)))]
            for root, dirs, names in walker:
                dirs.sort()
                for n in sorted(names):
                    full = os.path.join(root, n)
                    if split_ext(n)[1] in WAV_EXT and os.path.isfile(full) \
                            and full.casefold() not in seen:
                        seen.add(full.casefold())
                        out.append(full)
        elif os.path.isfile(p) and split_ext(p)[1] in WAV_EXT \
                and p.casefold() not in seen:
            seen.add(p.casefold())
            out.append(p)
    return out


# *****************************************************************************
# DEL 09 - SCANNER  (source -> matched tracks), runs in a worker thread
# *****************************************************************************
class ScanResult:
    def __init__(self):
        self.cover_files = []          # every file in the Cover folder(s)
        self.tracks = []
        self.report = []
        self.error = ""


def _scan_group(cfg, group, old_by_key, res, say, multi, lyr_index=None):
    """Read ONE group folder (its MP3 / Cover / Text) and match it up.

    Returns (tracks, keys_seen).  The group name keeps the keys apart, so two
    groups may each hold a song with the same file name without colliding.
    """
    rep = res.report.append

    src = make_source(cfg["type"], group["address"], cfg.get("api_key", ""),
                      cfg.get("audio_style", ""), cfg.get("image_style", ""))

    gname = group.get("name", "").strip()
    if not gname and multi:
        try:
            gname = src.folder_title() or ""
        except Exception:
            gname = ""
        if not gname:
            gname = "Group %d" % (group.get("index", 0) + 1)
    group["resolved_name"] = gname

    rep("")
    rep("=== %s ===" % (gname or "All tracks"))
    rep("Source: " + src.describe())
    say("Reading %s ..." % (gname or "main folder"))

    drop_no = bool(cfg.get("drop_track_numbers", True))
    cutoff = float(cfg.get("fuzzy_cutoff", 0.84))

    drops = {}          # per folder: was numbering detected in THIS folder?

    def grab(folder_name, exts, label):
        if not folder_name.strip():
            rep("%s folder: (not used)" % label)
            drops[label] = False
            return {}
        say("Reading %s ..." % folder_name)
        try:
            items = src.list_folder(folder_name)
        except SourceError:
            raise
        except Exception as exc:
            raise SourceError("Could not read '%s':\n%s" % (folder_name, exc))
        if items is None:
            rep("%s folder '%s': NOT FOUND in the main folder."
                % (label, folder_name))
            drops[label] = False
            return {}
        if not items:
            rep("%s folder '%s': found, but it is EMPTY - nothing in it yet."
                % (label, folder_name))
            drops[label] = False
            return {}

        usable = [f for f in items if split_ext(f.name)[1] in exts]
        # decided per folder, and only if the option is on at all
        folder_drop = drop_no and looks_like_track_numbering(
            [f.name for f in usable])
        drops[label] = folder_drop
        if drop_no:
            rep("%s folder '%s': leading numbers %s"
                % (label, folder_name,
                   "look like track numbers - they will be ignored"
                   if folder_drop else
                   "are part of the titles - they will be KEPT"))

        keep = {}
        skipped = 0
        for f in items:
            _, ext = split_ext(f.name)
            if ext not in exts:
                skipped += 1
                continue
            k = norm_key(f.name, folder_drop)
            if k in keep:
                # Google Drive does NOT replace a file when you drop a new
                # one with the same name on it - it puts a SECOND file there
                # with the same name.  Taking "the first" would then quietly
                # publish last week's version, so the newer one wins and it
                # is said out loud, with what to do about it.
                old, new = keep[k], f
                if (new.mtime or 0) > (old.mtime or 0):
                    keep[k] = new
                    older = old
                else:
                    older = new
                rep("  ! '%s' is up there TWICE (%s and %s) - using the "
                    "newer one.  Delete the older copy in the cloud."
                    % (f.name,
                       human_when(keep[k].mtime, keep[k].exact) or "no date",
                       human_when(older.mtime, older.exact) or "no date"))
                continue
            keep[k] = f
        rep("%s folder '%s': %d usable file(s)%s"
            % (label, folder_name, len(keep),
               ", %d ignored (wrong file type)" % skipped if skipped else ""))
        if not keep and skipped:
            rep("  ! every file in '%s' had an unexpected extension - "
                "expected one of: %s"
                % (folder_name, " ".join(exts)))
        return keep

    audio = grab(cfg.get("audio_folder", "MP3"), AUDIO_EXT, "Audio")
    covers = grab(cfg.get("cover_folder", "Cover"), IMAGE_EXT, "Cover")
    for cf in covers.values():           # "Set cover..." picks from these
        res.cover_files.append({"name": cf.name, "group": gname,
                                "url": src.image_url(cf)})
    texts = grab(cfg.get("text_folder", "Text"), TEXT_EXT, "Text")

    if not audio:
        rep("No audio files in this group.")
        return [], set()

    audio_drop = drops.get("Audio", False)

    # Initial order: a real track number wins ("01 - Song.mp3"), but only when
    # this folder was actually recognised as numbered - otherwise alphabetical.
    def first_order(item):
        key, f = item
        if not audio_drop:
            return (1, 0, key)
        base, _ = split_ext(f.name)
        _, n = strip_tracknumber(base)
        return (0, n, key) if n is not None else (1, 0, key)

    used_covers, used_texts = set(), set()
    lyr_found, lyr_missing = [], []
    tracks, keys_seen = [], set()
    fresh_titles = {}                 # what each file's own name would give
    order = 0
    for key, af in sorted(audio.items(), key=first_order):
        gkey = ("%s/%s" % (gname, key)) if (multi and gname) else key
        keys_seen.add(gkey)
        tr = Track.new(gkey, pretty_title(af.name, audio_drop))
        fresh_titles[gkey] = tr["title"]
        tr["group"] = gname
        old = old_by_key.get(gkey)
        if old:                                   # keep everything you typed
            for fld in ("title", "artist", "year", "description", "hidden",
                        "lyrics_src", "lyrics_keep", "lyrics_drop",
                        "lyrics_by", "lyrics_by_src",
                        "made", "about_person", "released", "alt"):
                tr[fld] = old.get(fld, tr[fld])
            if old.get("lyrics") and not cfg.get("_relyrics"):
                tr["lyrics"] = old["lyrics"]
            tr["order"] = old.get("order", order)
        else:
            # a brand new file lands at the end of an existing hand-made order
            tr["order"] = (100000 + order) if old_by_key else order
        order += 1

        tr["audio_name"] = af.name
        tr["audio_url"] = src.audio_url(af)

        notes = []
        # cover
        free_covers = {k: v for k, v in covers.items() if k not in used_covers}
        hit = None if (old and old.get("cover_hand")) \
            else best_match(key, free_covers, cutoff)
        if old and old.get("cover_hand"):
            # chosen by hand: Fetch never replaces it (not even "no cover")
            tr["cover_url"] = old.get("cover_url", "")
            tr["cover_name"] = old.get("cover_name", "")
            tr["cover_hand"] = True
            # a cover picked from the cloud is found again BY NAME, so a
            # file uploaded anew (new id) keeps working
            fresh = next((cf for cf in covers.values()
                          if cf.name == tr["cover_name"]), None)
            if fresh is not None:
                tr["cover_url"] = src.image_url(fresh)
            notes.append("cover set by hand" if tr["cover_url"]
                         else "no cover (by hand)")
        elif hit:
            ck, how = hit
            used_covers.add(ck)
            tr["cover_name"] = covers[ck].name
            tr["cover_url"] = src.image_url(covers[ck])
            if how != "exact":
                notes.append("cover matched by %s (%s)" % (how, covers[ck].name))
        else:
            notes.append("no cover")

        # lyrics / text
        free_texts = {k: v for k, v in texts.items() if k not in used_texts}
        hit = best_match(key, free_texts, cutoff)
        if hit:
            tk_, how = hit
            used_texts.add(tk_)
            tr["text_name"] = texts[tk_].name
            if not tr["lyrics"]:
                say("Reading text for %s ..." % tr["title"])
                tr["lyrics"] = fetch_text_file(src, texts[tk_]).strip()
            if how != "exact":
                notes.append("text matched by %s (%s)" % (how, texts[tk_].name))

        # words out of his own lyric files.  They are the master copy, so
        # they are read again every time - unless he has edited the words
        # here by hand, and then his hand wins and keeps winning.
        if lyr_index:
            # lines he moved across by hand in "Choose lines" are applied
            # again on top of the rules, so a Fetch never undoes them
            got, gone = fill_lyrics([tr], lyr_index)
            lyr_found.extend(got)
            lyr_missing.extend(gone)

        tr["match_note"] = "; ".join(notes)
        tracks.append(tr)

    # A second version of a song - "Clowner_(a_cappella)" beside "Clowner" -
    # nearly always wants the same picture.  The cover was taken by whichever
    # of them came first, so without this the other one stands there bare.
    # Only a tail in brackets or after a dash is ignored, so two songs that
    # merely start alike never steal each other's cover.
    with_cover = {}
    for tr in tracks:
        if tr.get("cover_url"):
            for k in lyric_title_keys(split_ext(tr["audio_name"])[0]):
                with_cover.setdefault(k, tr)
    shared = 0
    for tr in tracks:
        if tr.get("cover_url") or not tr.get("audio_name") \
                or tr.get("cover_hand"):
            continue
        for k in lyric_title_keys(split_ext(tr["audio_name"])[0])[1:]:
            other = with_cover.get(k)
            if not other:
                continue
            tr["cover_url"] = other["cover_url"]
            tr["cover_name"] = other["cover_name"]
            tr["match_note"] = "; ".join(
                x for x in (tr.get("match_note", "").replace("no cover", ""),
                            "cover shared with %s" % other["title"]) if x
            ).strip("; ")
            shared += 1
            break
    if shared:
        rep("%d version(s) of a song borrowed the cover of the original."
            % shared)

    # A title that two tracks share, where one of them is NOT that file's own
    # name, is a copy (the old "saved into the wrong row" bug): the file's
    # own name goes back, and it is said out loud.
    def _flat(s):
        return re.sub(r"\W+", "", (s or "").casefold())
    by_title = {}
    for t in tracks:
        by_title.setdefault(_flat(t["title"]), []).append(t)
    for flat, same in by_title.items():
        if len(same) < 2:
            continue
        own = [t for t in same if _flat(fresh_titles.get(t["key"])) == flat]
        if not own:
            continue
        for t in same:
            if t in own:
                continue
            fresh = fresh_titles.get(t["key"], "")
            if fresh:
                rep("Title of %s was a copy of another track's (%s) - set "
                    "back to '%s'." % (t["audio_name"], t["title"], fresh))
                t["title"] = fresh

    leftover_c = [covers[k].name for k in covers if k not in used_covers]
    leftover_t = [texts[k].name for k in texts if k not in used_texts]
    if leftover_c:
        rep("Covers with no song: " + ", ".join(sorted(leftover_c)))
    if leftover_t:
        rep("Texts with no song: " + ", ".join(sorted(leftover_t)))
    if lyr_index:
        rep("Words from your lyric files: %d of %d song(s)."
            % (len(lyr_found), len(lyr_found) + len(lyr_missing)))
        if lyr_missing:
            rep("  no words found for: " + ", ".join(sorted(lyr_missing)))

    rep("Matched %d track(s), %d with a cover, %d with lyrics."
        % (len(tracks),
           sum(1 for t in tracks if t["cover_url"]),
           sum(1 for t in tracks if t["lyrics"])))
    return tracks, keys_seen


def scan_source(cfg, existing_tracks=None, progress=None):
    """Read every group folder in turn and build one combined track list."""
    res = ScanResult()
    say = progress or (lambda m: None)
    rep = res.report.append

    groups = parse_groups(cfg.get("folders", ""), cfg.get("address", ""))
    if not groups:
        res.error = ("No folder address was given.\n\n"
                     "Put the share link of the main folder in the "
                     "'Main folder(s)' box on the Source tab.")
        return res
    for i, g in enumerate(groups):
        g["index"] = i

    multi = len(groups) > 1
    old_by_key = {t["key"]: t for t in (existing_tracks or []) if t.get("key")}

    lyr_index = {}
    lyr_paths = parse_lyrics_files(cfg.get("lyrics_files", ""))
    if lyr_paths:
        lyr_index, lyr_report, n = build_lyrics_index(lyr_paths, say)
        for line in lyr_report:
            rep(line)
        rep("Lyric files: %d song(s) to look words up in." % n)

    all_keys, failures = set(), []
    for g in groups:
        try:
            tracks, keys = _scan_group(cfg, g, old_by_key, res, say, multi,
                                       lyr_index)
        except SourceError as exc:
            # one bad group must never throw away the good ones
            label = g.get("name") or g.get("address", "")[:60]
            rep("FAILED: " + str(exc).splitlines()[0])
            failures.append("%s\n%s" % (label, exc))
            continue
        res.tracks.extend(tracks)
        all_keys |= keys

    if not res.tracks:
        res.error = ("No audio files were found.\n\n"
                     + ("\n\n".join(failures) if failures else
                        "Check that each main folder really contains a "
                        "sub-folder named '%s' with audio files inside."
                        % cfg.get("audio_folder", "MP3")))
        return res

    if parse_backups(cfg.get("backups", "")) or any(t.get("alt") for t in res.tracks):
        rep("")
        scan_backups(cfg, groups, res.tracks, rep, say)

    cidx, creport = build_credits_index(cfg.get("credits_file", ""))
    if cidx or creport:
        for line in creport:
            rep(line)
        apply_credits(res.tracks, cidx)
        left = credits_unused(cidx)
        if left:
            rep("Credits for songs that are not on the page: "
                + ", ".join(sorted(left)))

    if failures:
        rep("")
        rep("!! %d group(s) could not be read - see above. "
            "The rest of the tracks are here." % len(failures))

    gone = [t for t in (existing_tracks or [])
            if t.get("key") and t["key"] not in all_keys]
    if gone:
        rep("Gone from the source (removed from the list): "
            + ", ".join(t.get("title", "?") for t in gone))

    # groups keep the order you listed them in; inside a group your own
    # hand-made order survives
    gorder = {g.get("resolved_name", ""): i for i, g in enumerate(groups)}
    res.tracks.sort(key=lambda t: (gorder.get(t.get("group", ""), 0),
                                   t.get("order", 0)))
    for i, t in enumerate(res.tracks):
        t["order"] = i
    if multi:
        rep("")
        rep("TOTAL: %d track(s) in %d group(s)."
            % (len(res.tracks), len(groups) - len(failures)))
    return res


# *****************************************************************************
# DEL 09b - UPLOAD CHECK  (which of MY files are newer than the ones online)
#
#   The master files live on this disk; the cloud folder is supposed to be a
#   copy of them.  The only question that matters is "what have I changed
#   since I last uploaded", and the program had no idea the local folders
#   even existed until now.
#
#   How each file is judged, in this order:
#       1. no file of that name online .................. NEW
#       2. both sizes known and different ............... CHANGED
#       3. both sizes known and equal ................... up to date
#       4. only dates known, mine is newer .............. NEWER  (exact date)
#                                                    or   CHECK  (day only)
#       5. the source says neither size nor date ........ CHECK
#
#   Size beats date on purpose: a file that was only re-saved, moved or
#   touched keeps its size, and nagging about those would make the whole
#   list useless.  Two different exports of the same song practically never
#   land on the same byte count.
#
#   Google Drive hands out both numbers WITHOUT an API key - the folder
#   listing gives the day, and a HEAD of the download link gives the exact
#   size and time (head_info).  That is what "Deep check" is.
#
#   MusicSite cannot upload to Drive: writing needs a signed-in Google
#   account (OAuth), not a public link.  So it does the next best thing and
#   copies everything that has to go up into a Temp_to_drive folder, in the
#   same MP3 / Cover / Text shape as the cloud folder, ready to drag over in
#   one go.
# *****************************************************************************
SYNC_KINDS = (("Audio", "audio_folder", "MP3", AUDIO_EXT),
              ("Cover", "cover_folder", "Cover", IMAGE_EXT),
              ("Text", "text_folder", "Text", TEXT_EXT))

STATUS_NEW = "new"
STATUS_CHANGED = "changed"
STATUS_NEWER = "newer"
STATUS_STAGED = "staged"
STATUS_ASSUMED = "assumed"
STATUS_CHECK = "check"
STATUS_SAME = "same"
STATUS_ONLINE = "online"

STATUS_TEXT = {
    STATUS_NEW:     "NEW - not online",
    STATUS_CHANGED: "CHANGED - other size",
    STATUS_NEWER:   "NEWER here",
    STATUS_STAGED:  "WAITING in Temp_to_drive",
    STATUS_ASSUMED: "you say it is uploaded",
    STATUS_CHECK:   "CHECK - cannot tell",
    STATUS_SAME:    "up to date",
    STATUS_ONLINE:  "only online",
}
STATUS_ORDER = {STATUS_NEW: 0, STATUS_CHANGED: 1, STATUS_NEWER: 2,
                STATUS_STAGED: 3, STATUS_ASSUMED: 4, STATUS_CHECK: 5,
                STATUS_SAME: 6, STATUS_ONLINE: 7}
# what gets ticked by itself.  A file that is already lying in Temp_to_drive
# is NOT among them: copying it there a second time is work for nothing.
UPLOAD_STATUSES = (STATUS_NEW, STATUS_CHANGED, STATUS_NEWER)

STAGE_README = "_UPLOAD THESE.txt"
CLOUD_MEMORY_FILE = os.path.join(HELP_DIR, "cloud_memory.json")


class CloudMemory:
    """What the cloud has already told us about each file, kept on disk.

    The listing of a folder is cheap - one request - and it is what finds new
    and removed files, so it is ALWAYS read fresh.  The expensive part is the
    exact size and time, one question per file: 71 songs plus 478 covers is
    550 questions, and that is the "evighet".

    The trick is that the free listing already hands out something that
    changes whenever the file up there changes: its id, and the day it was
    last touched.  That pair is the token.  Same token = same file = the
    numbers we asked for last time are still true, and nothing has to be
    asked again.  A file that has been re-uploaded gets a new id or a new
    day, so it is asked about again by itself.

    On top of that: every file copied to Temp_to_drive is marked as "on its
    way up".  Those are never taken from memory - they are the ones most
    likely to have changed - and when the cloud finally agrees with the file
    you staged, the mark clears itself and the row says so.
    """

    VERSION = 1

    def __init__(self, path=None):
        # not a default ARGUMENT: that would freeze the path at import time
        # and a test could no longer keep its hands off the live file
        self.path = path or CLOUD_MEMORY_FILE
        self.data = {"app": APP_NAME, "version": self.VERSION, "sources": {}}
        self.lock = threading.Lock()
        self.dirty = False
        self.load()

    # -- disk ---------------------------------------------------------------
    def load(self):
        try:
            with open(self.path, "r", encoding="utf-8") as f:
                got = json.load(f)
            if got.get("version") == self.VERSION and \
                    isinstance(got.get("sources"), dict):
                self.data = got
        except FileNotFoundError:
            pass
        except Exception as exc:
            log_exception("CloudMemory.load", exc)

    def save(self):
        if not self.dirty:
            return
        try:
            tmp = self.path + ".tmp"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump(self.data, f, ensure_ascii=False)
            os.replace(tmp, self.path)
            self.dirty = False
        except Exception as exc:
            log_exception("CloudMemory.save", exc)

    # -- one file -----------------------------------------------------------
    @staticmethod
    def token(rf):
        """What the LISTING says - changes as soon as the file up there does."""
        return "%s|%d|%d" % (rf.ident or rf.name, int(rf.mtime or 0),
                             int(rf.size or 0))

    def _folder(self, skey, folder, make=False):
        src = self.data.setdefault("sources", {})
        if make:
            return src.setdefault(skey, {}).setdefault(folder, {})
        return src.get(skey, {}).get(folder, {})

    def get(self, skey, folder, name):
        return self._folder(skey, folder).get(name)

    def recall(self, skey, folder, rf, max_age=7 * 86400):
        """Fill rf from memory when the listing says it is the same file.

        Returns "hit", "stale", "pending" or "miss" - the last three all mean
        "ask the cloud about this one".
        """
        got = self.get(skey, folder, rf.name)
        if not got:
            return "miss"
        if got.get("pending"):
            return "pending"
        if got.get("tok") != self.token(rf):
            return "stale"
        # a source that tells us nothing in its listing (a plain web folder)
        # gives the same token forever, so those entries also grow old
        if not (rf.ident or rf.mtime or rf.size):
            if time.time() - float(got.get("asked", 0)) > max_age:
                return "stale"
        if got.get("size"):
            rf.size = int(got["size"])
        if got.get("mtime"):
            rf.mtime = float(got["mtime"])
            rf.exact = bool(got.get("exact", True))
        return "hit"

    def remember(self, skey, folder, rf, tok=None):
        # The token MUST be the one from the listing, taken before the probe
        # overwrote size and mtime with the real values - otherwise nothing
        # ever matches again and the memory is worthless.
        with self.lock:
            entry = self._folder(skey, folder, True).setdefault(rf.name, {})
            entry.update({"tok": tok or self.token(rf),
                          "size": int(rf.size or 0),
                          "mtime": float(rf.mtime or 0),
                          "exact": bool(rf.exact), "asked": time.time()})
            self.dirty = True

    # -- what is on its way up ---------------------------------------------
    def mark_staged(self, skey, folder, name, size, mtime):
        with self.lock:
            entry = self._folder(skey, folder, True).setdefault(name, {})
            entry["pending"] = {"size": int(size), "mtime": float(mtime),
                                "when": time.time()}
            self.dirty = True

    def pending(self, skey, folder, name):
        got = self.get(skey, folder, name)
        return (got or {}).get("pending")

    def clear_pending(self, skey, folder, name):
        with self.lock:
            got = self.get(skey, folder, name)
            if got and got.pop("pending", None) is not None:
                self.dirty = True

    # -- what HE says is up there ------------------------------------------
    def mark_claimed(self, skey, folder, name, size, mtime):
        """He says this file is already uploaded.  Believe him, but remember
        exactly which file he said it about, and let a clean comparison be
        the judge."""
        with self.lock:
            entry = self._folder(skey, folder, True).setdefault(name, {})
            entry["claimed"] = {"size": int(size), "mtime": float(mtime),
                                "when": time.time()}
            self.dirty = True

    def claimed(self, skey, folder, name):
        got = self.get(skey, folder, name)
        return (got or {}).get("claimed")

    def clear_claimed(self, skey, folder, name):
        with self.lock:
            got = self.get(skey, folder, name)
            if got and got.pop("claimed", None) is not None:
                self.dirty = True
                return True
        return False

    # -- housekeeping -------------------------------------------------------
    def forget(self, skeys):
        """A clean comparison: throw away what we think we know."""
        with self.lock:
            n = 0
            for skey in skeys:
                folders = self.data.get("sources", {}).pop(skey, {})
                n += sum(len(v) for v in folders.values())
            self.dirty = True
        self.save()
        return n

    def stats(self):
        files = pending = claimed = 0
        newest = 0.0
        for folders in self.data.get("sources", {}).values():
            for entries in folders.values():
                for e in entries.values():
                    files += 1
                    if e.get("pending"):
                        pending += 1
                    if e.get("claimed"):
                        claimed += 1
                    newest = max(newest, float(e.get("asked", 0)))
        return {"files": files, "pending": pending, "claimed": claimed,
                "asked": newest}


def human_size(n):
    n = float(n or 0)
    if n < 1024:
        return "%d B" % int(n)
    for unit in ("KB", "MB", "GB"):
        n /= 1024.0
        if n < 1024 or unit == "GB":
            return "%.1f %s" % (n, unit)
    return "%.1f GB" % n


def human_when(ts, exact=True):
    if not ts:
        return ""
    try:
        d = datetime.fromtimestamp(ts)
    except (OSError, OverflowError, ValueError):
        return ""
    return d.strftime("%Y-%m-%d %H:%M") if exact \
        else d.strftime("%Y-%m-%d") + " (day)"


class SyncResult:
    def __init__(self):
        self.items = []
        self.report = []
        self.error = ""
        self.cancelled = False
        self.asked = 0             # questions the cloud had to answer
        self.cached = 0            # answers that came from memory
        self.keys = []             # the source keys this run touched

    def counts(self):
        c = {}
        for it in self.items:
            c[it["status"]] = c.get(it["status"], 0) + 1
        return c


def parse_local_map(text, groups):
    """Pair the local folders with the cloud groups.

    A group may have SEVERAL folders, and that is the point: new exports
    tend to land in whatever folder you were working in, not in the tidy
    library folder.  List both and they are searched as one.

    A named line ("Songs 2026 | D:\\Musik\\2026") goes to the group of that
    name and may be repeated.  Plain lines fill whatever groups have nothing
    yet, top to bottom; when there is only ONE group - the normal case -
    every plain line belongs to it.

    Returns (pairs, problems) where pairs is [(group, [path, ...]), ...].
    """
    lines = []
    for line in (text or "").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "|" in line:
            nm, path = line.split("|", 1)
            lines.append((nm.strip(), path.strip().strip('"')))
        else:
            lines.append(("", line.strip('"')))

    problems = []
    folders = {}                               # index of group -> [paths]

    def add(group, path):
        folders.setdefault(group.get("index", 0), []).append(path)

    for nm, path in lines:                     # named lines first
        if not nm or not path:
            continue
        hit = None
        for g in groups:
            gname = (g.get("name") or g.get("resolved_name") or "")
            if gname.casefold() == nm.casefold():
                hit = g
                break
        if hit is None:
            problems.append("No group is called '%s' - that line was skipped."
                            % nm)
            continue
        add(hit, path)
    for nm, path in lines:                     # then the plain ones, in order
        if nm or not path:
            continue
        empty = [g for g in groups if not folders.get(g.get("index", 0))]
        if empty:
            add(empty[0], path)
        elif len(groups) == 1:
            add(groups[0], path)               # all of them belong to it
        else:
            problems.append("Which group is '%s' for?  Write it as "
                            "\"Name | %s\"." % (path, path))

    pairs = [(g, folders[g.get("index", 0)]) for g in groups
             if folders.get(g.get("index", 0))]
    return pairs, problems


def local_files(base, sub, exts):
    """The files of ONE kind in a local library folder.

    The sub-folder (MP3 / Cover / Text) is used when it exists - the local
    library is normally shaped exactly like the cloud one.  When it does not
    exist, the files are taken straight out of the main folder and sorted by
    extension instead, because a folder on your own disk is not always as
    tidy as the one you uploaded.

    Returns (files, where, note); files is {name.casefold(): {...}}.
    """
    where, note = "", ""
    d = os.path.join(base, sub)
    if not os.path.isdir(d):
        d = ""
        try:
            for entry in os.listdir(base):
                if entry.casefold() == sub.casefold() and \
                        os.path.isdir(os.path.join(base, entry)):
                    d = os.path.join(base, entry)
                    break
        except OSError as exc:
            return {}, "", "Could not read %s (%s)" % (base, exc)
    if not d:
        d = base
        note = ("no '%s' sub-folder here - looking straight in the folder "
                "instead" % sub)
    where = d

    out = {}
    try:
        entries = sorted(os.listdir(d))
    except OSError as exc:
        return {}, where, "Could not read %s (%s)" % (d, exc)
    for entry in entries:
        full = os.path.join(d, entry)
        if not os.path.isfile(full):
            continue
        if split_ext(entry)[1] not in exts:
            continue
        try:
            st = os.stat(full)
        except OSError:
            continue
        out[entry.casefold()] = {"name": entry, "path": full,
                                 "size": st.st_size, "mtime": st.st_mtime,
                                 "flat": bool(note)}
    return out, where, note


def local_files_multi(bases, sub, exts):
    """The files of one kind across ALL of a group's local folders.

    When the same name sits in two of them the NEWEST wins - that is the one
    you just made - and it is said out loud, because quietly picking a file
    is how you end up uploading last week's version.
    """
    out, notes = {}, []
    many = len(bases) > 1
    for base in bases:
        got, where, note = local_files(base, sub, exts)
        if note:
            notes.append(note)
        for key, f in got.items():
            f["from"] = where
            old = out.get(key)
            if old is None:
                out[key] = f
                continue
            keep = f if f["mtime"] > old["mtime"] else old
            out[key] = keep
            if many:
                notes.append("%s is in two folders - using the newer one, "
                             "from %s" % (keep["name"], keep["from"]))
    return out, notes


def classify_file(local, rf, tol_sec):
    """One local file against its counterpart online -> (status, note)."""
    if rf is None:
        return STATUS_NEW, ""
    if local["size"] and rf.size:
        if local["size"] != rf.size:
            # "online 1.1 MB, here 1.1 MB" is worse than saying nothing, so
            # when the two round to the same thing the bytes are spelled out
            there, here = human_size(rf.size), human_size(local["size"])
            if there == here:
                there, here = "%d B" % rf.size, "%d B" % local["size"]
            diff = local["size"] - rf.size
            return STATUS_CHANGED, ("online %s, here %s  (%s %s)"
                                    % (there, here, human_size(abs(diff)),
                                       "bigger" if diff > 0 else "smaller"))
        # Saying just "up to date" about a file you know you touched
        # yesterday is exactly what makes people distrust the whole list.
        if rf.mtime and local["mtime"] > rf.mtime + tol_sec:
            return STATUS_SAME, ("same size - yours is newer, but byte for "
                                 "byte it is the same file")
        return STATUS_SAME, "same size"
    if rf.mtime:
        if rf.exact:
            if local["mtime"] > rf.mtime + tol_sec:
                return STATUS_NEWER, ""
            return STATUS_SAME, ""
        # A day-only date (Google Drive's listing) still settles it when the
        # two are on different days: after the last second of that day, mine
        # IS newer.  On the same day nobody can tell, and saying "up to date"
        # then would be a guess dressed up as an answer.
        day = human_when(rf.mtime, False).split(" ")[0]
        if local["mtime"] > rf.mtime + tol_sec:
            return STATUS_NEWER, "online it says only '%s'" % day
        if local["mtime"] >= rf.mtime - 86399 - tol_sec:
            return STATUS_CHECK, ("both are from %s - turn on Deep check to "
                                  "be sure" % day)
        return STATUS_SAME, ""
    return STATUS_CHECK, "this source gives neither size nor date"


def compare_library(cfg, kinds=("Audio", "Cover", "Text"), deep=True,
                    tol_min=5, say=None, cancel=None, memory=None,
                    fresh=False):
    """Walk every group: local library folders vs the cloud folder.

    'memory' is a CloudMemory: the exact size and time of a file is asked for
    once and remembered until the listing says the file up there changed.
    'fresh' ignores all of it and asks about everything again - the button
    called "Clean comparison".
    """
    res = SyncResult()
    say = say or (lambda m: None)
    cancel = cancel or (lambda: False)
    rep = res.report.append
    tol_sec = max(0.0, float(tol_min or 0)) * 60.0
    stage_dest = (cfg.get("stage_dir") or "").strip() or STAGE_DIR_DEFAULT
    staged_waiting = []
    claim_kept, claim_wrong, claim_broken = [], [], []

    groups = parse_groups(cfg.get("folders", ""), cfg.get("address", ""))
    if not groups:
        res.error = ("No cloud folder to compare with.\n\n"
                     "Fill in 'Main folder(s)' on the Source tab first.")
        return res
    for i, g in enumerate(groups):
        g["index"] = i

    pairs, problems = parse_local_map(cfg.get("local_folders", ""), groups)
    for p in problems:
        rep("! " + p)
    if not pairs:
        res.error = ("No local folder to compare.\n\n"
                     "Put the folder your master files live in - the one with "
                     "MP3 / Cover / Text inside it - in the 'Local folder(s)' "
                     "box.")
        return res

    multi = len(groups) > 1
    for group, bases in pairs:
        if cancel():
            res.cancelled = True
            return res
        gname = group.get("name", "").strip()
        rep("")
        rep("=== %s ===" % (gname or "Main folder"))
        for gone in [b for b in bases if not os.path.isdir(b)]:
            rep("! There is no folder %s - skipped." % gone)
        bases = [b for b in bases if os.path.isdir(b)]
        if not bases:
            continue
        for b in bases:
            rep("Here:   " + b)
        try:
            src = make_source(cfg["type"], group["address"],
                              cfg.get("api_key", ""),
                              cfg.get("audio_style", ""),
                              cfg.get("image_style", ""))
        except SourceError as exc:
            rep("! " + str(exc).splitlines()[0])
            continue
        rep("Online: " + src.describe())
        skey = src.key() if hasattr(src, "key") else src.describe()
        if skey not in res.keys:
            res.keys.append(skey)
        if not gname and multi:
            try:
                gname = src.folder_title() or ""
            except Exception:
                gname = ""
            if not gname:
                gname = "Group %d" % (group.get("index", 0) + 1)
        group["resolved_name"] = gname

        songs = set()          # stems of the songs in this group, for below
        for label, cfgkey, default, exts in SYNC_KINDS:
            if cancel():
                res.cancelled = True
                return res
            if label not in kinds:
                continue
            folder = (cfg.get(cfgkey, default) or "").strip()
            if not folder:
                continue

            mine, notes = local_files_multi(bases, folder, exts)
            for note in notes:
                rep("%s: %s" % (label, note))
            if not mine:
                rep("%s: no files of that kind in %s"
                    % (label, " or ".join(bases)))

            say("Reading %s online ..." % folder)
            try:
                items = src.list_folder(folder)
            except SourceError as exc:
                rep("! Could not read '%s' online: %s"
                    % (folder, str(exc).splitlines()[0]))
                continue
            except Exception as exc:
                rep("! Could not read '%s' online: %s" % (folder, exc))
                continue
            if items is None:
                rep("%s: there is no '%s' folder online yet - everything here "
                    "counts as new." % (label, folder))
                items = []
            # Drive does not replace a file of the same name, it adds a
            # second one.  Compare against the NEWER of the two, and say
            # that the old one is still sitting up there.
            theirs, twice = {}, {}
            for f in items:
                if f.is_dir or split_ext(f.name)[1] not in exts:
                    continue
                key = f.name.casefold()
                other = theirs.get(key)
                if other is None:
                    theirs[key] = f
                    continue
                twice[key] = twice.get(key, 1) + 1
                if (f.mtime or 0) > (other.mtime or 0):
                    theirs[key] = f
            if twice:
                rep("%s: %d name(s) are up there more than once - the newest "
                    "copy is used.  Delete the old ones in the cloud: %s"
                    % (label, len(twice),
                       ", ".join(sorted(theirs[k].name for k in twice))[:150]))

            # Exact numbers, one request per file - but only for the files
            # that have a counterpart to compare with, and only for those we
            # do not already remember.  This is what turns half a minute of
            # waiting into two seconds.
            todo, remembered = [], 0
            for nm, rf in theirs.items():
                if nm not in mine:
                    continue
                if rf.size and rf.exact:
                    continue                   # the listing already said it
                how = "miss"
                if memory is not None and not fresh:
                    how = memory.recall(skey, folder, rf)
                if how == "hit":
                    remembered += 1
                else:
                    todo.append((rf, CloudMemory.token(rf)))
            res.cached += remembered
            if deep and todo and hasattr(src, "probe"):
                say("Asking the cloud about %d %s file(s) ..."
                    % (len(todo), label.lower()))
                done = [0]
                lock = threading.Lock()

                def ask(pair, _src=src, _n=len(todo)):
                    rf, tok = pair
                    if cancel():
                        return
                    try:
                        size, ts, ok = _src.probe(rf)
                    except Exception:
                        return
                    if not ok:
                        return
                    if size:
                        rf.size = size
                    if ts:
                        rf.mtime, rf.exact = ts, True
                    if memory is not None:
                        memory.remember(skey, folder, rf, tok)
                    with lock:
                        done[0] += 1
                        if done[0] % 10 == 0 or done[0] == _n:
                            say("... %d / %d" % (done[0], _n))

                try:
                    with ThreadPoolExecutor(max_workers=8) as ex:
                        list(ex.map(ask, todo))
                    res.asked += done[0]
                    rep("%s: %d answer(s) straight from memory, asked the "
                        "cloud about %d - %d answered."
                        % (label, remembered, len(todo), done[0]))
                except Exception as exc:
                    rep("! The deep check failed: %s" % exc)
            elif remembered:
                rep("%s: %d answer(s) straight from memory, nothing to ask."
                    % (label, remembered))
            if cancel():
                res.cancelled = True
                return res

            # a file with the same name but another extension online is worth
            # saying out loud: uploading would leave TWO covers for one song
            twins = {}
            for nm, rf in theirs.items():
                twins.setdefault(split_ext(rf.name)[0].casefold(),
                                 []).append(rf.name)

            if label == "Audio":
                songs = {split_ext(x)[0].casefold() for x in mine}
                songs |= {split_ext(x)[0].casefold() for x in theirs}
            loose = 0

            for nm in sorted(mine):
                lf = mine[nm]
                # A folder searched flat is somebody's working folder, not a
                # Cover folder: the root of a disk holds holiday photos and
                # stray notes, and offering to upload those as covers is how
                # a music page ends up with a picture of a car in it.  Only
                # files named after a song count there.
                if label != "Audio" and lf.get("flat") and songs and \
                        split_ext(lf["name"])[0].casefold() not in songs:
                    loose += 1
                    continue
                rf = theirs.get(nm)
                status, note2 = classify_file(lf, rf, tol_sec)
                if status == STATUS_NEW:
                    others = [x for x in twins.get(
                        split_ext(lf["name"])[0].casefold(), [])
                        if x.casefold() != nm]
                    if others:
                        note2 = ("online there is already %s - uploading this "
                                 "adds a SECOND file" % ", ".join(others))
                if len(bases) > 1 and lf.get("from"):
                    note2 = (note2 + "  " if note2 else "") + \
                        "[from %s]" % lf["from"]
                # something that was copied to Temp_to_drive: has it landed?
                pend = memory.pending(skey, folder, lf["name"]) \
                    if memory is not None else None
                landed = bool(pend and rf is not None and rf.size and
                              int(pend.get("size", 0)) == rf.size)
                if landed:
                    memory.clear_pending(skey, folder, lf["name"])
                    note2 = (note2 + "  " if note2 else "") + \
                        "(uploaded since last time)"
                item = {
                    "group": gname, "kind": label, "folder": folder,
                    "skey": skey,
                    "name": lf["name"], "path": lf["path"],
                    "lsize": lf["size"], "lmtime": lf["mtime"],
                    "rsize": rf.size if rf else 0,
                    "rmtime": rf.mtime if rf else 0.0,
                    "rexact": bool(rf.exact) if rf else False,
                    "status": status, "note": note2,
                    "include": status in UPLOAD_STATUSES,
                }
                # It still has to go up - but it is already lying in
                # Temp_to_drive from last time, so there is nothing to copy.
                if nm in twice:
                    item["note"] = (item["note"] + "  " if item["note"]
                                    else "") + \
                        "%d copies of this name are online - delete the " \
                        "old one" % twice[nm]
                # "I have already uploaded that one" - a half-tick he sets by
                # hand.  It is a claim, not a fact, so it is believed only
                # while the file here is unchanged, and a clean comparison
                # (which really asks the cloud) is what exposes a slip.
                claim = memory.claimed(skey, folder, lf["name"]) \
                    if memory is not None else None
                if claim and status not in UPLOAD_STATUSES:
                    # the cloud agrees with him now - the mark has done its
                    # job and is cleared away by itself
                    memory.clear_claimed(skey, folder, lf["name"])
                    claim = None
                if claim and status in UPLOAD_STATUSES:
                    same = (int(claim.get("size", -1)) == lf["size"] and
                            abs(float(claim.get("mtime", 0))
                                - lf["mtime"]) < 2)
                    if not same:
                        memory.clear_claimed(skey, folder, lf["name"])
                        item["note"] = (item["note"] + "  " if item["note"]
                                        else "") + \
                            "you marked this as uploaded, but the file here " \
                            "has changed since - back in the list"
                        claim_broken.append(lf["name"])
                    elif fresh or rf is None:
                        # the cloud was really asked (or the name is not up
                        # there at all): the claim does not hold
                        memory.clear_claimed(skey, folder, lf["name"])
                        item["note"] = (item["note"] + "  " if item["note"]
                                        else "") + \
                            "YOU MARKED THIS AS UPLOADED - it is not up there"
                        claim_wrong.append(lf["name"])
                    else:
                        item["status"] = STATUS_ASSUMED
                        item["include"] = False
                        item["note"] = ("you marked it as uploaded %s - not "
                                        "checked again%s"
                                        % (human_when(claim.get("when", 0)),
                                           "  " + item["note"]
                                           if item["note"] else ""))
                        claim_kept.append(lf["name"])

                when = human_when(pend.get("when", 0)) if pend else ""
                if item["status"] in UPLOAD_STATUSES and \
                        staged_copy(item, stage_dest, multi):
                    item["status"] = STATUS_STAGED
                    item["include"] = False
                    item["note"] = ("waiting in Temp_to_drive%s - upload it, "
                                    "then Compare again"
                                    % (" since " + when if when else "")
                                    ) + ("  " + item["note"]
                                         if nm in twice else "")
                    staged_waiting.append(lf["name"])
                elif pend and not landed:
                    # it was staged once, it is not in Temp_to_drive any more,
                    # and the cloud still shows the old file
                    item["note"] = (item["note"] + "  " if item["note"]
                                    else "") + \
                        "copied to Temp_to_drive %s - not up there yet" % when
                res.items.append(item)
            for nm in sorted(theirs):
                if nm in mine:
                    continue
                rf = theirs[nm]
                res.items.append({
                    "group": gname, "kind": label, "folder": folder,
                    "skey": skey,
                    "name": rf.name, "path": "",
                    "lsize": 0, "lmtime": 0.0,
                    "rsize": rf.size, "rmtime": rf.mtime,
                    "rexact": bool(rf.exact),
                    "status": STATUS_ONLINE,
                    "note": "not in your local folder",
                    "include": False,
                })
            if loose:
                rep("%s: %d loose file(s) ignored - they are not named after "
                    "any song." % (label, loose))
            rep("%s: %d here, %d online."
                % (label, len(mine) - loose, len(theirs)))

    res.items.sort(key=lambda it: (it["group"],
                                   STATUS_ORDER.get(it["status"], 9),
                                   it["kind"], it["name"].casefold()))
    c = res.counts()
    rep("")
    rep("To upload: %d new, %d changed, %d newer here.  %d waiting in "
        "Temp_to_drive, %d marked by you, %d to check, %d up to date, "
        "%d only online."
        % (c.get(STATUS_NEW, 0), c.get(STATUS_CHANGED, 0),
           c.get(STATUS_NEWER, 0), c.get(STATUS_STAGED, 0),
           c.get(STATUS_ASSUMED, 0), c.get(STATUS_CHECK, 0),
           c.get(STATUS_SAME, 0), c.get(STATUS_ONLINE, 0)))
    if claim_wrong:
        rep("!! You marked %d file(s) as uploaded, but they are NOT up "
            "there: %s" % (len(claim_wrong), ", ".join(sorted(claim_wrong))))
        rep("   They are back in the list, ticked, and the mark is gone.")
    if claim_broken:
        rep("! %d file(s) you had marked as uploaded have changed here "
            "since: %s" % (len(claim_broken), ", ".join(sorted(claim_broken))))
    if claim_kept:
        rep("%d file(s) are only marked as uploaded BY YOU and were not "
            "checked: %s" % (len(claim_kept), ", ".join(sorted(claim_kept))))
        rep("   Press 'Clean comparison' when you want that checked for real.")
    if staged_waiting:
        rep("%d file(s) are already lying in Temp_to_drive from last time "
            "and are NOT copied again: %s"
            % (len(staged_waiting), ", ".join(sorted(staged_waiting)[:6])
               + (" ..." if len(staged_waiting) > 6 else "")))
    quiet = c.get(STATUS_SAME, 0) + c.get(STATUS_ONLINE, 0)
    if quiet > 50:
        rep("Tip: tick 'hide what is already up to date' to get the %d "
            "uninteresting rows out of the way." % quiet)
    if memory is not None:
        rep("The cloud answered %d question(s); %d came from memory."
            % (res.asked, res.cached))
        memory.save()
    return res


def staged_copy(item, dest, multi):
    """Is this exact file already lying in Temp_to_drive, waiting?

    Same name, same byte count, same time (copy2 keeps the time) - then it
    is the very file that was put there last time and there is no reason to
    copy it again.  Change the file at home and it stops matching, so a new
    version is staged as it should be.
    """
    if not dest or not item.get("path"):
        return False
    path = os.path.join(stage_folder_for(item, dest, multi), item["name"])
    try:
        st = os.stat(path)
    except OSError:
        return False
    return (st.st_size == item.get("lsize") and
            abs(st.st_mtime - item.get("lmtime", 0)) < 2)


def safe_folder_name(name):
    """A group name you can actually make a folder of, still readable."""
    out = re.sub(r'[<>:"/\\|?*]+', "-", name or "").strip(" .")
    return out or "group"


def stage_folder_for(item, dest, multi):
    """Where one file goes inside Temp_to_drive."""
    d = dest
    if multi and item.get("group"):
        d = os.path.join(d, safe_folder_name(item["group"]))
    return os.path.join(d, item.get("folder") or "MP3")


def stage_uploads(items, dest, multi=False, clear=True, say=None,
                  memory=None, keep=None):
    """Copy the marked files into Temp_to_drive, shaped like the cloud folder.

    'clear' only ever empties the sub-folders that are about to be written
    (Temp_to_drive/[group/]MP3 and friends) - never the whole tree, and never
    anything else that happens to be lying there.  'keep' is the set of
    (sub-folder, name) that STILL has to go up: those are left alone even
    when clearing, so a file that has been waiting since yesterday is never
    thrown away just because something else is being staged today.
    """
    say = say or (lambda m: None)
    items = [it for it in items if it.get("path")]
    if not items:
        return {"count": 0, "bytes": 0, "dest": dest, "removed": 0,
                "already": 0}

    targets = sorted({stage_folder_for(it, dest, multi) for it in items})
    keep = keep or set()
    removed = 0
    if clear:
        for d in targets:
            if not os.path.isdir(d):
                continue
            sub = os.path.basename(d)
            for entry in os.listdir(d):
                full = os.path.join(d, entry)
                if not os.path.isfile(full):
                    continue
                if (sub, entry) in keep:
                    continue                   # still waiting to go up
                try:
                    os.remove(full)
                    removed += 1
                except OSError as exc:
                    say("Could not remove %s (%s)" % (entry, exc))
    for d in targets:
        os.makedirs(d, exist_ok=True)

    count, total, lines, already = 0, 0, [], 0
    for it in items:
        d = stage_folder_for(it, dest, multi)
        dst = os.path.join(d, it["name"])
        if staged_copy(it, dest, multi):       # the same file is already here
            already += 1
            lines.append("%-6s %-8s %s  (was already here)"
                         % (it.get("group", "") or "-", it.get("folder", ""),
                            it["name"]))
            continue
        say("Copying %s ..." % it["name"])
        shutil.copy2(it["path"], dst)          # copy2 keeps the date
        # remember that this one is on its way up: it must never be answered
        # from memory again, and the next comparison can tell you whether it
        # actually landed
        if memory is not None and it.get("skey"):
            memory.mark_staged(it["skey"], it.get("folder", ""), it["name"],
                               it.get("lsize", 0), it.get("lmtime", 0))
        count += 1
        total += it.get("lsize", 0)
        lines.append("%-6s %-8s %s  (%s)"
                     % (it.get("group", "") or "-", it.get("folder", ""),
                        it["name"], human_size(it.get("lsize", 0))))

    try:
        with open(os.path.join(dest, STAGE_README), "w",
                  encoding="utf-8") as f:
            f.write(stage_readme_text(dest, count, total, lines, multi))
    except Exception as exc:
        log_exception("stage readme", exc)
    if memory is not None:
        memory.save()
    log("Staged %d file(s) in %s" % (count, dest))
    return {"count": count, "bytes": total, "dest": dest,
            "removed": removed, "already": already}


def stage_readme_text(dest, count, total, lines, multi):
    return (
        "%s - files waiting to be uploaded\n"
        "%s\n\n"
        "Made %s by %s %s.\n"
        "%d file(s), %s in total.\n\n"
        "WHAT TO DO\n"
        "----------\n"
        "1. Open your cloud folder in the browser.\n"
        "2. Open this folder in Explorer.\n"
        "3. Drag the CONTENTS of each sub-folder here into the sub-folder of\n"
        "   the same name up there - the MP3 folder into MP3, the Cover\n"
        "   folder into Cover, and so on.%s\n"
        "4. When the cloud asks whether to replace a file that is already\n"
        "   there, say yes - that is exactly the point of the changed ones.\n"
        "5. Come back to MusicSite, press 'Compare with the cloud' again and\n"
        "   everything should say 'up to date'.  Then Fetch and Build.\n\n"
        "This folder is emptied and refilled every time you press\n"
        "'Copy to Temp_to_drive', so nothing has to be cleaned up by hand.\n\n"
        "WHAT IS IN HERE\n"
        "---------------\n%s\n"
        % (STAGE_README.replace(".txt", "").replace("_", ""),
           "=" * 60,
           datetime.now().strftime("%Y-%m-%d %H:%M"), APP_NAME, APP_VERSION,
           count, human_size(total),
           ("\n   Each group has its own folder here - upload each one into\n"
            "   the matching cloud folder." if multi else ""),
           "\n".join(lines)))


# *****************************************************************************
# DEL 10 - HTML TEMPLATE
#   One self-contained file: inline CSS, inline JS, track data as JSON.
#   Deliberately calm - no flashing, no bouncing, no auto-animations.
# *****************************************************************************
PAGE_TEMPLATE = r"""<!doctype html>
<html lang="en" data-theme="@@THEME@@">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@@TITLE@@</title>
<meta name="description" content="@@META@@">
<meta property="og:title" content="@@TITLE@@">
<meta property="og:description" content="@@META@@">
<meta property="og:type" content="music.album">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='@@ACCENT_ENC@@'/%3E%3Cpath d='M13 8v11.2a3.2 3.2 0 1 0 2 2.97V12h6V8z' fill='%23fff'/%3E%3C/svg%3E">
<style>
:root{
  --accent:@@ACCENT@@;
  --bg:#ffffff; --bg2:#f5f5f8; --card:#ffffff; --fg:#17171c;
  --dim:#5f5f6b; --line:#e3e3ea; --shadow:0 1px 3px rgba(0,0,0,.10);
}
html[data-theme="dark"]{
  --bg:#0f0f13; --bg2:#17171e; --card:#1a1a22; --fg:#ececf2;
  --dim:#9c9caa; --line:#2b2b36; --shadow:0 1px 3px rgba(0,0,0,.45);
}
@media (prefers-color-scheme: dark){
  html[data-theme="auto"]{
    --bg:#0f0f13; --bg2:#17171e; --card:#1a1a22; --fg:#ececf2;
    --dim:#9c9caa; --line:#2b2b36; --shadow:0 1px 3px rgba(0,0,0,.45);
  }
}
*{box-sizing:border-box}
html,body{margin:0;padding:0}
body{
  background:var(--bg); color:var(--fg);
  font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,
       "Helvetica Neue",Arial,sans-serif;
  padding-bottom:104px;
  -webkit-font-smoothing:antialiased;
}
a{color:var(--accent)}
.wrap{max-width:920px;margin:0 auto;padding:0 18px}

header.site{padding:44px 0 20px}
header.site h1{margin:0;font-size:clamp(28px,5vw,44px);line-height:1.1;
  letter-spacing:-.02em}
header.site .artist{margin:6px 0 0;font-size:17px;color:var(--dim)}
header.site .tagline{margin:10px 0 0;font-size:15px;color:var(--dim);
  font-style:italic}
header.site .about{margin:18px 0 0;max-width:62ch;color:var(--fg);
  white-space:pre-wrap}
.rule{height:1px;background:var(--line);margin:26px 0 18px}

/* ---- the little menu (Music / Discography / About) ---- */
.topnav{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 24px}
.topnav a{padding:7px 14px;border-radius:999px;border:1px solid var(--line);
  background:var(--bg2);color:var(--fg);text-decoration:none;font-size:14px;
  font-weight:600}
.topnav a:hover{border-color:var(--accent)}
.topnav a.on{background:var(--accent);border-color:var(--accent);color:#fff}

/* ---- release numbers (#3 #9): a click opens the discography there ---- */
.rels{display:inline-flex;gap:4px;flex-wrap:wrap;align-items:center}
.rel{padding:2px 8px;border-radius:999px;border:1px solid var(--accent);
  color:var(--accent);font-size:12.5px;font-weight:700;text-decoration:none;
  font-variant-numeric:tabular-nums;line-height:1.5}
.rel:hover{background:var(--accent);color:#fff}
.track .rels-d{flex:0 0 auto;max-width:150px;justify-content:flex-end;
  margin-right:2px}
.track .rels-m{display:none;margin-top:5px}
@media (max-width:640px){
  .track .rels-d{display:none}
  .track .rels-m{display:inline-flex}
}

.toolbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;
  margin-bottom:14px}
.toolbar input[type=search]{
  flex:1 1 200px;min-width:160px;padding:9px 12px;border-radius:9px;
  border:1px solid var(--line);background:var(--bg2);color:var(--fg);
  font-size:14px;outline:none}
.toolbar input[type=search]:focus{border-color:var(--accent)}
.btn{
  border:1px solid var(--line);background:var(--bg2);color:var(--fg);
  padding:9px 14px;border-radius:9px;cursor:pointer;font-size:14px}
.btn:hover{border-color:var(--accent)}
.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff}
.count{color:var(--dim);font-size:13px;margin-left:auto}

.tracks{list-style:none;margin:0;padding:0}
.ghead{
  margin:26px 0 10px;padding-bottom:6px;border-bottom:2px solid var(--accent);
  font-size:19px;font-weight:700;letter-spacing:-.01em;scroll-margin-top:12px}
.ghead:first-child{margin-top:4px}
.ghead .gcount{
  font-size:13px;font-weight:400;color:var(--dim);margin-left:8px}
.chips{display:flex;gap:7px;flex-wrap:wrap;margin:0 0 14px}
.chip{
  border:1px solid var(--line);background:var(--bg2);color:var(--dim);
  padding:6px 12px;border-radius:999px;cursor:pointer;font-size:13px}
.chip:hover{border-color:var(--accent)}
.chip.on{background:var(--accent);border-color:var(--accent);color:#fff}
.srcbar{align-items:center}.srcl,.srch{color:var(--dim);font-size:13px}
.track{
  display:flex;gap:14px;align-items:center;padding:10px;border-radius:12px;
  background:var(--card);border:1px solid var(--line);margin-bottom:8px;
  box-shadow:var(--shadow)}
.track.playing{border-color:var(--accent)}
.track .num{width:26px;text-align:right;color:var(--dim);
  font-variant-numeric:tabular-nums;font-size:13px;flex:0 0 auto}
.track .cover{
  width:60px;height:60px;flex:0 0 auto;border-radius:8px;object-fit:cover;
  background:var(--bg2);border:1px solid var(--line);cursor:zoom-in;
  display:block}
.track .meta{flex:1 1 auto;min-width:0}
.track .t{font-weight:600;cursor:pointer;overflow-wrap:break-word}
.track .s{font-size:13px;color:var(--dim);overflow-wrap:break-word}
.track .acts{display:flex;gap:6px;flex:0 0 auto;align-items:center}
.iconbtn{
  width:38px;height:38px;border-radius:50%;border:1px solid var(--line);
  background:var(--bg2);color:var(--fg);cursor:pointer;font-size:15px;
  line-height:1;display:flex;align-items:center;justify-content:center;
  padding:0}
.iconbtn:hover{border-color:var(--accent)}
.iconbtn.play{background:var(--accent);border-color:var(--accent);color:#fff}
.lyr{
  margin:0 0 10px 0;padding:14px 18px;border-radius:12px;background:var(--bg2);
  border:1px solid var(--line);white-space:pre-wrap;font-size:14.5px;
  overflow-wrap:anywhere}
.lyr[hidden]{display:none}
.cred{
  margin:0 0 10px 0;padding:12px 18px;border-radius:12px;
  background:var(--bg2);border:1px solid var(--line);font-size:14.5px}
.cred[hidden]{display:none}
.cred .crow{display:flex;gap:12px;padding:2px 0}
.cred .crole{flex:0 0 130px;color:var(--dim)}
.cred .crole::first-letter{text-transform:uppercase}
.cred .cname{min-width:0;overflow-wrap:anywhere}
.iconbtn.qm{font-weight:700;font-size:17px}

/* ---- the "?" popup: when, about whom, earlier releases ---- */
#ib{
  position:fixed;left:0;top:0;right:0;bottom:0;z-index:100;
  background:rgba(0,0,0,.6);display:flex;align-items:center;
  justify-content:center;padding:20px}
#ib[hidden]{display:none}
#ib .card{
  position:relative;width:min(460px,100%);max-height:86vh;overflow:auto;
  background:var(--card);color:var(--fg);border:1px solid var(--line);
  border-radius:14px;padding:20px 24px 18px;
  box-shadow:0 8px 40px rgba(0,0,0,.5)}
#ib h3{margin:0 34px 12px 0;font-size:17px;overflow-wrap:anywhere}
#ib .irow{padding:6px 0;overflow-wrap:anywhere}
#ib .ilab{color:var(--dim);font-size:12px;text-transform:uppercase;
  letter-spacing:.05em;margin-bottom:2px}
#ib ul{margin:0;padding-left:18px}
#ib li{padding:1px 0}
#ib .ix{position:absolute;top:10px;right:12px;width:32px;height:32px;
  border-radius:50%;border:1px solid var(--line);background:var(--bg2);
  color:var(--fg);font-size:20px;line-height:1;cursor:pointer;padding:0}

section.appbox{margin:0 0 20px;padding:18px 22px;border-radius:14px;
  background:var(--card);border:1px solid var(--line);display:flex;gap:16px;
  align-items:flex-start}
section.appbox .appicon{font-size:34px;line-height:1}
section.appbox .appbody{min-width:0;flex:1}
section.appbox h2{margin:0 0 8px;font-size:18px;color:var(--accent)}
section.appbox p{margin:0 0 10px;max-width:62ch;line-height:1.55}
section.appbox .appbtn{display:inline-block;padding:10px 18px;border-radius:999px;
  background:var(--accent);border:1px solid var(--accent);color:#fff;
  text-decoration:none;font-weight:600}
section.appbox .appbtn:hover{filter:brightness(1.08)}
section.appbox .appsteps{margin:4px 0 0;color:var(--dim);font-size:14px;
  max-width:62ch}
section.appbox .appsteps summary{cursor:pointer;color:var(--fg)}
section.appbox .appsteps ol{margin:8px 0 0;padding-left:20px;line-height:1.55}
section.appbox .appsteps code{background:var(--bg2);border:1px solid var(--line);
  border-radius:6px;padding:1px 6px;word-break:break-all;color:var(--fg)}
section.appbox .appcopy{margin-left:6px;padding:2px 10px;border-radius:999px;
  border:1px solid var(--accent);background:transparent;color:var(--accent);
  cursor:pointer;font:inherit;font-size:13px}
section.appbox .appqr{flex:none;text-align:center;width:150px}
section.appbox .appqrimg{display:block;width:150px;height:150px;border-radius:8px;
  border:1px solid var(--line)}
section.appbox .appqrcap{margin:6px 0 0;font-size:12px;line-height:1.35;
  color:var(--dim)}
@media (max-width:640px){section.appbox{padding:16px}
  section.appbox .appicon{display:none}
  section.appbox .appqr{display:none}}
@media (pointer:coarse){section.appbox .appqr{display:none}}
section.support{margin:34px 0 0;padding:22px 24px;border-radius:14px;
  background:var(--card);border:1px solid var(--line)}
section.support h2{margin:0 0 10px;font-size:18px;color:var(--accent)}
section.support p{margin:0 0 10px;max-width:62ch;line-height:1.55}
section.support .paylinks{display:flex;gap:10px;flex-wrap:wrap;margin-top:14px}
section.support .paylinks a{display:inline-block;padding:9px 16px;
  border-radius:999px;border:1px solid var(--accent);color:var(--accent);
  text-decoration:none;font-weight:600}
section.support .paylinks a:hover{background:var(--accent);color:#fff}
footer.site{padding:34px 0 20px;color:var(--dim);font-size:14px}
footer.site .links{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:10px}
footer.site .made{font-size:12px;opacity:.75;margin-top:14px}

#player{
  position:fixed;left:0;right:0;bottom:0;background:var(--card);
  border-top:1px solid var(--line);padding:10px 0 12px;z-index:50}
#player .inner{display:flex;gap:12px;align-items:center}
#player img{width:52px;height:52px;border-radius:7px;object-fit:cover;
  background:var(--bg2);border:1px solid var(--line);flex:0 0 auto}
#player .np{flex:1 1 auto;min-width:0}
#player .np .t{font-weight:600;white-space:nowrap;overflow:hidden;
  text-overflow:ellipsis}
#player .np .s{font-size:12.5px;color:var(--dim);white-space:nowrap;
  overflow:hidden;text-overflow:ellipsis}
#player .ctl{display:flex;gap:6px;align-items:center;flex:0 0 auto}
#bar{display:flex;gap:10px;align-items:center;margin-top:8px}
#bar .time{font-size:12px;color:var(--dim);
  font-variant-numeric:tabular-nums;width:44px;text-align:center;
  flex:0 0 auto}
input[type=range]{
  -webkit-appearance:none;appearance:none;height:5px;border-radius:3px;
  background:var(--line);outline:none;flex:1 1 auto;cursor:pointer}
input[type=range]::-webkit-slider-thumb{
  -webkit-appearance:none;width:14px;height:14px;border-radius:50%;
  background:var(--accent);border:none;cursor:pointer}
input[type=range]::-moz-range-thumb{
  width:14px;height:14px;border-radius:50%;background:var(--accent);
  border:none;cursor:pointer}
#vol{max-width:96px;flex:0 0 auto}
#err{color:#d9534f;font-size:13px;margin-top:6px;display:none}
.toggled{border-color:var(--accent);color:var(--accent)}

/* ---- letter index ---- */
.letters{display:flex;flex-wrap:wrap;gap:4px;margin:0 0 14px}
.letters[hidden]{display:none}
.lt{
  min-width:32px;height:32px;padding:0 8px;border-radius:8px;
  border:1px solid var(--line);background:var(--bg2);color:var(--fg);
  cursor:pointer;font-size:14px;font-weight:600}
.lt:hover{border-color:var(--accent);color:var(--accent)}
.lt.first-other{margin-left:10px}
#lj{
  position:fixed;right:14px;bottom:122px;z-index:60;height:42px;
  min-width:56px;padding:0 14px;border-radius:21px;
  border:1px solid var(--accent);background:var(--accent);color:#fff;
  font-weight:700;font-size:14px;cursor:pointer;
  box-shadow:0 2px 8px rgba(0,0,0,.35)}
#ljpanel{
  position:fixed;right:14px;bottom:172px;z-index:61;width:min(340px,92vw);
  max-height:55vh;overflow:auto;padding:12px;border-radius:14px;
  background:var(--card);border:1px solid var(--line);
  box-shadow:0 6px 24px rgba(0,0,0,.35);display:flex;flex-wrap:wrap;gap:4px}
#lj[hidden],#ljpanel[hidden],#lb[hidden],#ib[hidden]{display:none}
body.dl-only #lj{bottom:16px}
body.dl-only #ljpanel{bottom:66px}
.track,.ghead{scroll-margin-top:12px}
.track.flash{animation:flash 1.3s ease-out}
@keyframes flash{0%{box-shadow:0 0 0 3px var(--accent)}
  100%{box-shadow:var(--shadow)}}

/* ---- enlarged cover ---- */
#lb{
  position:fixed;left:0;top:0;right:0;bottom:0;z-index:100;
  background:rgba(0,0,0,.86);display:flex;align-items:center;
  justify-content:center;padding:20px;cursor:zoom-out}
#lb figure{margin:0;max-width:100%;max-height:100%;display:flex;
  flex-direction:column;align-items:center;gap:12px}
#lb img{min-width:min(80vw,440px);max-width:min(92vw,900px);max-height:76vh;
  border-radius:10px;
  object-fit:contain;background:var(--bg2);
  box-shadow:0 8px 40px rgba(0,0,0,.6)}
#lb figcaption{color:#fff;text-align:center;font-size:16px;font-weight:600;
  max-width:80ch}
#lb figcaption .s{opacity:.7;font-size:13px;font-weight:400}
.lbx{position:absolute;top:14px;right:18px;width:42px;height:42px;
  border-radius:50%;border:none;background:rgba(255,255,255,.18);
  color:#fff;font-size:24px;line-height:1;cursor:pointer}

/* ---- download page (host will not allow playback) ---- */
body.dl-only{padding-bottom:28px}
body.dl-only #player{display:none}
.dlbtn{
  display:inline-flex;align-items:center;gap:7px;white-space:nowrap;
  background:var(--accent);border:1px solid var(--accent);color:#fff;
  padding:9px 15px;border-radius:9px;font-size:14px;font-weight:600;
  text-decoration:none;cursor:pointer}
.dlbtn:hover{filter:brightness(1.08)}
.dlnote{
  margin:0 0 16px;padding:12px 16px;border-radius:10px;background:var(--bg2);
  border:1px solid var(--line);color:var(--dim);font-size:14px}
.dlnote strong{color:var(--fg)}
@media (max-width:640px){
  .track .num{display:none}
  .track .cover{width:52px;height:52px}
  .track .acts{gap:4px}
  .iconbtn{width:34px;height:34px;font-size:14px}
  #vol{display:none}
  header.site{padding-top:30px}
}
@media (max-width:430px){
  .wrap{padding:0 12px}
  .track{padding:8px;gap:10px}
  .track .act-link{display:none}   /* keep room for the title on phones */
  .cred .crole{flex-basis:92px}
  .iconbtn{width:32px;height:32px}
}
@media (prefers-reduced-motion: reduce){*{transition:none !important}}
</style>
</head>
<body>

<div class="wrap">
  <header class="site">
    @@NAV_HTML@@
    <h1>@@H1@@</h1>
    @@ARTIST_HTML@@
    @@TAGLINE_HTML@@
    @@ABOUT_HTML@@
  </header>

  <div class="rule"></div>

  @@APP_HTML@@

  <div id="dlnote" class="dlnote" hidden></div>

  @@SOURCE_HTML@@

  <div class="toolbar">
    @@SEARCH_HTML@@
    @@SHUFFLE_HTML@@
    <span class="count" id="count"></span>
  </div>

  <div class="chips" id="chips" hidden></div>
  <nav class="letters" id="letters" aria-label="Jump to a letter" hidden></nav>
  <div class="tracks" id="list"></div>

  @@SUPPORT_HTML@@

  <footer class="site">
    @@LINKS_HTML@@
    @@FOOTER_HTML@@
    @@MADE_HTML@@
  </footer>
</div>

<div id="player">
  <div class="wrap">
    <div class="inner">
      <img id="pcover" alt="">
      <div class="np">
        <div class="t" id="ptitle">&mdash;</div>
        <div class="s" id="psub">Pick a track to start</div>
      </div>
      <div class="ctl">
        <button class="iconbtn" id="prev" title="Previous (P)">&#9198;</button>
        <button class="iconbtn play" id="toggle" title="Play / pause (Space)">&#9654;</button>
        <button class="iconbtn" id="next" title="Next (N)">&#9197;</button>
      </div>
    </div>
    <div id="bar">
      <span class="time" id="cur">0:00</span>
      <input type="range" id="seek" min="0" max="1000" value="0" step="1"
             aria-label="Seek">
      <span class="time" id="dur">0:00</span>
      <input type="range" id="vol" min="0" max="100" value="100" step="1"
             aria-label="Volume" title="Volume">
    </div>
    <div id="err"></div>
  </div>
</div>

<audio id="au" preload="none"></audio>

<button id="lj" type="button" title="Jump to a letter" hidden>A&ndash;Z</button>
<div id="ljpanel" hidden></div>

<div id="lb" hidden>
  <button class="lbx" type="button" aria-label="Close">&times;</button>
  <figure>
    <img id="lbimg" alt="">
    <figcaption id="lbcap"></figcaption>
  </figure>
</div>

<div id="ib" hidden>
  <div class="card" role="dialog" aria-modal="true">
    <button class="ix" type="button" aria-label="Close">&times;</button>
    <div id="ibbody"></div>
  </div>
</div>

<script>
"use strict";
var DATA = @@DATA@@;
var OPT  = @@OPTIONS@@;

// Backup sources: the chosen one replaces every song's audio / cover address BEFORE anything is drawn.  The buttons store the
// choice and reload the page (?src=<id>, so a link can open the page already switched).
(function(){
  var S = OPT.sources || [];
  if(S.length < 2){ return; }
  var m = /[?&]src=([^&#]*)/.exec(location.search), id = "main";
  try{ id = m ? decodeURIComponent(m[1]) : (localStorage.getItem("musicsite_src") || "main"); }
  catch(e){ id = m ? decodeURIComponent(m[1]) : "main"; }
  if(S.indexOf(id) < 0){ id = "main"; }
  if(id !== "main"){
    DATA.forEach(function(t){
      var a = t.alt && t.alt[id];
      if(a){ if(a.audio){ t.audio = a.audio; } if(a.cover){ t.cover = a.cover; } }
    });
  }
  var bar = document.getElementById("srcbar");
  if(!bar){ return; }
  [].forEach.call(bar.querySelectorAll("button"), function(b){
    if(b.dataset.s === id){ b.classList.add("on"); }
    b.onclick = function(){
      try{ localStorage.setItem("musicsite_src", b.dataset.s); }catch(e){}
      location.href = location.pathname + "?src=" + encodeURIComponent(b.dataset.s) + location.hash;
    };
  });
})();

var TRACKS = DATA.filter(function(t){ return !t.hidden && t.audio; });
var au     = document.getElementById("au");
var listEl = document.getElementById("list");
var cur    = -1, shuffle = false, filtered = TRACKS.slice();
var groupFilter = "";

var GROUPS = (function(){
  var seen = [], out = [];
  TRACKS.forEach(function(t){
    var g = t.group || "";
    if(seen.indexOf(g) < 0){ seen.push(g); out.push(g); }
  });
  return out.length && out[0] === "" && out.length === 1 ? [] : out;
})();

function slugOf(s){
  return String(s || "other").toLowerCase()
    .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "other";
}

function esc(s){
  return String(s == null ? "" : s)
    .replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")
    .replace(/"/g,"&quot;");
}
function fmt(sec){
  if(!isFinite(sec) || sec < 0){ return "0:00"; }
  var m = Math.floor(sec/60), s = Math.floor(sec%60);
  return m + ":" + (s<10 ? "0"+s : s);
}
function placeholder(t){
  var letter = (t.title || "?").trim().charAt(0).toUpperCase() || "?";
  var svg = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'>"
    + "<rect width='120' height='120' fill='" + OPT.accent + "'/>"
    + "<text x='60' y='78' font-size='58' font-family='sans-serif'"
    + " fill='#ffffff' text-anchor='middle'>" + esc(letter) + "</text></svg>";
  return "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
}

/* ---------- credits: words first, then everybody else ---------- */
function creditLines(t){
  var out = [];
  if(t.words_by){ out.push({role: "Words", name: t.words_by}); }
  (t.credits || []).forEach(function(c){ out.push(c); });
  return out;
}
function creditText(c){ return c.role ? c.role + ": " + c.name : c.name; }

/* ---------- the "?" popup: made, about, earlier releases ---------- */
function releaseText(r){
  var s = r.medium || "";
  if(r.title){ s += (s ? " \u2014 " : "") + r.title; }
  if(r.when){ s += " (" + r.when + ")"; }
  return s;
}
function hasInfo(t){
  return !!(t.made || t.about || (t.released && t.released.length));
}

/* ---------- release numbers: #3 #9, each one a link into the discography ---- */
function relLink(n){
  return OPT.discoUrl + "#r" + n;
}
function relBadges(t, cls){
  if(!OPT.discoUrl || !t.rel || !t.rel.length){ return ""; }
  return '<span class="rels ' + cls + '">' + t.rel.map(function(n){
    return '<a class="rel" href="' + esc(relLink(n)) + '" title="'
      + esc((OPT.rels && OPT.rels[n]) || ("Release #" + n)) + '">#' + n
      + '</a>';
  }).join("") + '</span>';
}

/* ---------- list ---------- */
function render(){
  listEl.innerHTML = "";
  var lastGroup = null;
  filtered.forEach(function(t){
    var i = TRACKS.indexOf(t);

    /* a heading whenever the group changes (only when there IS more than one) */
    if(GROUPS.length > 1 && t.group !== lastGroup){
      lastGroup = t.group;
      var h = document.createElement("h2");
      h.className = "ghead";
      h.id = "g-" + slugOf(t.group);
      var n = filtered.filter(function(x){ return x.group === t.group; }).length;
      h.innerHTML = esc(t.group || "Other")
        + '<span class="gcount">' + n + (n === 1 ? " track" : " tracks")
        + '</span>';
      listEl.appendChild(h);
    }

    var li = document.createElement("div");
    li.className = "track";
    li.id = "t-" + t.slug;
    li.dataset.i = i;

    var sub = [];
    if(t.artist){ sub.push(t.artist); }
    if(t.year){ sub.push(t.year); }
    /* one credit fits on the line; more than that goes behind a button */
    var cl = creditLines(t);
    if(cl.length === 1){ sub.push(creditText(cl[0])); }
    if(t.description){ sub.push(t.description); }

    var html = ""
      + '<span class="num">' + (i+1) + '</span>'
      + '<img class="cover" loading="lazy" alt="" src="'
      +   esc(t.cover || placeholder(t)) + '">'
      + '<div class="meta">'
      +   '<div class="t">' + esc(t.title) + '</div>'
      +   (sub.length ? '<div class="s">' + esc(sub.join(" · ")) + '</div>' : '')
      +   relBadges(t, "rels-m")
      + '</div>'
      + '<div class="acts">'
      + relBadges(t, "rels-d");
    if(hasInfo(t)){
      html += '<button class="iconbtn qm act-info" '
           +  'title="More about this song">?</button>';
    }
    if(cl.length > 1){
      html += '<button class="iconbtn act-cred" title="Contributors">'
           +  '&#128101;</button>';
    }
    if(OPT.lyrics && t.lyrics){
      html += '<button class="iconbtn act-lyr" title="Words">&#9998;</button>';
    }
    if(OPT.downloadOnly){
      /* The host refuses to be embedded, but a link click is a normal
         navigation and is served fine - so the page is a download page. */
      html += '<a class="dlbtn" href="' + esc(t.audio) + '" '
           +  'rel="noopener" download>&#8681; Download</a>';
    }else{
      if(OPT.downloads){
        html += '<a class="iconbtn" title="Open / download the file" '
             +  'href="' + esc(t.audio) + '" target="_blank" rel="noopener" '
             +  'download>&#8681;</a>';
      }
      html += '<button class="iconbtn act-link" '
           +  'title="Copy link to this track">&#128279;</button>'
           +  '<button class="iconbtn play act-play" title="Play">'
           +  '&#9654;</button>';
    }
    html += '</div>';
    li.innerHTML = html;
    listEl.appendChild(li);

    if(hasInfo(t)){
      li.querySelector(".act-info").addEventListener("click", function(){
        openInfo(t);
      });
    }
    if(cl.length > 1){
      var cr = document.createElement("div");
      cr.className = "cred";
      cr.hidden = true;
      cr.innerHTML = cl.map(function(c){
        return '<div class="crow"><span class="crole">' + esc(c.role)
             + '</span><span class="cname">' + esc(c.name) + '</span></div>';
      }).join("");
      listEl.appendChild(cr);
      li.querySelector(".act-cred").addEventListener("click", function(){
        cr.hidden = !cr.hidden;
        this.classList.toggle("toggled", !cr.hidden);
      });
    }
    var ly = null;
    if(OPT.lyrics && t.lyrics){
      ly = document.createElement("div");
      ly.className = "lyr";
      ly.hidden = true;
      ly.textContent = t.lyrics;
      listEl.appendChild(ly);
      li.querySelector(".act-lyr").addEventListener("click", function(){
        ly.hidden = !ly.hidden;
      });
    }
    if(OPT.downloadOnly){
      /* nothing to play - a click on the title just opens the words */
      var titleEl = li.querySelector(".t");
      var coverEl = li.querySelector(".cover");
      var ly2 = ly;
      var hasLyr = !!ly2;
      titleEl.style.cursor = hasLyr ? "pointer" : "default";
      coverEl.style.cursor = t.cover ? "zoom-in" : "default";
      if(t.cover){
        coverEl.addEventListener("click", function(){ openCover(t); });
      }
      if(hasLyr){
        titleEl.addEventListener("click", function(){
          ly2.hidden = !ly2.hidden;
        });
      }
      return;
    }

    li.querySelector(".act-play").addEventListener("click", function(){
      (cur === i && !au.paused) ? au.pause() : play(i);
    });
    li.querySelector(".t").addEventListener("click", function(){ play(i); });
    var cv = li.querySelector(".cover");
    if(t.cover){
      cv.addEventListener("click", function(){ openCover(t); });
    }else{
      cv.style.cursor = "pointer";       /* nothing to enlarge: play */
      cv.addEventListener("click", function(){ play(i); });
    }
    li.querySelector(".act-link").addEventListener("click", function(){
      var url = location.origin + location.pathname + "#" + t.slug;
      if(navigator.clipboard){ navigator.clipboard.writeText(url); }
      this.textContent = "✓";
      var b = this;
      setTimeout(function(){ b.innerHTML = "&#128279;"; }, 1200);
    });
  });
  document.getElementById("count").textContent =
    filtered.length + (filtered.length === 1 ? " track" : " tracks");
  buildLetters();
  markPlaying();
}

function markPlaying(){
  var items = listEl.querySelectorAll(".track");
  for(var k = 0; k < items.length; k++){
    var on = (parseInt(items[k].dataset.i,10) === cur);
    items[k].classList.toggle("playing", on);
    var b = items[k].querySelector(".act-play");
    if(b){ b.innerHTML = (on && !au.paused) ? "&#10073;&#10073;" : "&#9654;"; }
  }
}

/* ---------- playback ---------- */
function play(i){
  if(i < 0 || i >= TRACKS.length){ return; }
  var t = TRACKS[i];
  document.getElementById("err").style.display = "none";
  if(cur !== i){
    cur = i;
    au.src = t.audio;
    document.getElementById("ptitle").textContent = t.title;
    document.getElementById("psub").textContent =
      [t.artist || OPT.artist, t.year]
      .concat(creditLines(t).map(creditText)).filter(Boolean).join(" · ")
      || " ";
    document.getElementById("pcover").src = t.cover || placeholder(t);
    document.title = t.title + " — " + OPT.site_title;
    if("mediaSession" in navigator){
      try{
        navigator.mediaSession.metadata = new MediaMetadata({
          title: t.title,
          artist: t.artist || OPT.artist || "",
          album: OPT.site_title,
          artwork: t.cover ? [{src:t.cover, sizes:"512x512"}] : []
        });
      }catch(e){}
    }
  }
  var p = au.play();
  if(p && p.catch){ p.catch(function(){}); }
}

document.getElementById("toggle").addEventListener("click", function(){
  if(cur < 0){ play(filtered.length ? TRACKS.indexOf(filtered[0]) : 0); return; }
  au.paused ? au.play() : au.pause();
});
document.getElementById("next").addEventListener("click", function(){ step(1); });
document.getElementById("prev").addEventListener("click", function(){
  if(au.currentTime > 3){ au.currentTime = 0; return; }
  step(-1);
});

function step(d){
  if(!TRACKS.length){ return; }
  if(shuffle){
    var n = cur;
    if(TRACKS.length > 1){
      while(n === cur){ n = Math.floor(Math.random()*TRACKS.length); }
    }
    play(n);
    return;
  }
  play((cur + d + TRACKS.length) % TRACKS.length);
}

au.addEventListener("play",  function(){
  document.getElementById("toggle").innerHTML = "&#10073;&#10073;";
  markPlaying();
});
au.addEventListener("pause", function(){
  document.getElementById("toggle").innerHTML = "&#9654;";
  markPlaying();
});
au.addEventListener("ended", function(){
  if(OPT.autonext){ step(1); }
});
au.addEventListener("error", function(){
  var e = document.getElementById("err");
  e.textContent = "This file could not be loaded. The host may be busy or "
    + "the link may have changed — try again in a while.";
  e.style.display = "block";
});
au.addEventListener("loadedmetadata", function(){
  document.getElementById("dur").textContent = fmt(au.duration);
});
au.addEventListener("timeupdate", function(){
  document.getElementById("cur").textContent = fmt(au.currentTime);
  if(!seeking && au.duration){
    seek.value = Math.round(au.currentTime / au.duration * 1000);
  }
});

var seek = document.getElementById("seek"), seeking = false;
seek.addEventListener("input",  function(){ seeking = true; });
seek.addEventListener("change", function(){
  if(au.duration){ au.currentTime = au.duration * (seek.value/1000); }
  seeking = false;
});
var vol = document.getElementById("vol");
try{
  var sv = localStorage.getItem("ms_vol");
  if(sv !== null){ vol.value = sv; }
}catch(e){}
au.volume = vol.value / 100;
vol.addEventListener("input", function(){
  au.volume = vol.value / 100;
  try{ localStorage.setItem("ms_vol", vol.value); }catch(e){}
});

/* ---------- search + shuffle ---------- */
var search = document.getElementById("search");

function applyFilter(){
  var q = search ? search.value.trim().toLowerCase() : "";
  filtered = TRACKS.filter(function(t){
    if(groupFilter && (t.group || "") !== groupFilter){ return false; }
    if(!q){ return true; }
    return (t.title + " " + (t.artist||"") + " " + (t.year||"") + " "
            + (t.made||"") + " " + (t.about||"") + " "
            + (t.released||[]).map(releaseText).join(" ") + " "
            + creditLines(t).map(creditText).join(" ") + " "
            + (t.description||"") + " " + (t.lyrics||""))
           .toLowerCase().indexOf(q) >= 0;
  });
  render();
}
if(search){ search.addEventListener("input", applyFilter); }

/* one chip per group, so a big collection stays walkable */
if(GROUPS.length > 1){
  var chipBox = document.getElementById("chips");
  chipBox.hidden = false;
  var defs = [{label:"All", value:""}].concat(GROUPS.map(function(g){
    return {label: g || "Other", value: g};
  }));
  defs.forEach(function(d){
    var b = document.createElement("button");
    b.className = "chip" + (d.value === groupFilter ? " on" : "");
    b.textContent = d.label;
    b.addEventListener("click", function(){
      groupFilter = d.value;
      chipBox.querySelectorAll(".chip").forEach(function(c){
        c.classList.remove("on");
      });
      b.classList.add("on");
      applyFilter();
      window.scrollTo({top: 0});
    });
    chipBox.appendChild(b);
  });
}
var shufBtn = document.getElementById("shuf");
if(shufBtn){
  shufBtn.addEventListener("click", function(){
    shuffle = !shuffle;
    shufBtn.classList.toggle("toggled", shuffle);
    shufBtn.setAttribute("aria-pressed", shuffle ? "true" : "false");
  });
}

/* ---------- download page (host refuses playback, downloads are fine) ---- */
if(OPT.downloadOnly){
  document.body.classList.add("dl-only");
  var note = document.getElementById("dlnote");
  note.innerHTML =
      "<strong>&#8681; Every song here is free to download.</strong> "
    + "Press Download on any track to save the file. "
    + "The songs cannot be played straight from this page, because the "
    + "place the files are kept does not allow that &mdash; but the "
    + "download itself works fine.";
  note.hidden = false;
}

/* ---------- the "?" popup ---------- */
var ib = document.getElementById("ib"), ibBody = document.getElementById("ibbody");
function openInfo(t){
  var h = "<h3>" + esc(t.title) + "</h3>";
  if(t.made){
    h += '<div class="irow"><div class="ilab">Made</div>' + esc(t.made) + "</div>";
  }
  if(t.about){
    h += '<div class="irow"><div class="ilab">About</div>' + esc(t.about) + "</div>";
  }
  if(t.released && t.released.length){
    h += '<div class="irow"><div class="ilab">Released before on</div><ul>'
      + t.released.map(function(r){ return "<li>" + esc(releaseText(r)) + "</li>"; })
        .join("") + "</ul></div>";
  }
  if(OPT.discoUrl && t.rel && t.rel.length){
    h += '<div class="irow"><div class="ilab">On the discography</div><ul>'
      + t.rel.map(function(n){
          return '<li><a href="' + esc(relLink(n)) + '">#' + n + "</a> "
            + esc((OPT.rels && OPT.rels[n]) || "") + "</li>";
        }).join("") + "</ul></div>";
  }
  ibBody.innerHTML = h;
  ib.hidden = false;
}
function closeInfo(){ ib.hidden = true; ibBody.innerHTML = ""; }
ib.addEventListener("click", function(ev){
  if(ev.target === ib || ev.target.className === "ix"){ closeInfo(); }
});

/* ---------- enlarged cover ---------- */
var lb = document.getElementById("lb"), lbImg = document.getElementById("lbimg"),
    lbCap = document.getElementById("lbcap");
function openCover(t){
  var sub = [];
  if(t.artist){ sub.push(t.artist); }
  if(t.year){ sub.push(t.year); }
  creditLines(t).forEach(function(c){ sub.push(creditText(c)); });
  lbImg.src = t.cover;
  lbImg.alt = t.title;
  lbCap.innerHTML = "<div>" + esc(t.title) + "</div>"
    + (sub.length ? '<div class="s">' + esc(sub.join(" · ")) + "</div>" : "");
  lb.hidden = false;
}
function closeCover(){ lb.hidden = true; lbImg.removeAttribute("src"); }
lb.addEventListener("click", closeCover);

/* ---------- letter index ---------- */
var letterBar = document.getElementById("letters"),
    ljBtn = document.getElementById("lj"),
    ljPanel = document.getElementById("ljpanel"),
    letterOK = false, SWE = "\u00c5\u00c4\u00d6";

/* the letter a title is filed under: digits -> #, Å Ä Ö kept apart, other
   accented Latin letters under their base letter (É -> E), any other
   alphabet under its own letter, quotes and brackets in front skipped */
function letterOf(title){
  var s = String(title || "");
  for(var k = 0; k < s.length; k++){
    var ch = s.charAt(k);
    if(ch >= "0" && ch <= "9"){ return "#"; }
    var isL = false;
    try{ isL = /\p{L}/u.test(ch); }
    catch(e){ isL = ch.toLowerCase() !== ch.toUpperCase(); }
    if(!isL){ continue; }
    var up = ch.toUpperCase();
    if(SWE.indexOf(up) >= 0){ return up; }
    var base = up;
    try{ base = up.normalize("NFD").charAt(0); }catch(e){}
    if(base >= "A" && base <= "Z"){ return base; }
    return up;
  }
  return "#";
}
function letterRank(l){
  if(l === "#"){ return 0; }
  if(l.length === 1 && l >= "A" && l <= "Z"){ return 1; }
  if(SWE.indexOf(l) >= 0){ return 2; }
  return 3;
}
function buildLetters(){
  var first = Object.create(null), order = [];
  filtered.forEach(function(t){
    var l = letterOf(t.title);
    if(!(l in first)){ first[l] = t; order.push(l); }
  });
  letterOK = filtered.length >= 12 && order.length >= 2;
  letterBar.innerHTML = "";
  ljPanel.innerHTML = "";
  letterBar.hidden = !letterOK;
  if(!letterOK){ ljBtn.hidden = true; ljPanel.hidden = true; return; }
  order.sort(function(a, b){
    var ra = letterRank(a), rb = letterRank(b);
    if(ra !== rb){ return ra - rb; }
    if(ra === 2){ return SWE.indexOf(a) - SWE.indexOf(b); }
    return a < b ? -1 : (a > b ? 1 : 0);
  });
  var prev = -1;
  order.forEach(function(l){
    var rk = letterRank(l);
    var cls = "lt" + (rk === 3 && prev !== 3 ? " first-other" : "");
    prev = rk;
    [letterBar, ljPanel].forEach(function(box){
      var b = document.createElement("button");
      b.type = "button";
      b.className = cls;
      b.textContent = l;
      b.title = l;
      b.addEventListener("click", function(){ jumpTo(first[l]); });
      box.appendChild(b);
    });
  });
  var lo = order[0] === "#" ? order[1] : order[0];
  var hi = order[order.length - 1];
  ljBtn.textContent = lo === hi ? lo : lo + "\u2013" + hi;
  updateLj();
}
function jumpTo(t){
  ljPanel.hidden = true;
  var el = document.getElementById("t-" + t.slug);
  if(!el){ return; }
  var calm = window.matchMedia &&
             window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  el.scrollIntoView({behavior: calm ? "auto" : "smooth", block: "start"});
  el.classList.remove("flash");
  void el.offsetWidth;
  el.classList.add("flash");
}
/* the little button shows only while the letter row is out of sight */
function updateLj(){
  if(!letterOK){ return; }
  var away = letterBar.getBoundingClientRect().bottom < 0;
  ljBtn.hidden = !away;
  if(!away){ ljPanel.hidden = true; }
}
ljBtn.addEventListener("click", function(){ ljPanel.hidden = !ljPanel.hidden; });
document.addEventListener("click", function(ev){
  if(!ljPanel.hidden && ev.target !== ljBtn && !ljPanel.contains(ev.target)){
    ljPanel.hidden = true;
  }
});
var ljTick = false;
function ljSoon(){
  if(ljTick){ return; }
  ljTick = true;
  requestAnimationFrame(function(){ ljTick = false; updateLj(); });
}
window.addEventListener("scroll", ljSoon, {passive: true});
window.addEventListener("resize", ljSoon);
document.addEventListener("keydown", function(ev){
  if(ev.key === "Escape"){
    if(!lb.hidden){ closeCover(); }
    if(!ib.hidden){ closeInfo(); }
    ljPanel.hidden = true;
  }
});

/* ---------- keyboard ---------- */
document.addEventListener("keydown", function(ev){
  if(OPT.downloadOnly){ return; }
  var tag = (ev.target && ev.target.tagName || "").toLowerCase();
  if(tag === "input" || tag === "textarea"){ return; }
  if(ev.key === " "){
    ev.preventDefault();
    document.getElementById("toggle").click();
  }else if(ev.key === "ArrowRight"){ au.currentTime += 5; }
  else if(ev.key === "ArrowLeft"){  au.currentTime -= 5; }
  else if(ev.key === "n" || ev.key === "N"){ step(1); }
  else if(ev.key === "p" || ev.key === "P"){ step(-1); }
});

/* ---------- deep link ---------- */
render();
(function(){
  var h = (location.hash || "").replace("#","");
  if(!h){ return; }
  for(var i = 0; i < TRACKS.length; i++){
    if(TRACKS[i].slug === h){
      var el = document.getElementById("t-" + h);
      if(el){ el.scrollIntoView({block:"center"}); }
      if(!OPT.downloadOnly){ play(i); }
      return;
    }
  }
})();
</script>
</body>
</html>
"""

# The other pages (discography, about me).  Plain HTML with no script at all:
# the anchors do the scrolling.  The colours are the same variables as in
# PAGE_TEMPLATE above - keep the two in step.
SUBPAGE_TEMPLATE = r"""<!doctype html>
<html lang="en" data-theme="@@THEME@@">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@@TITLE@@</title>
<meta name="description" content="@@META@@">
<meta property="og:title" content="@@TITLE@@">
<meta property="og:description" content="@@META@@">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='@@ACCENT_ENC@@'/%3E%3Cpath d='M13 8v11.2a3.2 3.2 0 1 0 2 2.97V12h6V8z' fill='%23fff'/%3E%3C/svg%3E">
<style>
:root{
  --accent:@@ACCENT@@;
  --bg:#ffffff; --bg2:#f5f5f8; --card:#ffffff; --fg:#17171c;
  --dim:#5f5f6b; --line:#e3e3ea; --shadow:0 1px 3px rgba(0,0,0,.10);
}
html[data-theme="dark"]{
  --bg:#0f0f13; --bg2:#17171e; --card:#1a1a22; --fg:#ececf2;
  --dim:#9c9caa; --line:#2b2b36; --shadow:0 1px 3px rgba(0,0,0,.45);
}
@media (prefers-color-scheme: dark){
  html[data-theme="auto"]{
    --bg:#0f0f13; --bg2:#17171e; --card:#1a1a22; --fg:#ececf2;
    --dim:#9c9caa; --line:#2b2b36; --shadow:0 1px 3px rgba(0,0,0,.45);
  }
}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
html,body{margin:0;padding:0}
body{
  background:var(--bg); color:var(--fg);
  font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,
       "Helvetica Neue",Arial,sans-serif;
  padding-bottom:30px;
  -webkit-font-smoothing:antialiased;
}
a{color:var(--accent)}
.wrap{max-width:920px;margin:0 auto;padding:0 18px}
header.site{padding:44px 0 10px}
header.site h1{margin:0;font-size:clamp(28px,5vw,44px);line-height:1.1;
  letter-spacing:-.02em}
header.site .lead{margin:12px 0 0;max-width:62ch;color:var(--dim)}
.rule{height:1px;background:var(--line);margin:22px 0 18px}

.topnav{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 24px}
.topnav a{padding:7px 14px;border-radius:999px;border:1px solid var(--line);
  background:var(--bg2);color:var(--fg);text-decoration:none;font-size:14px;
  font-weight:600}
.topnav a:hover{border-color:var(--accent)}
.topnav a.on{background:var(--accent);border-color:var(--accent);color:#fff}

/* ---- discography ---- */
.jump{display:flex;gap:6px;flex-wrap:wrap;margin:0 0 20px}
.jump a{min-width:42px;text-align:center;padding:5px 10px;border-radius:8px;
  border:1px solid var(--line);background:var(--bg2);color:var(--fg);
  text-decoration:none;font-size:13.5px;font-weight:700;
  font-variant-numeric:tabular-nums}
.jump a:hover{border-color:var(--accent);color:var(--accent)}
article.release{
  background:var(--card);border:1px solid var(--line);border-radius:14px;
  padding:16px 18px 12px;margin:0 0 16px;box-shadow:var(--shadow);
  scroll-margin-top:14px}
article.release:target{border-color:var(--accent);
  box-shadow:0 0 0 3px var(--accent)}
article.release .top{display:flex;gap:14px;align-items:center}
article.release .no{
  flex:0 0 auto;min-width:54px;height:54px;padding:0 10px;border-radius:12px;
  background:var(--accent);color:#fff;font-size:21px;font-weight:800;
  display:flex;align-items:center;justify-content:center;
  font-variant-numeric:tabular-nums}
article.release h2{margin:0;font-size:20px;line-height:1.2;
  overflow-wrap:anywhere}
article.release .sub{color:var(--dim);font-size:14px;margin-top:2px}
dl.facts{display:grid;grid-template-columns:max-content 1fr;gap:3px 14px;
  margin:14px 0 6px;font-size:14px}
dl.facts dt{color:var(--dim)}
dl.facts dd{margin:0;overflow-wrap:anywhere}
details.tl{margin-top:8px}
details.tl summary{cursor:pointer;color:var(--dim);font-size:13.5px;
  padding:4px 0}
ul.tracks{list-style:none;margin:6px 0 4px;padding:0;
  columns:2 280px;column-gap:28px}
ul.tracks li{padding:2px 0;break-inside:avoid;overflow-wrap:anywhere}
ul.tracks li .n{display:inline-block;min-width:26px;color:var(--dim);
  font-size:13px;font-variant-numeric:tabular-nums}
ul.tracks li.side{font-weight:700;color:var(--accent);padding:16px 0 2px;
  column-span:none}
ul.tracks li.side:first-child{padding-top:2px}
ul.tracks li.gap{height:12px;padding:0}
ul.tracks li .by{display:block;margin-left:26px;color:var(--dim);
  font-size:12.5px;line-height:1.35}
.mk{color:var(--accent);font-weight:700}
sup.mk{margin-left:3px;font-size:11px}
.cred{margin:12px 0 4px;padding:10px 14px;border-radius:10px;
  background:var(--bg2);border:1px solid var(--line);font-size:14px}
.cred h3{margin:0 0 4px;font-size:13px;color:var(--dim);font-weight:600;
  text-transform:uppercase;letter-spacing:.05em}
.cred ul{margin:0;padding-left:18px}
.cred li{padding:1px 0;overflow-wrap:anywhere}
ul.tracks li a{text-decoration:none}
ul.tracks li a:hover{text-decoration:underline}
.note{color:var(--dim);font-size:13.5px;margin:8px 0 0}

/* ---- about ---- */
.aboutbody{max-width:66ch;font-size:16px}
.aboutbody img{max-width:100%;height:auto;border-radius:12px;margin:0 0 18px;
  display:block}
.aboutbody p{margin:0 0 14px}
.soon{color:var(--dim);font-style:italic}

footer.site{padding:30px 0 10px;color:var(--dim);font-size:14px}
footer.site .links{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:10px}
footer.site .made{font-size:12px;opacity:.75;margin-top:14px}
@media (max-width:430px){
  .wrap{padding:0 12px}
  article.release{padding:14px 12px 10px}
  article.release .no{min-width:46px;height:46px;font-size:18px}
  dl.facts{grid-template-columns:1fr;gap:0}
  dl.facts dt{margin-top:6px}
}
@media (prefers-reduced-motion: reduce){html{scroll-behavior:auto}}
</style>
</head>
<body>
<div class="wrap">
  <header class="site">
    @@NAV_HTML@@
    <h1>@@H1@@</h1>
    @@LEAD_HTML@@
  </header>
  <div class="rule"></div>
  @@BODY_HTML@@
  <footer class="site">
    @@LINKS_HTML@@
    @@FOOTER_HTML@@
    @@MADE_HTML@@
  </footer>
</div>
</body>
</html>
"""


# *****************************************************************************
# DEL 11 - HTML BUILDER
# *****************************************************************************
def para_html(text):
    """Plain text the way he typed it -> paragraphs on the page.

    A blank line starts a new paragraph, a single newline is a line break.
    Without this his own text arrived as one grey lump, which is why it
    looked as if it could not be written at all.
    """
    out = []
    for block in re.split(r"\n\s*\n", (text or "").strip()):
        block = block.strip()
        if block:
            out.append("<p>%s</p>" % esc(block).replace("\n", "<br>"))
    return "".join(out)


def esc(s):
    return html.escape(str(s or ""), quote=True)


# ----- QR code maker (v1.17.0) -----------------------------------------------
# Own small encoder (no pip module needed): byte mode, error correction M,
# versions 1-10 (up to 213 bytes).  Same code as the Android apps' QrCode.java;
# checked module by module against the `segno` library (mask forced equal).
_QR_ECC_PER_BLOCK = [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26]
_QR_NUM_BLOCKS = [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5]


def _qr_raw_modules(ver):
    r = (16 * ver + 128) * ver + 64
    if ver >= 2:
        n = ver // 7 + 2
        r -= (25 * n - 10) * n - 55
        if ver >= 7:
            r -= 36
    return r


def _qr_mul(x, y):                      # multiplication in GF(2^8), poly 0x11D
    z = 0
    for i in range(7, -1, -1):
        z = (z << 1) ^ ((z >> 7) * 0x11D)
        z ^= ((y >> i) & 1) * x
    return z


def _qr_rs_divisor(degree):
    r = [0] * degree
    r[degree - 1] = 1
    root = 1
    for _ in range(degree):
        for j in range(degree):
            r[j] = _qr_mul(r[j], root)
            if j + 1 < degree:
                r[j] ^= r[j + 1]
        root = _qr_mul(root, 2)
    return r


def _qr_rs_remainder(data, div):
    r = [0] * len(div)
    for b in data:
        factor = b ^ r[0]
        r = r[1:] + [0]
        for j in range(len(r)):
            r[j] ^= _qr_mul(div[j], factor)
    return r


def _qr_codewords(data, ver):
    nb, ec = _QR_NUM_BLOCKS[ver], _QR_ECC_PER_BLOCK[ver]
    raw = _qr_raw_modules(ver) // 8
    n_short, short_len = nb - raw % nb, raw // nb
    div = _qr_rs_divisor(ec)
    blocks, k = [], 0
    for i in range(nb):
        dl = short_len - ec + (0 if i < n_short else 1)
        dat = data[k:k + dl]
        k += dl
        block = dat + ([0] if i < n_short else []) + _qr_rs_remainder(dat, div)
        blocks.append(block)
    out = []
    for i in range(len(blocks[0])):
        for j in range(nb):
            if i != short_len - ec or j >= n_short:
                out.append(blocks[j][i])
    return out


def qr_matrix(text, forced_mask=-1):
    """Rows of booleans (True = dark) for `text`; ValueError when too long."""
    data = text.encode("utf-8")
    ver = 0
    for v in range(1, 11):
        cap = (_qr_raw_modules(v) // 8 - _QR_ECC_PER_BLOCK[v] * _QR_NUM_BLOCKS[v]) * 8
        if 4 + (8 if v < 10 else 16) + 8 * len(data) <= cap:
            ver = v
            break
    if not ver:
        raise ValueError("text too long for a QR code")
    data_cw = _qr_raw_modules(ver) // 8 - _QR_ECC_PER_BLOCK[ver] * _QR_NUM_BLOCKS[ver]
    bits = []
    def put(value, ln):
        bits.extend(((value >> i) & 1) for i in range(ln - 1, -1, -1))
    put(4, 4)
    put(len(data), 8 if ver < 10 else 16)
    for b in data:
        put(b, 8)
    bits.extend([0] * min(4, data_cw * 8 - len(bits)))
    while len(bits) % 8:
        bits.append(0)
    cw = [int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)]
    pad = 0xEC
    while len(cw) < data_cw:
        cw.append(pad)
        pad ^= 0xEC ^ 0x11
    allcw = _qr_codewords(cw, ver)

    size = ver * 4 + 17
    mod = [[False] * size for _ in range(size)]
    fn = [[False] * size for _ in range(size)]

    def set_fn(x, y, dark):
        mod[y][x] = dark
        fn[y][x] = True

    def finder(cx, cy):
        for dy in range(-4, 5):
            for dx in range(-4, 5):
                dist, x, y = max(abs(dx), abs(dy)), cx + dx, cy + dy
                if 0 <= x < size and 0 <= y < size:
                    set_fn(x, y, dist not in (2, 4))

    def draw_format(m):
        rem = m
        for _ in range(10):
            rem = (rem << 1) ^ ((rem >> 9) * 0x537)
        fb = ((m << 10) | rem) ^ 0x5412
        bit = lambda i: ((fb >> i) & 1) != 0
        for i in range(0, 6):
            set_fn(8, i, bit(i))
        set_fn(8, 7, bit(6))
        set_fn(8, 8, bit(7))
        set_fn(7, 8, bit(8))
        for i in range(9, 15):
            set_fn(14 - i, 8, bit(i))
        for i in range(8):
            set_fn(size - 1 - i, 8, bit(i))
        for i in range(8, 15):
            set_fn(8, size - 15 + i, bit(i))
        set_fn(8, size - 8, True)

    for i in range(size):
        set_fn(6, i, i % 2 == 0)
        set_fn(i, 6, i % 2 == 0)
    finder(3, 3)
    finder(size - 4, 3)
    finder(3, size - 4)
    if ver > 1:
        n = ver // 7 + 2
        step = (ver * 4 + n * 2 + 1) // (n * 2 - 2) * 2
        ap = [6] + [0] * (n - 1)
        pos = size - 7
        for i in range(n - 1, 0, -1):
            ap[i] = pos
            pos -= step
        for i in range(n):
            for j in range(n):
                if (i == 0 and j == 0) or (i == 0 and j == n - 1) or (i == n - 1 and j == 0):
                    continue
                for dy in range(-2, 3):
                    for dx in range(-2, 3):
                        set_fn(ap[i] + dx, ap[j] + dy, max(abs(dx), abs(dy)) != 1)
    draw_format(0)
    if ver >= 7:
        rem = ver
        for _ in range(12):
            rem = (rem << 1) ^ ((rem >> 11) * 0x1F25)
        vb = (ver << 12) | rem
        for i in range(18):
            b = ((vb >> i) & 1) != 0
            a, c = size - 11 + i % 3, i // 3
            set_fn(a, c, b)
            set_fn(c, a, b)

    i, total_bits = 0, len(allcw) * 8
    right = size - 1
    while right >= 1:
        if right == 6:
            right = 5
        for vert in range(size):
            for j in range(2):
                x = right - j
                upward = ((right + 1) & 2) == 0
                y = size - 1 - vert if upward else vert
                if not fn[y][x] and i < total_bits:
                    mod[y][x] = ((allcw[i >> 3] >> (7 - (i & 7))) & 1) != 0
                    i += 1
        right -= 2

    def apply_mask(m):
        for y in range(size):
            for x in range(size):
                if m == 0:
                    inv = (x + y) % 2 == 0
                elif m == 1:
                    inv = y % 2 == 0
                elif m == 2:
                    inv = x % 3 == 0
                elif m == 3:
                    inv = (x + y) % 3 == 0
                elif m == 4:
                    inv = (x // 3 + y // 2) % 2 == 0
                elif m == 5:
                    inv = x * y % 2 + x * y % 3 == 0
                elif m == 6:
                    inv = (x * y % 2 + x * y % 3) % 2 == 0
                else:
                    inv = ((x + y) % 2 + x * y % 3) % 2 == 0
                if inv and not fn[y][x]:
                    mod[y][x] = not mod[y][x]

    def penalty():
        p = 0
        for d in range(2):
            for a in range(size):
                run = 1
                for b in range(1, size):
                    cur = mod[a][b] if d == 0 else mod[b][a]
                    prev = mod[a][b - 1] if d == 0 else mod[b - 1][a]
                    if cur == prev:
                        run += 1
                    else:
                        if run >= 5:
                            p += 3 + run - 5
                        run = 1
                if run >= 5:
                    p += 3 + run - 5
        for y in range(size - 1):
            for x in range(size - 1):
                c = mod[y][x]
                if c == mod[y][x + 1] and c == mod[y + 1][x] and c == mod[y + 1][x + 1]:
                    p += 3
        pats = ([0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0])
        for d in range(2):
            for a in range(size):
                line = [False] * 4 + [mod[a][b] if d == 0 else mod[b][a]
                                      for b in range(size)] + [False] * 4
                for s in range(len(line) - 10):
                    for pat in pats:
                        if all(line[s + k] == (pat[k] == 1) for k in range(11)):
                            p += 40
        dark = sum(1 for row in mod for v in row if v)
        tot = size * size
        k = (abs(dark * 20 - tot * 10) + tot - 1) // tot - 1
        return p + k * 10

    best = forced_mask
    if forced_mask < 0:
        best_pen = None
        for m in range(8):
            apply_mask(m)
            draw_format(m)
            pen = penalty()
            apply_mask(m)
            if best_pen is None or pen < best_pen:
                best_pen, best = pen, m
    apply_mask(best)
    draw_format(best)
    return mod


def qr_svg(text, px=168):
    """The QR code of `text` as an inline <svg> (white square, 4 modules quiet
    zone, dark modules as one path), or "" when it cannot be made."""
    try:
        m = qr_matrix(text)
    except Exception:
        return ""
    n = len(m)
    d = "".join("M%d %dh1v1h-1z" % (x + 4, y + 4)
                for y in range(n) for x in range(n) if m[y][x])
    return ('<svg class="appqrimg" xmlns="http://www.w3.org/2000/svg" '
            'viewBox="0 0 %d %d" width="%d" height="%d" role="img" '
            'aria-label="QR code" shape-rendering="crispEdges">'
            '<rect width="100%%" height="100%%" fill="#fff"/>'
            '<path d="%s" fill="#000"/></svg>' % (n + 8, n + 8, px, px, d))


def app_download_url(url):
    """The address behind the app button.

    A Google Drive share link ("drive.google.com/file/d/ID/view") opens a
    viewer page; the link a phone needs is the direct download of that file.
    Any other address is used as typed.
    """
    url = (url or "").strip()
    if "drive.google.com" in url or "drive.usercontent.google.com" in url:
        m = (re.search(r"/file/d/([A-Za-z0-9_\-]{10,})", url)
             or re.search(r"[?&]id=([A-Za-z0-9_\-]{10,})", url))
        if m:
            return ("https://drive.usercontent.google.com/download?id=%s"
                    "&export=download&confirm=t" % m.group(1))
    return url


def app_box_html(site):
    """The 'Get the Android app' box, or "" when it is off / has no address."""
    url = app_download_url(site.get("app_url", ""))
    if not site.get("show_app", True) or not url:
        return ""
    button = site.get("app_button") or "Download the app (APK)"
    head = ('<h2>%s</h2>' % esc(site["app_title"])
            if site.get("app_title") else "")
    # v1.17.0: a QR code of the same download address, for a visitor on a
    # computer (scan it with the phone).  Hidden on phones/touch screens by the
    # style sheet; left out when the address is not a web address.
    qr_html = ""
    if re.match(r"https?://", url, re.I):
        svg = qr_svg(url)
        if svg:
            qr_html = ('<div class="appqr">%s<p class="appqrcap">Scan with your '
                       'phone to download the app</p></div>' % svg)
    return (
        '<section class="appbox" id="appbox">'
        '<div class="appicon" aria-hidden="true">&#128241;</div>'
        '<div class="appbody">%s%s'
        '<p><a class="appbtn" href="%s" rel="noopener">&#11015; %s</a></p>'
        '<details class="appsteps"><summary>How to install it</summary><ol>'
        '<li>Tap the button.  The phone saves a file called '
        '<b>MusicSitePlayer.apk</b>.</li>'
        '<li>Open that file (from the notification or the Downloads folder).  '
        'The first time, Android asks whether your browser may install apps '
        '- allow it, then press Install.  Your phone may also warn that the '
        'app is not from the Play Store; that is true, it comes from this '
        'page.</li>'
        '<li>Open the app, tap the gear and, under <b>Where the songs come '
        'from</b>, type the address of this page: '
        '<code id="appaddr">this page</code> '
        '<button type="button" class="appcopy" id="appcopy" hidden>Copy'
        '</button></li></ol></details>'
        '</div>%s</section>'
        '<script>(function(){var a=document.getElementById("appaddr"),'
        'b=document.getElementById("appcopy");'
        'if(!a||!/^https?:/i.test(location.href))return;'
        'var u=location.href.split("#")[0].split("?")[0];a.textContent=u;'
        'if(b&&navigator.clipboard){b.hidden=false;b.onclick=function(){'
        'navigator.clipboard.writeText(u).then(function(){'
        'b.textContent="Copied"},function(){});};}})();</script>'
        % (head, para_html(site.get("app_text", "")), esc(url), esc(button),
           qr_html))


def _download_one(url, dst, timeout=180):
    """Fetch a URL (or copy a local file) to dst.  Returns bytes written."""
    if os.path.isabs(url) and os.path.isfile(url):
        shutil.copy2(url, dst)
        return os.path.getsize(dst)
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT,
                                               "Accept": "*/*"})
    tmp = dst + ".part"
    total = 0
    with urllib.request.urlopen(req, timeout=timeout) as r, \
            open(tmp, "wb") as f:
        while True:
            chunk = r.read(262144)
            if not chunk:
                break
            f.write(chunk)
            total += len(chunk)
    os.replace(tmp, dst)
    return total


def download_media(project, outdir, kind, progress=None):
    """Bring 'audio' or 'cover' files into the output folder.

    Returns {track key: relative url}.  Files that are already there with the
    right size are left alone, so a second Build is quick.
    """
    say = progress or (lambda m: None)
    url_field = "audio_url" if kind == "audio" else "cover_url"
    name_field = "audio_name" if kind == "audio" else "cover_name"
    subdir = "mp3" if kind == "audio" else "covers"
    default_ext = ".mp3" if kind == "audio" else ".jpg"

    ddir = os.path.join(outdir, subdir)
    os.makedirs(ddir, exist_ok=True)

    wanted = [t for t in project.tracks
              if t.get(url_field) and not t.get("hidden")]
    mapping, failed, done = {}, [], 0
    taken = set()

    # Where each local file came from.  Without it "already here" keeps an
    # old, wrong picture for ever under the same name after a cover was
    # corrected.  A file the list has never heard of is trusted for audio
    # (big, slow) and fetched again for covers (small).
    man_path = os.path.join(ddir, "_sources.json")
    try:
        with open(man_path, "r", encoding="utf-8") as mf:
            manifest = json.load(mf)
        if not isinstance(manifest, dict):
            manifest = {}
    except Exception:
        manifest = {}

    for t in wanted:
        url = t[url_field]
        src_name = t.get(name_field) or ""
        ext = os.path.splitext(src_name)[1].lower() or default_ext
        # the group has to be part of the name: two groups may hold a song
        # with exactly the same title, and one must not overwrite the other
        stem = slugify(("%s %s" % (t.get("group", ""), t.get("title", kind)))
                       if t.get("group") else t.get("title", kind))
        local, n = stem + ext, 2
        while local.lower() in taken:
            local = "%s-%d%s" % (stem, n, ext)
            n += 1
        taken.add(local.lower())
        dst = os.path.join(ddir, local)
        done += 1
        try:
            known = manifest.get(local)
            same = (known == url) if known is not None else (kind == "audio")
            if same and os.path.isabs(url) and os.path.isfile(url):
                same = os.path.getsize(url) == os.path.getsize(dst) \
                    if os.path.isfile(dst) else False
            if same and os.path.isfile(dst) and os.path.getsize(dst) > 0:
                say("[%d/%d] already here: %s" % (done, len(wanted), local))
                manifest[local] = url
            else:
                say("[%d/%d] downloading %s ..." % (done, len(wanted),
                                                    src_name or local))
                size = _download_one(url, dst)
                manifest[local] = url
                say("[%d/%d] %s  (%.1f MB)" % (done, len(wanted), local,
                                               size / 1048576.0))
            mapping[t["key"]] = subdir + "/" + urllib.parse.quote(local)
        except Exception as exc:
            log("%s download failed for %s: %s" % (kind, src_name, exc),
                "WARN")
            failed.append("%s (%s)" % (src_name or t.get("title"), exc))

    try:
        with open(man_path, "w", encoding="utf-8") as mf:
            json.dump(manifest, mf, indent=1, ensure_ascii=False)
    except Exception as exc:
        log_exception("sources list", exc)
    if failed:
        say("  ! %d file(s) could not be fetched:" % len(failed))
        for f in failed[:10]:
            say("      " + f)
    return mapping


def title_sort_key(title):
    """Alphabetical order the way the letter index files titles.

    Digits first (in number order: 8, 42, 161), then A-Z, then Å Ä Ö, then
    other alphabets.  Quotes and brackets in front of a title are skipped,
    case does not matter, and É sorts as E.
    """
    s = unicodedata.normalize("NFC", title or "")
    i = 0
    while i < len(s) and not s[i].isalnum():
        i += 1
    key = []
    for chunk in re.findall(r"\d+|\D", s[i:].casefold()):
        if chunk.isdigit():
            key.append((0, int(chunk)))
        elif chunk in "åäö":
            key.append((2, ord("z") + 1 + "åäö".index(chunk)))
        elif chunk.isalpha():
            base = unicodedata.normalize("NFD", chunk)[0]
            key.append((2, ord(base)) if "a" <= base <= "z"
                       else (3, ord(chunk)))
        else:
            key.append((1, ord(chunk)))
    return key


def page_order(tracks, mode):
    """The tracks in the order the page shows them.  Groups stay in the
    order they first appear; inside a group 'alpha' sorts by title."""
    if mode == "own":
        return list(tracks)
    gorder = {}
    for t in tracks:
        gorder.setdefault(t.get("group", ""), len(gorder))
    return sorted(tracks, key=lambda t: (gorder[t.get("group", "")],
                                         title_sort_key(t.get("title", ""))))


def clean_releases(items):
    """The earlier releases of a track, ready for the page (empty ones out)."""
    out = []
    for r in (items or []):
        if not isinstance(r, dict):
            continue
        row = {"medium": str(r.get("medium", "") or "").strip(),
               "title": str(r.get("title", "") or "").strip(),
               "when": str(r.get("when", "") or "").strip()}
        if any(row.values()):
            out.append(row)
    return out


# *****************************************************************************
# DEL 11b - THE OTHER PAGES  (menu, discography, about me)
# *****************************************************************************
def site_pages(project, index_name):
    """The pages this site has: [(key, menu label, file name)].  The music
    page is always there; the discography needs releases; about me is a
    switch (it may be empty - the page then says it is coming)."""
    site = project.site
    pages = [("music", "Music", index_name)]
    if site.get("show_discography", True) and any(
            not r.get("hidden") for r in project.discography):
        pages.append(("disco", site.get("disco_title") or "Discography",
                      DISCO_FILE))
    if site.get("show_aboutpage", True):
        pages.append(("about", site.get("aboutpage_title") or "About me",
                      ABOUT_FILE))
    return pages


def page_nav_html(pages, current):
    """The small menu at the top of every page ('' when there is only one)."""
    if len(pages) < 2:
        return ""
    return '<nav class="topnav" aria-label="Pages">%s</nav>' % "".join(
        '<a href="%s"%s>%s</a>' % (esc(fname), ' class="on"' if key == current
                                   else "", esc(label))
        for key, label, fname in pages)


def write_page_file(out, page, say=None):
    """Write one page: the old one goes to Backups first (date as suffix),
    and the new one is written to a temp file and swapped in, so a build
    that dies half-way cannot leave half a page."""
    say = say or (lambda m: None)
    if os.path.isfile(out):
        try:
            say("Backup of the old %s: %s"
                % (os.path.basename(out), make_backup(out)))
        except Exception as exc:
            log_exception("page backup", exc)
    tmp_out = out + ".tmp"
    with open(tmp_out, "w", encoding="utf-8", newline="\n") as f:
        f.write(page)
    os.replace(tmp_out, out)


def _subpage(project, pages, current, title, lead_html, body_html, shell):
    site = project.site
    accent = site.get("accent", "#e8663a")
    meta = re.sub(r"\s+", " ", "%s - %s" % (title, shell.get("meta", ""))
                  ).strip()[:180]
    full_title = "%s - %s" % (title, site.get("site_title", "My Music"))
    page = SUBPAGE_TEMPLATE
    repl = {
        "@@THEME@@": esc(site.get("theme", "auto")),
        "@@TITLE@@": esc(full_title),
        "@@META@@": esc(meta),
        "@@ACCENT@@": accent,
        "@@ACCENT_ENC@@": urllib.parse.quote(accent, safe=""),
        "@@NAV_HTML@@": page_nav_html(pages, current),
        "@@H1@@": esc(title),
        "@@LEAD_HTML@@": lead_html,
        "@@BODY_HTML@@": body_html,
        "@@LINKS_HTML@@": shell.get("links", ""),
        "@@FOOTER_HTML@@": shell.get("footer", ""),
        "@@MADE_HTML@@": shell.get("made", ""),
    }
    for k, v in repl.items():
        page = page.replace(k, v)
    return page


def song_credit_text(title, track_index, tracks, credit_index):
    """What the page says about WHO is on one song of a release:
    'Words: Malin Östh · guitar: Mikael Swahn'.

    It works backwards from the credits (and the "Lyrics by" of the song on
    the music page): a name is printed on every release song it was given
    for, also those that are not on the music page - the credits file is
    searched by the title.  '' when nobody is credited.
    """
    words, other = [], []
    if track_index is not None:
        t = tracks[track_index]
        if t.get("lyrics_by"):
            words.append(t["lyrics_by"])
        other = ["%s: %s" % (c["role"], c["name"]) if c["role"] else c["name"]
                 for c in credit_objs(t)]
    elif credit_index:
        entry, _how = find_lyrics(credit_index, title)
        for c in (entry or {}).get("credits", []):
            if c.get("role", "").casefold() in LYRICS_ROLES:
                words.append(c["name"])
            else:
                other.append("%s: %s" % (c["role"], c["name"])
                             if c.get("role") else c["name"])
    parts = (["Words: " + ", ".join(words)] if words else []) + other
    return " · ".join(parts)


def release_credits_html(release):
    """The box of musicians / guests on a release.  A line that starts with
    *, *1 ... belongs to the songs marked the same way; the others are for
    the whole release."""
    general, marked = [], []
    for line in (release.get("credits") or "").splitlines():
        marks, text = split_credit_marks(line)
        if not text:
            continue
        if marks:
            marked.append('<li><span class="mk">%s</span> %s</li>'
                          % (esc(" ".join(marks)), esc(text)))
        else:
            general.append("<li>%s</li>" % esc(text))
    if not (general or marked):
        return ""
    return ('<div class="cred"><h3>Musicians &amp; credits</h3><ul>%s</ul></div>'
            % "".join(general + marked))


def discography_page_html(project, pages, link_of, slug_of, index_name, shell):
    """discography.html: one card per release, anchor #r<number>."""
    site = project.site
    # a hidden release is left out but keeps its number (#14 stays #14)
    shown = [(i, r) for i, r in enumerate(project.discography)
             if not r.get("hidden")]
    total = sum(disco_song_count(r) for _i, r in shown)
    cidx = shell.get("credit_index") or {}
    lead = para_html(site.get("disco_intro", ""))
    if lead:
        lead = '<div class="lead">%s</div>' % lead
    count_line = ('<p class="note">%d releases, %d songs in all.</p>'
                  % (len(shown), total))

    jump = '<nav class="jump" aria-label="Releases">%s</nav>' % "".join(
        '<a href="#r%d" title="%s">#%d</a>' % (i + 1, esc(release_label(r)),
                                              i + 1)
        for i, r in shown)

    cards = []
    for ri, r in shown:
        sub = " &middot; ".join(esc(x) for x in
                                (r.get("group"), r.get("format"),
                                 r.get("year")) if x)
        facts = []
        for lab, val in (("Recorded", r.get("dates")),
                         ("Where", r.get("where")),
                         ("Released", r.get("released")),
                         ("Copies", r.get("copies")),
                         ("Songs", str(disco_song_count(r) or ""))):
            if val:
                facts.append("<dt>%s</dt><dd>%s</dd>" % (lab, esc(val)))
        items = []
        for entry in disco_layout(r):
            if entry[0] == "side":
                items.append('<li class="side">%s</li>' % esc(entry[1]))
                continue
            if entry[0] == "gap":
                items.append('<li class="gap" aria-hidden="true"></li>')
                continue
            _, n, title, li, marks = entry
            tix = link_of.get((ri, li))
            slug = slug_of.get(tix) if tix is not None else None
            label = ('<a href="%s#%s" title="Listen on the music page">%s</a>'
                     % (esc(index_name), esc(slug), esc(title))) \
                if slug else esc(title)
            if marks:
                label += '<sup class="mk">%s</sup>' % esc(" ".join(marks))
            by = song_credit_text(title, tix, project.tracks, cidx)
            if by:
                label += '<span class="by">%s</span>' % esc(by)
            items.append('<li><span class="n">%d</span>%s</li>' % (n, label))
        note = ('<p class="note">%s</p>' % esc(r["note"]).replace("\n", "<br>")
                ) if r.get("note") else ""
        cards.append(
            '<article class="release" id="r%d">'
            '<div class="top"><div class="no">#%d</div>'
            '<div><h2>%s</h2>%s</div></div>'
            '%s%s%s'
            '<details class="tl" open><summary>Tracklist (%d)</summary>'
            '<ul class="tracks">%s</ul></details>'
            '</article>'
            % (ri + 1, ri + 1, esc(r.get("title") or "(no title)"),
               '<div class="sub">%s</div>' % sub if sub else "",
               '<dl class="facts">%s</dl>' % "".join(facts) if facts else "",
               release_credits_html(r), note, disco_song_count(r),
               "".join(items)))

    body = count_line + jump + "".join(cards)
    return _subpage(project, pages, "disco",
                    site.get("disco_title") or "Discography", lead, body,
                    shell)


def about_page_html(project, pages, shell):
    """about.html: his title, text and picture - or a 'coming soon' line."""
    site = project.site
    text = para_html(site.get("aboutpage_text", ""))
    img = site.get("aboutpage_image", "").strip()
    body = '<div class="aboutbody">%s%s</div>' % (
        '<img src="%s" alt="">' % esc(img) if img else "",
        text or '<p class="soon">This page is coming soon.</p>')
    return _subpage(project, pages, "about",
                    site.get("aboutpage_title") or "About me", "", body,
                    shell)


def build_site(project, progress=None):
    """Write index.html (and discography.html / about.html next to it).
    Returns the full path of the music page."""
    say = progress or (lambda m: None)
    site = project.site
    outdir = project.output_dir or OUT_DIR_DEFAULT
    os.makedirs(outdir, exist_ok=True)

    def _is_disk_path(url):
        return bool(url) and not re.match(r"^https?://", url)

    # Files that live on this PC have to be copied - a web page cannot link
    # to C:\... - so a local source switches these on by itself.
    want_cover_local = site.get("cover_mode") == "local"
    want_audio_local = site.get("audio_mode") == "local"
    if not want_audio_local and any(_is_disk_path(t.get("audio_url"))
                                    for t in project.tracks
                                    if not t.get("hidden")):
        want_audio_local = True
        say("The audio is on this PC, so it is copied into the output "
            "folder (a web page cannot link to a disk path).")
    if not want_cover_local and any(_is_disk_path(t.get("cover_url"))
                                    for t in project.tracks
                                    if t.get("cover_url")
                                    and not t.get("hidden")):
        want_cover_local = True
        say("The covers are on this PC, so they are copied into the output "
            "folder.")

    cover_map, audio_map = {}, {}
    if want_cover_local:
        say("--- covers ---")
        cover_map = download_media(project, outdir, "cover", say)
    if want_audio_local:
        say("--- audio (this is the slow part) ---")
        audio_map = download_media(project, outdir, "audio", say)

    # Will the finished page be allowed to PLAY the sound?  Downloading is a
    # different question: a link click is a navigation, and hosts that refuse
    # to be embedded (Google Drive) still serve those perfectly well.
    warning = ""
    mode = site.get("player_mode", "auto")
    download_only = (mode == "download")

    if mode in ("auto", "player") and not audio_map:
        first = next((t.get("audio_url") for t in project.tracks
                      if t.get("audio_url") and not t.get("hidden")), "")
        if first and re.match(r"^https?://", first):
            say("Checking whether the host lets a web page play the audio...")
            ok, detail = probe_embeddable(first, "audio")
            say("  playing:     %s  (%s)"
                % ("allowed" if ok else "REFUSED", detail))
            if not ok:
                log("Hotlink check failed: %s" % detail, "WARN")
                if mode == "auto":
                    download_only = True
                    say("  downloading: allowed - building a DOWNLOAD page "
                        "instead of a player.")
                else:
                    warning = HOTLINK_WARNING

    if download_only:
        say("Page style: download page (no player).")

    fname = site.get("page_filename") or "index.html"
    if not fname.lower().endswith((".html", ".htm")):
        fname += ".html"
    pages = site_pages(project, fname)
    has_disco = any(p[0] == "disco" for p in pages)

    # Which song was on which release - found by the titles, like lyrics and
    # covers find their songs.
    rel_of, link_of = {}, {}
    if has_disco:
        rel_of, link_of, how = match_discography(project.discography,
                                                 project.tracks)
        nhid = sum(1 for r in project.discography if r.get("hidden"))
        say("Discography: %d release(s)%s, %d song(s) on the page have a "
            "release number." % (len(project.discography) - nhid,
                                 " (%d hidden)" % nhid if nhid else "",
                                 len(rel_of)))
        for kind, num, line, title in how:
            say("   #%d  \"%s\"  =  \"%s\"  (%s)" % (num, line, title, kind))
    index_of = {id(t): i for i, t in enumerate(project.tracks)}
    slug_of = {}                              # track index -> its #slug

    # Backup sources: only those that hold at least one song of the page, and only web addresses (a disk path is no use to a visitor)
    def _alt_of(t):
        out = {}
        for bid, a in (t.get("alt") or {}).items():
            a = {k: v for k, v in (a or {}).items() if k in ("audio", "cover") and re.match(r"^https?://", str(v or ""))}
            if a.get("audio"):
                out[bid] = a
        return out
    backups = parse_backups(project.source.get("backups", ""))
    live = [b for b in backups
            if any(b["id"] in _alt_of(t) for t in project.tracks if not t.get("hidden"))]
    for b in backups:
        n = sum(1 for t in project.tracks if not t.get("hidden") and b["id"] in _alt_of(t))
        total = sum(1 for t in project.tracks if not t.get("hidden"))
        say("Backup source '%s': %d of %d song(s) have a file there%s" % (
            b["name"], n, total, "" if n else " - left out of the page (press Fetch to look again)"))

    say("Assembling the page...")
    used_slugs = set()
    data = []
    for t in page_order(project.tracks, site.get("sort_mode", "alpha")):
        if t.get("hidden"):
            continue
        slug = slugify(t.get("title") or t.get("key") or "track")
        base_slug, n = slug, 2
        while slug in used_slugs:
            slug = "%s-%d" % (base_slug, n)
            n += 1
        used_slugs.add(slug)
        if t.get("audio_url") or audio_map.get(t.get("key", "")):
            slug_of[index_of[id(t)]] = slug   # only songs with a row to link to
        data.append({
            "rel": rel_of.get(index_of[id(t)], []),
            "slug": slug,
            "group": t.get("group", ""),
            "title": t.get("title", ""),
            "artist": t.get("artist", ""),
            "year": str(t.get("year", "") or ""),
            "made": str(t.get("made", "") or "").strip(),
            "about": str(t.get("about_person", "") or "").strip(),
            "released": clean_releases(t.get("released")),
            "description": t.get("description", ""),
            "words_by": t.get("lyrics_by", ""),
            "credits": credit_objs(t),
            "lyrics": t.get("lyrics", "") if site.get("show_lyrics") else "",
            "audio": audio_map.get(t.get("key", ""), t.get("audio_url", "")),
            "cover": cover_map.get(t.get("key", ""), t.get("cover_url", "")),
            "hidden": False,
        })
        if live:
            alt = {k: v for k, v in _alt_of(t).items() if k in {b["id"] for b in live}}
            if alt:
                data[-1]["alt"] = alt

    options = {
        "site_title": site.get("site_title", "My Music"),
        "artist": site.get("artist", ""),
        "accent": site.get("accent", "#e8663a"),
        "downloads": bool(site.get("show_downloads", True)) or download_only,
        "lyrics": bool(site.get("show_lyrics", True)),
        "autonext": bool(site.get("autoplay_next", True)),
        "downloadOnly": download_only,
        "sources": ["main"] + [b["id"] for b in live] if live else [],
        "discoUrl": DISCO_FILE if has_disco else "",
        "rels": ({str(i + 1): release_label(r)
                  for i, r in enumerate(project.discography)
                  if not r.get("hidden")}
                 if has_disco else {}),
    }

    accent = site.get("accent", "#e8663a")
    meta = site.get("tagline") or site.get("about") or site.get("site_title")
    meta = re.sub(r"\s+", " ", meta).strip()[:180]

    artist_html = ('<p class="artist">%s</p>' % esc(site["artist"])) \
        if site.get("artist") else ""
    tagline_html = ('<p class="tagline">%s</p>' % esc(site["tagline"])) \
        if site.get("tagline") else ""
    about_html = ('<div class="about">%s</div>' % para_html(site["about"])) \
        if site.get("about") else ""

    search_html = ('<input type="search" id="search" '
                   'placeholder="Search titles, words, years&hellip;">') \
        if site.get("show_search", True) else ""
    shuffle_html = ('<button class="btn" id="shuf" aria-pressed="false" '
                    'title="Shuffle">&#128256; Shuffle</button>') \
        if site.get("show_shuffle", True) and not download_only else ""

    links = site.get("links") or []
    if links:
        parts = []
        for lk in links:
            if lk.get("url"):
                parts.append('<a href="%s" target="_blank" rel="noopener">%s</a>'
                             % (esc(lk["url"]), esc(lk.get("label")
                                                    or lk["url"])))
        links_html = '<div class="links">%s</div>' % "".join(parts)
    else:
        links_html = ""
    footer_html = ('<div>%s</div>' % para_html(site["footer_text"])) \
        if site.get("footer_text") else ""
    made_html = ('<div class="made">Built with %s &middot; %s</div>'
                 % (APP_NAME, datetime.now().strftime("%Y-%m-%d"))) \
        if site.get("show_made", True) else ""

    # The box at the bottom: his own words, and the ways to pay if somebody
    # wants to.  Text and links both come from the Site tab - the program
    # holds no opinion about either.
    support_html = ""
    if site.get("show_support", True) and (site.get("support_text")
                                           or site.get("support_links")):
        pay = []
        for lk in (site.get("support_links") or []):
            if lk.get("url"):
                pay.append('<a href="%s" target="_blank" rel="noopener">%s</a>'
                           % (esc(lk["url"]),
                              esc(lk.get("label") or lk["url"])))
        support_html = (
            '<section class="support">%s%s%s</section>'
            % ('<h2>%s</h2>' % esc(site["support_title"])
               if site.get("support_title") else "",
               para_html(site.get("support_text", "")),
               '<div class="paylinks">%s</div>' % "".join(pay) if pay else ""))

    source_html = ""
    if live:                                   # the switch between the original and the backup source(s)
        source_html = ('<div class="chips srcbar" id="srcbar"><span class="srcl">Download from</span>%s'
                       '<span class="srch">Not playing, or the download fails?  Try another source.</span></div>'
                       % "".join('<button type="button" class="chip" data-s="%s">%s</button>' % (esc(i), esc(n))
                                 for i, n in [("main", "Original")] + [(b["id"], b["name"]) for b in live]))

    page = PAGE_TEMPLATE
    repl = {
        "@@SOURCE_HTML@@": source_html,
        "@@THEME@@": esc(site.get("theme", "auto")),
        "@@TITLE@@": esc(site.get("site_title", "My Music")),
        "@@H1@@": esc(site.get("site_title", "My Music")),
        "@@META@@": esc(meta),
        "@@ACCENT@@": accent,
        "@@ACCENT_ENC@@": urllib.parse.quote(accent, safe=""),
        "@@ARTIST_HTML@@": artist_html,
        "@@TAGLINE_HTML@@": tagline_html,
        "@@ABOUT_HTML@@": about_html,
        "@@NAV_HTML@@": page_nav_html(pages, "music"),
        "@@SEARCH_HTML@@": search_html,
        "@@SHUFFLE_HTML@@": shuffle_html,
        "@@LINKS_HTML@@": links_html,
        "@@FOOTER_HTML@@": footer_html,
        "@@SUPPORT_HTML@@": support_html,
        "@@APP_HTML@@": app_box_html(site),
        "@@MADE_HTML@@": made_html,
        "@@DATA@@": json.dumps(data, ensure_ascii=False)
                        .replace("</", "<\\/"),
        "@@OPTIONS@@": json.dumps(options, ensure_ascii=False)
                           .replace("</", "<\\/"),
    }
    for k, v in repl.items():
        page = page.replace(k, v)

    out = os.path.join(outdir, fname)
    write_page_file(out, page, say)
    log("Built %s (%d tracks, %d bytes)" % (out, len(data),
                                            os.path.getsize(out)))

    # the other pages, in the same folder
    credit_index = {}
    if has_disco:
        credit_index, _rep = build_credits_index(
            project.source.get("credits_file", ""))
    shell = {"links": links_html, "footer": footer_html, "made": made_html,
             "meta": meta, "credit_index": credit_index}
    project.last_pages = [out]
    for key, label, pname in pages:
        if key == "music":
            continue
        if key == "disco":
            html_text = discography_page_html(project, pages, link_of,
                                              slug_of, fname, shell)
        else:
            html_text = about_page_html(project, pages, shell)
        pout = os.path.join(outdir, pname)
        write_page_file(pout, html_text, say)
        project.last_pages.append(pout)
        say("Wrote %s" % pout)

    project.last_warning = warning        # picked up by the Build tab
    return out


# *****************************************************************************
# DEL 12 - SETTINGS  (remember everything, including window size)
# *****************************************************************************
DEFAULT_SETTINGS = {
    "geometry": "1180x760",
    "last_project": "",
    "last_output": OUT_DIR_DEFAULT,
    "last_stage": STAGE_DIR_DEFAULT,
    "sash": 470,
}


def load_settings():
    s = dict(DEFAULT_SETTINGS)
    try:
        with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
            s.update(json.load(f))
    except Exception:
        pass
    return s


def save_settings(s):
    try:
        tmp = SETTINGS_FILE + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(s, f, indent=2, ensure_ascii=False)
        os.replace(tmp, SETTINGS_FILE)
    except Exception as exc:
        log_exception("save_settings", exc)


# *****************************************************************************
# DEL 12C - SEND THE FINISHED PAGES TO THE SERVERS  (v1.15.0)
# *****************************************************************************
# Only the SMALL files go: index.html, discography.html, about.html, covers\ if the page uses them (never the mp3 folder, and
# nothing bigger than SRV_MAX_FILE).  The songs themselves stay on Google Drive.  One place (HTG, the old FTP server, was dropped
# 2026-11-14):
#
#   Webdock (my own VPS)   <AppSite upd_remote>/p/<name>/   through ssh/scp with the key AppSite already uses.  Nothing about the
#                          server is written in this program: host, key and folder are READ from Helpfiles\AppSite\settings.json
#                          (never written).  Test address:  <upd_url>/p/<name>/ ; the public names (issu. / loss.issusbarn.se) are
#                          nginx names on the same folder (WebdockTool > Web sites sets that up).
#
# One profile can never overwrite the other: every server folder gets a marker file (.musicsite_profile = the profile).  A folder
# that belongs to another profile is refused; a folder that has files but no marker (e.g. the page Lars uploaded by hand) is only
# taken over after he says yes.  The webdock folder is replaced as a WHOLE (new folder unpacked beside it, then swapped), so a visitor
# never sees half a page.
# A second server (a backup Webdock) later: srv_servers() returns the list of servers; today it holds the one from AppSite's settings.
import tarfile
import tempfile

SRV_MARKER = ".musicsite_profile"
SRV_MAX_FILE = 8 * 1024 * 1024
SRV_SKIP_DIRS = {"mp3"}
SRV_RESERVED = {"railmaps", "railmaps-files", "android", "pc", "apps", "programs", "updates", "f", "p"}
SRV_PATH_OK = re.compile(r"^/[A-Za-z0-9_./-]+$")


class ServerError(Exception):
    """Anything that stops a send, with a message fit to show Lars."""


class NeedConfirm(ServerError):
    """The server folder has files but no marker: ask Lars before taking it over."""


def srv_profile_id() -> str:
    return (PROFILE or "music").lower()


def srv_clean_name(name: str) -> str:
    """The folder name on the server ('' = not usable)."""
    n = (name or "").strip().lower()
    return n if re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,30}", n) and n not in SRV_RESERVED else ""


def srv_default_folder_name() -> str:
    return srv_clean_name(srv_profile_id()) or "music"


def srv_collect(outdir: str):
    """([(relative path with /, full path, size)], [(relative path, why)]) of what may be sent from the output folder."""
    files, skipped = [], []
    for dp, dns, fns in os.walk(outdir):
        keep = []
        for d in sorted(dns):
            if d.startswith(".") or d.lower() in SRV_SKIP_DIRS:
                skipped.append((os.path.relpath(os.path.join(dp, d), outdir).replace("\\", "/") + "/", "not sent (fat files stay on Drive)"
                                if d.lower() in SRV_SKIP_DIRS else "hidden folder"))
            else:
                keep.append(d)
        dns[:] = keep
        for fn in sorted(fns):
            full = os.path.join(dp, fn)
            rel = os.path.relpath(full, outdir).replace("\\", "/")
            low = fn.lower()
            if fn.startswith(".") or low.endswith((".tmp", ".bak", ".new", ".part")) or low == "desktop.ini" or low == "thumbs.db":
                continue
            try:
                size = os.path.getsize(full)
            except OSError:
                continue
            if size > SRV_MAX_FILE:
                skipped.append((rel, "bigger than %d MB" % (SRV_MAX_FILE // (1024 * 1024))))
                continue
            files.append((rel, full, size))
    return files, skipped


def foreign_profile_dir(path: str) -> str:
    """The name of ANOTHER profile whose Helpfiles folder `path` is inside ('' = fine).  Stops a project copied from
    one profile from building into the other profile's Site folder."""
    if not path:
        return ""
    p = os.path.normcase(os.path.normpath(os.path.abspath(path)))
    mine = os.path.normcase(os.path.normpath(HELP_DIR))
    try:
        names = os.listdir(HELP_ROOT)
    except OSError:
        return ""
    for n in names:
        if n.lower() == "musicsite" or n.lower().startswith("musicsite_"):
            other = os.path.normcase(os.path.normpath(os.path.join(HELP_ROOT, n)))
            if other != mine and (p == other or p.startswith(other + os.sep)):
                return n
    return ""


def list_profiles():
    """[(name, note)] of the profiles that can be opened: every Helpfiles\\MusicSite_<name> folder, plus 'Issu' as a suggestion
    while only the old Helpfiles\\MusicSite folder exists (starting it copies that folder)."""
    found = {}
    try:
        for n in os.listdir(HELP_ROOT):
            if n.lower().startswith(PROFILE_PREFIX.lower()) and os.path.isdir(os.path.join(HELP_ROOT, n)):
                p = _clean_profile(n[len(PROFILE_PREFIX):])
                if p:
                    found[p.lower()] = (p, "")
    except OSError:
        pass
    if "issu" not in found and os.path.isdir(LEGACY_HELP_DIR) and PROFILE.lower() != "issu":
        found["issu"] = ("Issu", "copies the old MusicSite data")
    return sorted(found.values(), key=lambda t: t[0].lower())


def launch_profile(name: str) -> str:
    """Open `name` in a NEW window of this same program (python or exe, by full path).  '' = started, else the reason."""
    name = _clean_profile(name)
    if not name:
        return "A profile name may only hold letters, digits, - and _ (up to 31 characters, starting with a letter or digit)."
    try:
        if getattr(sys, "frozen", False):
            cmd = [sys.executable, "--profile", name]
            here = os.path.dirname(os.path.abspath(sys.executable))
        else:
            exe = sys.executable
            w = os.path.join(os.path.dirname(exe), "pythonw.exe")      # no console window
            if os.path.basename(exe).lower() == "python.exe" and os.path.isfile(w):
                exe = w
            cmd = [exe, os.path.abspath(__file__), "--profile", name]
            here = os.path.dirname(os.path.abspath(__file__))
        subprocess.Popen(cmd, cwd=here, creationflags=(0x00000008 | 0x00000200) if os.name == "nt" else 0, close_fds=True)
        return ""
    except Exception as exc:
        log_exception("launch_profile", exc)
        return "Could not start the other window: %s" % exc


# ---- the Webdock side ---------------------------------------------------------------------------------------------------
def srv_appsite_config() -> dict:
    path = os.path.join(HELP_ROOT, "AppSite", "settings.json")
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
    except Exception as exc:
        raise ServerError("The Webdock settings could not be read from AppSite's settings file:\n\n    %s\n\nOpen AppSite, go to the "
                          "Updates tab and set the server up there first.\n\n(%s)" % (path, exc))
    cfg = {"host": str(data.get("upd_host", "")).strip(), "port": str(data.get("upd_port", "") or 22).strip(),
           "user": str(data.get("upd_user", "")).strip(), "key": str(data.get("upd_key", "")).strip(),
           "remote": str(data.get("upd_remote", "")).strip().rstrip("/"), "url": str(data.get("upd_url", "")).strip().rstrip("/")}
    missing = [k for k in ("host", "user", "key", "remote") if not cfg[k]]
    if missing:
        raise ServerError("AppSite's Updates settings are not complete (missing: %s).\n\nOpen AppSite > Updates and fill them in." % ", ".join(missing))
    if not re.fullmatch(r"[0-9]{1,5}", cfg["port"]):
        raise ServerError("The server port in AppSite's Updates settings is not a number.")
    if not SRV_PATH_OK.match(cfg["remote"]):
        raise ServerError("The server folder in AppSite's Updates settings has odd characters: %s" % cfg["remote"])
    if not os.path.isfile(cfg["key"]):
        raise ServerError("The server key file was not found:\n\n    %s\n\nCheck the key path in AppSite > Updates." % cfg["key"])
    return cfg


def _srv_exe(name: str) -> str:
    """ssh / scp by full path (rule: never start a system program by bare name)."""
    cand = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "OpenSSH", name + ".exe")
    if os.path.isfile(cand):
        return cand
    found = shutil.which(name)
    if found:
        return found
    raise ServerError("%s.exe was not found. Windows' OpenSSH client is needed (Settings > Optional features)." % name)


def _srv_opts(cfg: dict, port_flag: str) -> list:
    return ["-i", cfg["key"], "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new",
            "-o", "ConnectTimeout=15", port_flag, cfg["port"]]


def _srv_run(cmd: list, stdin=None, timeout: int = 180):
    try:
        r = subprocess.run(cmd, input=stdin, capture_output=True, timeout=timeout,
                           creationflags=0x08000000 if os.name == "nt" else 0)
        return r.returncode, r.stdout.decode("utf-8", "replace"), r.stderr.decode("utf-8", "replace")
    except subprocess.TimeoutExpired:
        return 255, "", "timed out"
    except (OSError, subprocess.SubprocessError) as exc:
        return 255, "", str(exc)


def _srv_sh(cfg: dict, script: str, timeout: int = 180):
    """Run a small sh script on the server: it goes in on stdin, so no quoting trouble."""
    return _srv_run([_srv_exe("ssh")] + _srv_opts(cfg, "-p") + ["%s@%s" % (cfg["user"], cfg["host"]), "sh -s"],
                    script.encode("utf-8"), timeout)


def _srv_scp(cfg: dict, local: str, remote: str, timeout: int = 600):
    return _srv_run([_srv_exe("scp")] + _srv_opts(cfg, "-P") + [local, "%s@%s:%s" % (cfg["user"], cfg["host"], remote)], None, timeout)


def _srv_problem(what: str, rc: int, err: str) -> ServerError:
    e = (err or "").strip()
    low = e.lower()
    hint = ""
    if "permission denied (publickey" in low or "authentication failed" in low:
        hint = "\n\nThe server refused the key. Is it the right key file in AppSite > Updates?"
    elif "timed out" in low or "no route" in low or "could not resolve" in low or "connection" in low:
        hint = "\n\nThe server could not be reached. Is the internet up?"
    return ServerError("%s failed (code %d).\n\n%s%s" % (what, rc, e[:600] or "(no message)", hint))


def srv_servers() -> list:
    """[(label, cfg)] of every server a page is sent to.  Today: the ONE Webdock from AppSite's Updates settings.  A second
    (backup) Webdock later = one more entry here (its own host / key / folder); nothing else in this program changes."""
    return [("Webdock", srv_appsite_config())]


def send_webdock(files, name: str, say, adopt: bool = False, dry: bool = False, cfg: dict = None, label: str = "Webdock") -> dict:
    """Replace <remote>/p/<name>/ on a Webdock server by `files`.  Returns {'where', 'url', 'count', 'bytes'}."""
    name = srv_clean_name(name)
    if not name:
        raise ServerError("The Webdock folder name is empty or not allowed.  Use Servers... to set one (letters, digits, - and _).")
    if not files:
        raise ServerError("There is nothing to send - build the page first.")
    cfg = cfg or srv_appsite_config()
    root = cfg["remote"] + "/p"
    d = root + "/" + name
    me = srv_profile_id()
    rc, out, err = _srv_sh(cfg, 'd=%s\nif [ -f "$d/%s" ]; then cat "$d/%s"; elif [ -n "$(ls -A "$d" 2>/dev/null)" ]; then echo "?FOREIGN"; '
                                'else echo "?EMPTY"; fi\n' % (d, SRV_MARKER, SRV_MARKER), 60)
    if rc != 0:
        raise _srv_problem("Looking at the Webdock folder", rc, err)
    owner = (out.strip().splitlines() or ["?EMPTY"])[0].strip()
    if owner not in ("?EMPTY", "?FOREIGN", me):
        raise ServerError("The Webdock folder '%s' belongs to another profile ('%s'), not to this one ('%s').\n\nNothing was sent.  "
                          "Use Servers... to give this profile its own folder name." % (name, owner, me))
    if owner == "?FOREIGN" and not adopt:
        raise NeedConfirm("The Webdock folder '%s' already holds files that this program did not put there.\n\nTake it over "
                          "(its files are replaced)?" % name)
    total = sum(s for _, _, s in files)
    url = (cfg["url"] + "/p/" + name + "/") if cfg["url"] else ""
    res = {"where": label, "url": url, "count": len(files), "bytes": total}
    if dry:
        return res
    stage = os.path.join(tempfile.gettempdir(), "musicsite_%s_%d.tgz" % (name, os.getpid()))
    try:
        with tarfile.open(stage, "w:gz") as t:
            for rel, full, _ in files:
                t.add(full, arcname=rel, recursive=False)
            mk = tarfile.TarInfo(SRV_MARKER)
            data = (me + "\n").encode("ascii")
            mk.size = len(data)
            mk.mtime = int(time.time())
            t.addfile(mk, io.BytesIO(data))
        say("   sending %d file(s), %.0f KB, to %s ..." % (len(files), total / 1024.0, label))
        rc, out, err = _srv_sh(cfg, "set -e\nmkdir -p %s\nchmod 755 %s\n" % (root, root), 60)
        if rc != 0:
            raise _srv_problem("Making the Webdock folder", rc, err)
        rc, out, err = _srv_scp(cfg, stage, d + ".tgz")
        if rc != 0:
            raise _srv_problem("Copying to Webdock", rc, err)
    finally:
        try:
            os.remove(stage)
        except OSError:
            pass
    swap = ("set -e\nd=%s\nrm -rf \"$d.new\"\nmkdir -p \"$d.new\"\ntar -xzf \"$d.tgz\" -C \"$d.new\"\nrm -f \"$d.tgz\"\n"
            "chmod -R a+rX \"$d.new\"\nchmod 755 \"$d.new\"\nif [ -d \"$d\" ]; then rm -rf \"$d.old\"; mv \"$d\" \"$d.old\"; fi\n"
            "mv \"$d.new\" \"$d\"\nrm -rf \"$d.old\"\n" % d)
    rc, out, err = _srv_sh(cfg, swap, 120)
    if rc != 0:
        raise _srv_problem("Unpacking on Webdock", rc, err)
    return res


# *****************************************************************************
# DEL 12D - UPDATE EVERYTHING  (v1.16.0: Fetch -> Save -> Build -> Send, no window needed)
# *****************************************************************************
# One function does the whole round for ONE profile, so nothing can be forgotten or done in the wrong order:
#   1. Fetch   read the cloud folder again (new / changed songs), keep what he typed  (scan_source, the same as the Fetch button)
#   2. Save    the project file (the old one is copied to Backups first by Project.save)
#   3. Build   the pages  (build_site, the same as the Build button)
#   4. Send    the small files to every server of srv_servers()
# A red problem stops the round at that step (nothing is sent on after a failed build).  The window button "Update everything" (F11)
# runs it on the open project; headless_update() runs it from the saved project of the profile (AppSite's DO EVERYTHING button
# loads this file as a module and calls it for every profile).  `adopt` stays False here: a server folder that holds files this
# program did not put there is only taken over when he presses Send himself and says yes.
def update_pipeline(project, settings, say, adopt=False, fetch=True):
    """Runs the round on `project` (a Project).  Returns (ok, summary text, results list).  say(text) gets progress lines."""
    results = []
    bad = foreign_profile_dir(project.output_dir or OUT_DIR_DEFAULT)
    if bad:
        return False, "The output folder belongs to another profile (%s): %s" % (bad, project.output_dir), results
    if fetch:
        cfg = dict(project.source)
        if not (cfg.get("address") or "").strip():
            return False, "The project has no cloud folder address (Source tab).", results
        say("1. Fetch - reading the source ...")
        res = scan_source(cfg, [dict(t) for t in project.tracks], lambda m: None)
        if res.error:
            return False, "Fetch found nothing: %s" % res.error, results
        for line in res.report:
            if line.startswith("Gone from the source") or line.startswith("Title of "):
                say("   note: " + line)
        part = [l for l in res.report if l.startswith("!!")]
        if part:                      # one cloud folder failed: a page built from the rest would silently lose songs
            return False, "Fetch could not read every folder (%s) - nothing was changed, built or sent." % part[0].lstrip("! ").split(" - see")[0], results
        project.tracks = res.tracks
        if res.cover_files:
            project.cover_files = res.cover_files
        say("   %d track(s)" % len(res.tracks))
        if project.path:
            project.save()
            say("2. Saved the project (%s)" % os.path.basename(project.path))
    if not project.tracks:
        return False, "There are no tracks - nothing to build.", results
    say("3. Build ...")
    out = build_site(project, lambda m: None)
    say("   built %s" % os.path.basename(out))
    if not (settings.get("srv_webdock", True)):
        return True, "Built (sending is switched off: the Webdock tick on the Build tab).", results
    outdir = project.output_dir or OUT_DIR_DEFAULT
    files, skipped = srv_collect(outdir)
    for rel, why in skipped:
        say("   not sent: %s (%s)" % (rel, why))
    name = settings.get("srv_name") or srv_default_folder_name()
    say("4. Send to the server(s) ...")
    problems = []
    for label, cfg in srv_servers():
        try:
            results.append(send_webdock(files, name, say, adopt=adopt, cfg=cfg, label=label))
        except NeedConfirm as exc:
            problems.append("%s: %s  -> open %s and press 'Send to servers' once to take the folder over." % (
                label, str(exc).splitlines()[0], PROFILE_TITLE or "MusicSite"))
        except ServerError as exc:
            problems.append("%s: %s" % (label, str(exc).splitlines()[0]))
    for res in results:
        say("   SENT to %s: %d file(s), %.0f KB   %s" % (res["where"], res["count"], res["bytes"] / 1024.0, res.get("url", "")))
    if problems:
        return False, "; ".join(problems), results
    return True, "Updated %s: %d track(s), %d file(s) sent." % (PROFILE_TITLE or "MusicSite", len(project.tracks), len(files)), results


def headless_update(say, adopt=False, fetch=True):
    """The whole round for THIS profile from its saved project (settings: last_project).  No window.  Returns (ok, summary)."""
    settings = load_settings()
    path = settings.get("last_project") or ""
    if not path or not os.path.isfile(path):
        return False, "No project is open in %s: start it once, open or save a project, then it can run by itself." % (PROFILE_TITLE or "MusicSite")
    project = Project()
    try:
        project.load(path)
    except Exception as exc:
        log_exception("headless_update load", exc)
        return False, "The project could not be read: %s" % exc
    try:
        ok, text, _res = update_pipeline(project, settings, say, adopt=adopt, fetch=fetch)
    except Exception as exc:
        log_exception("headless_update", exc)
        return False, "Crashed: %s" % exc
    log("headless update (%s): %s %s" % (PROFILE or "none", "OK" if ok else "FAILED", text))
    return ok, text


# *****************************************************************************
# DEL 13 - HELP TEXT  (hard-coded, English only)
# *****************************************************************************
HELP_TEXT = """MusicSite - what it is and how to use it
=========================================================================

THE IDEA
-------------------------------------------------------------------------
You keep the actual music files in ONE shared folder in the cloud.
Inside that main folder you make sub-folders:

    <main folder>/MP3/      Dagen_utan_morgon.mp3
    <main folder>/Cover/    Dagen_utan_morgon.jpg
    <main folder>/Text/     Dagen_utan_morgon.txt      (optional)

MusicSite reads the main folder, pairs the files up BY NAME, and writes a
single self-contained web page with a real player in it.  You upload that
one file to your own web server.

You never handle individual share links.  The only address you ever type
is the address of the MAIN folder.

If you move to a different host later: copy the MP3 / Cover / Text folders
there, paste the new main address, press Fetch, press Build, upload the new
index.html.  Everything else stays exactly as you set it up.


TAB 1 - SOURCE
-------------------------------------------------------------------------
Source type
    Google Drive (share link)   Paste the share link of the main folder.
                                The folder must be shared as
                                "Anyone with the link" -> Viewer.
                                No API key needed for normal folders.
    Web folder (http/https)     Any web folder that either shows a
                                directory listing or contains a files.json
                                manifest inside each sub-folder.
    S3 bucket (public)          Any S3-compatible public bucket
                                (Scaleway, OVH, Backblaze B2, MinIO ...).
                                Paste the public bucket URL.
    Local folder (this PC)      A folder on your own disk.  The page then
                                uses relative paths, so you can upload the
                                whole folder to a web host as it is.

Main folder(s)          -- one line per group
    ONE address per line.  One line = one plain page, exactly as before.
    Several lines = several sections on the finished page, each with its
    own heading and its own filter button.

    Just the address:
        https://drive.google.com/drive/folders/AAA...
        https://drive.google.com/drive/folders/BBB...
    ...and the heading is taken from the folder's own name in the cloud.

    Or name the group yourself with a vertical bar:
        Songs 2026      | https://drive.google.com/drive/folders/AAA...
        A cappella      | https://drive.google.com/drive/folders/BBB...
        Old demos       | https://drive.google.com/drive/folders/CCC...

    Every group has its OWN MP3 / Cover / Text sub-folders inside it, and
    the sub-folder names are the same for all of them (set just below).
    Two groups may contain a song with the same file name - they are kept
    apart, and each keeps its own cover and its own words.

    A group that cannot be read (not shared, wrong link) is reported and
    skipped; the other groups are still built.

    Ctrl+Enter in this box = Fetch.

Backup source(s)         -- the same files somewhere else (optional)
    When the Drive folder is full, a file is deleted, or Drive refuses
    downloads for a while, the page can offer the music from a BACKUP
    source: a second Drive folder, or a folder on a web server.  It must
    hold the SAME sub-folders (MP3 / Cover) with the SAME file names.

    ONE backup per line:      Name | address
        Backup | https://drive.google.com/drive/folders/XXX...
        My server | https://www.issusbarn.se/music/
    (the type - Drive, web folder, S3, a folder on this PC - is recognised
    from the address).  With several main folders, give one address per
    section in the same order:   Name | address 1 | address 2

    Fetch looks every song's file up there BY NAME and the report says how
    many were found (and which were not).  Build then puts a switch on the
    page:   Download from:  Original | Backup   - it re-points every song's
    sound and cover at once, the choice is remembered in the visitor's
    browser, and a link ending in ?src=<name> opens the page already
    switched.  A song that is missing on a backup keeps playing from the
    original.  A web page cannot see from outside whether a Drive file
    still exists, so it does NOT switch by itself - the visitor presses the
    button.  A backup that holds none of the songs is left out of the page.
    (Local-folder backups are not offered: a disk path is no use online.)
    The Android app does not use the backups yet - it plays the original.

Audio / Cover / Text folder
    The names of the three sub-folders.  Defaults: MP3, Cover, Text.
    Leave one empty to skip it.

Credits file             -- everybody who helped, in ONE file
    Song title | Name, role        one credit per line, for example

        Bara på låtsas | Malin Östh, lyrics
        Besk glögg | Mikael Swahn, gitarr; Tony R, inspiration

    "lyrics" gives "Words: Malin Östh" under the title on the page; any
    other role is printed as "gitarr: Mikael Swahn".  The same song may
    have several lines, and credits on one line are separated by ";".
    Titles are matched like lyric headings (case and small typos do not
    matter).  "Open" creates the file if it does not exist yet, "Read"
    applies it at once and lists every line that matches no song on the
    page.  It is also read when a project is opened and on every Fetch.
    A "Lyrics by" typed by hand on the Tracks tab still wins.

New / Delete project (File menu)
    New project starts with an empty track list but keeps the folders -
    the Drive address, the lyric files, the local folders - so you only
    change what is different.  Delete project removes the project file
    (a copy is kept in Backups) and leaves you with an empty project that
    still points at the same folders.  Your music is never touched.

Lyric file(s) here      -- your own text files, with the chords in them
    You do not keep one text file per song, and you should not have to.
    Point at the files you actually write in - one path per line - and
    MusicSite finds each song in them by its heading.

    A file whose words are somebody else's gets a name in front:

        B:\\Texter\\0---Alla---Med_Ackord.txt
        Malin Östh | B:\\Texter\\0---Malins.txt

    Every song out of that file is then credited to that person, and the
    page prints "Words: Malin Östh" under the title.  You can still write
    or change the name for a single song on the Tracks tab ("Lyrics by"),
    and a name you type there is never replaced by the file's.


    What a file looks like:

        DAGS ATT SOMNA IN            <- the heading, in capitals
                                        (a blank line)
        Vid första glaset ...        <- the words.  These are published.
        ...
        Vers : Cx16 D#x8 Gx8         <- your chords.       NOT published
        (ORIGINAL)                   <- and everything     NOT published
        Vid första glaset ...           under it, the      NOT published
        Vid andra glaset ...            older version      NOT published
        ----------------------------------------------------------------
        NEXT SONG
        ...

    A line of dashes (or stars) separates two songs.  The heading has to
    resemble the name of the mp3 - "Dags_att_somna_in.mp3" finds "DAGS ATT
    SOMNA IN".  A tail in brackets or after a dash is ignored when
    looking, so "BADKAR - TILL BRÄDDEN ..." is still found by "Badkar.mp3",
    and "Besk_glögg_(full).mp3" finds "BESK GLÖGG".

    NOT published, ever:
      * chord rows, in every shape you write them - "V: Ex8 ↑Dx4 | X4",
        fret rows, note runs, "Bas-R:", "Synth:", indented continuations
      * the running order:  Int, V, R, St1, ½St1, St2
      * your notes: (ORIGINAL), (BORTTAGET), (?? TOM), (In Cakewalk) ...
        and, after (ORIGINAL), everything down to the end of that song,
        because that is the old version of the words
      * the heading itself - the page already prints the title

    Published, because they are words and not notes:
      * lines in brackets that are really backing vocals,
        "(All together now)", "(And I love her)"
      * verses in another language, Russian included
      * short repeated lines - "Ja, ja, ja, ja"

    Press Check to see, song by song, exactly what was kept and what was
    dropped, with the reason.  Nothing has to be taken on trust.

    The files are read again at every Fetch, so when you rewrite a line it
    is on the page after the next Fetch and Build.  If you edit the words
    HERE, on the Tracks tab, your version wins from then on and no file
    overwrites it again.

    Any encoding works, and they may differ from file to file: UTF-16,
    UTF-8, Windows-1252.  The file itself is never changed by MusicSite.

Google Drive API key (optional)
    Only needed for very large folders, or if the no-key listing stops
    working.  A free key from console.cloud.google.com (enable "Google
    Drive API", then Create credentials -> API key).

Audio link style / Image link style
    Google changes its direct-link formats now and then.  If sound or
    covers stop working, try the next style in the list and Build again.

Ignore leading track numbers
    Treats "01 - Song.mp3" and "Song.jpg" as the same track, and uses the
    number as the initial sort order.

Fuzzy matching
    How close a cover name has to be before it is accepted.  Every guess
    that was not an exact match is written into the report and shown in
    the Match column on the Tracks tab, so you can always see what it did.

Check playback
    Asks the host for one real song the way a browser will, and says
    whether the finished page will actually play it.  A plain download
    test cannot answer this - see 'Why Google Drive cannot serve the
    sound' further down.

Fetch / Refresh
    Reads the source and builds the track list.  Titles, descriptions and
    everything else you have typed are KEPT for tracks that still exist.


TAB 2 - TRACKS
-------------------------------------------------------------------------
The list shows every matched track.  Select one and edit it on the right:

    Group         Which folder the track came from (read-only).
    Title         What the page shows.  Prefilled from the file name.
    Artist        Only if this track differs from the site artist.
    Lyrics by     Who wrote the words, when it was not you.  Filled in by
                  itself for songs that came out of a lyric file with a
                  name in front of it ("Malin Östh | ...\\0---Malins.txt"),
                  and what you type here wins over that for good.
                  The page shows it as "Words: Malin Östh" under the title.
    Year          Optional.
    Description   One short line under the title.
    Made          When the song was made: a full date (1994-05-17), a month
                  (1994-05) or just a year (1994) - typed the way you
                  know it.  Shown in the "?" popup on the page.
    About         A person the song is about, if it is about one.
    Earlier releases
                  Every cassette, vinyl or CD the song has been on before
                  (it can be on several - add one line for each).  Add...
                  asks for the medium (or type your own), the name of the
                  release and its year; Edit... and Remove change the line
                  marked in the list.
                  These three are typed by you only - Fetch never touches
                  them.  A song with at least one of them gets a small
                  round "?" button on the page that opens a popup with
                  all of it; songs without get no button.
    Words / text  The lyrics.  Filled in from your lyric files (Source tab)
                  or from the Text folder.  The grey note beside the label
                  says where they came from: from your lyric file, with
                  your own corrections, or typed here.
                  The words live in YOUR files, so they are read again
                  every time the project is opened - a project saved before
                  you pointed at the files still shows them, and a line you
                  rewrite in the file is there the next time you open.
                  Type in the box and your version wins from then on - no
                  file overwrites it again.

    Choose lines  The song, line by line, with a tick on everything that is
                  published and the reason beside everything that is not
                  ("chords", "under (ORIGINAL)", "the running order").
                  Click the tick column, or mark rows and press Space.
                  This is where you correct the program when a rule got it
                  wrong: tick a chord row back on, untick a line you would
                  rather not show.  What you change is remembered as YOUR
                  choice for that song and put back after every Fetch, even
                  when you rewrite the rest of the song in the file.
                  "Back to the program's choice" forgets your corrections
                  for that song.
    Hidden        Keeps the track out of the page without deleting it.

Up / Down          Change the order on the page.
Sort by title      Alphabetical, inside each group.
Sort by number     Uses the leading number in the file name, inside each
                   group.  Groups themselves stay in the order you listed
                   them in the Main folder(s) box.
Share cover        Give several tracks the same picture.  Mark two or more
                   (Ctrl+click for single ones, Shift+click for a run) and
                   press.  The cover of the track you clicked LAST is given
                   to the others; if that one has no picture, the first
                   marked track that has one is used instead.
                   Made for the second versions of a song - the a cappella,
                   the full one, the one with guitars - which share the
                   picture with the original.
Set cover...       Fixes ONE track's cover by hand, e.g. when a song was
                   handed another song's picture.  The window lists the
                   files in the cloud's Cover folder as they were at the
                   last Fetch, closest names first; type to narrow the
                   list, pick the right one and press "Use the selected
                   cover".  The page links to it like any other cover, so
                   nothing extra has to be uploaded.
                   "No cover" leaves the song without; "Back to automatic"
                   lets the next Fetch match it by name again; "A picture
                   from this PC" is the fallback for a picture that is not
                   in the cloud (the covers folder must then be uploaded
                   with the page).
                   A cover set by hand - this way or with Share cover - is
                   never replaced by Fetch, and a picked cloud file is
                   found again by its NAME on every Fetch.  The other song,
                   the one that lost its picture to the wrong match, finds
                   its own on the next Fetch.
Remove             Takes the track out of this project (not off the cloud).

You rarely have to press Share cover, though: a track whose name is another
track's name plus a tail in brackets ("Clowner_(a_cappella)" next to
"Clowner") borrows the original's cover by itself, and the Match column
says "cover shared with ...".  Only a tail in brackets or after a dash is
ignored, so two songs that merely begin alike never steal each other's
picture.

The Match column tells you whether the cover/text was an exact name match
or a guess.


TAB 3 - SITE
-------------------------------------------------------------------------
Site title, Artist, Tagline, About      The text at the top of the page.
Accent colour                           One colour, used everywhere.
Theme                                   auto (follows the visitor's
                                        system), dark, or light.
Show download buttons                   A direct link per track.
The Android app box (top of the page)
    Show the app box    Off, or an empty address, and it is not on the page.
    Address             Where the .apk file lies.  A Google Drive share link
                        (drive.google.com/file/d/.../view) is fine - the page
                        gets the direct-download form of it by itself.
    Heading, button, text   Your own words (defaults are only a suggestion).
    The box also shows how to install an app from outside the Play Store
    and, on the live page, the page's own address with a Copy button - that
    is what the app wants under Settings > "Where the songs come from".
    To replace the app later: upload the new .apk over the old file on
    Drive ("Manage versions") and the link stays the same.

The box at the bottom  -  what it costs, and how to pay
    Everything in it is yours to write, and nothing in it is fixed in the
    program:

    Show the box        Off and it is not on the page at all.
    Heading             "If you like it" to begin with.  Write your own.
    Your text           Several paragraphs if you want - an empty line
                        starts a new one.  The words that are there when
                        you first open the program are only a suggestion:
                        the music is free, and whoever wants to give
                        something back decides what it is worth and which
                        way suits them.
    Payment links       One per line, "Name | address", exactly like the
                        footer links.  They come out as buttons in your
                        accent colour.  Revolut, PayPal and Wise are filled
                        in to start with - remove them, change them, add
                        Swish or a bank account instead, as you please.
    Built with          The small grey line at the very bottom.  Switch it
    MusicSite           off if you would rather not have it there.

Show words / lyrics                     Adds an expandable text per track.
Show search box                         Filter box above the list.
Show shuffle button                     Shuffle playback.
Play next automatically                 Continue to the next track.
Footer text and links                   Bandcamp, mail, whatever you like.

Audio handling      *** READ THIS IF YOU USE GOOGLE DRIVE ***
    Link straight to the host
        The page points at the audio where it already is.  Correct for a
        web folder of your own, or an S3 bucket.
    Download the audio into the output folder
        MusicSite fetches the audio and puts it in <output>/mp3/, and the
        page uses those copies.  You upload that folder together with
        index.html.  This is what you need for Google Drive.

Cover handling
    Keep the covers on the host
        Fine on Google Drive - its image endpoint allows embedding.
    Download the covers into the output folder
        Saved in <output>/covers/ and uploaded with the page.


TAB 4 - BUILD
-------------------------------------------------------------------------
TWO DIFFERENT FILES - this trips everyone up once:

    index.html     THE PAGE.  An ordinary web page, exactly the kind you
                   have always made.  This is the file you upload.
                   It is written into the Output folder below, and it is
                   called whatever you set on the Site tab ("Page file
                   name", index.html by default).

    ....msite      YOUR PROJECT.  The addresses, the words you typed, the
                   order of the songs, every setting.  It lives in
                   Helpfiles/MusicSite/Projects/ and it is NEVER uploaded.
                   It is only there so you do not have to set everything
                   up again next time.  The name in the title bar is this
                   file - not your site.

So: Save project = keep your work.  Build page = make the .html to upload.

Output folder    Where index.html is written.
Build page       Writes the file - and discography.html and about.html
                 next to it (tabs 6 and 7).  The previous version of each
                 is backed up automatically first, in Backups, with the
                 date as a suffix:  index_2026_10_27.html.  A second build
                 the same day also gets the time:
                 index_2026_10_27_143015.html.
Preview          Opens the page in YOUR browser - the one DefaultHub names
                 for web links, not whatever Windows happens to call the
                 default.  (A file:/// address matches no rule in that
                 table, so MusicSite asks the table what opens a link and
                 hands the page to that program.)
Open folder      Shows the file in Explorer, ready to upload.

Update everything  (F11)   THE ONE BUTTON.  Does the whole round in the right
                 order: Fetch (reads the cloud folder again) -> Save the
                 project (the old file is copied to Backups first) -> Build
                 the pages -> Send them to the server.  If a step fails
                 (a cloud folder could not be read, the build fails, the
                 server says no) it STOPS there and tells you why - nothing
                 half-finished is sent.  AppSite's DO EVERYTHING button
                 does the same for every profile without opening this window.
Send to server  (F10)   Sends the small files (the .html pages, covers/
                 if the page uses them - never the mp3 folder, nothing over
                 8 MB) to Webdock, my own VPS.  Folder <server>/p/<name>/ ;
                 the server and key are read from AppSite > Updates.
                 Test address: <public address>/p/<name>/ ("Open Webdock
                 page").  (The old HTG server is gone; there is only Webdock.)
                 "send after Build" does it by itself every time you build.
                 Server... = the Webdock folder name.
                 Every server folder gets a hidden marker file with the
                 profile name: the other profile's folder is refused, and a
                 folder with files but no marker (a page you uploaded by
                 hand) is only taken over after you say yes.
                 If you want to upload by hand instead: Open folder, then
                 upload the files (and the covers folder, if you chose that
                 mode).  Nothing else is needed - no database, no PHP.


PROFILES  (ISSUS BARN and LOSS)
-------------------------------------------------------------------------
The same program runs several separate music sites.  The profile is the end
of the program's file name:
    MusicSite_Issu.py / .exe     ISSUS BARN     Helpfiles/MusicSite_Issu/
    MusicSite_Loss.py / .exe     LOSS           Helpfiles/MusicSite_Loss/
    MusicSite.py                 no profile     Helpfiles/MusicSite/
(or start MusicSite.py with  --profile Loss).  FROM INSIDE THE PROGRAM:
File > Profile lists every profile that exists, opens one in a NEW window
(so ISSUS BARN and LOSS can be side by side) and has "New profile..." for a
new group - type a name (Blue, Band2 ...), a new empty profile opens.  One
file and one shortcut are enough; the file-name way still works.  Each profile has its own
projects, settings, backups, default output folder, cloud memory, log and
server folders, so they can not overwrite each other.  To start LOSS from
ISSUS BARN's work: open the Issu project, "Save project as..." in the LOSS
program, then change the texts and the main folder.  A project that still
points at the other profile's output folder is refused until you pick this
profile's own folder.
The first time MusicSite_Issu starts it COPIES the old Helpfiles/MusicSite
folder (the old one is left as it was).


TAB 6 - DISCOGRAPHY
-------------------------------------------------------------------------
The releases of the band: title, group, year, when and where it was
recorded, format, release date, copies and the whole tracklist.  The number
of a release (#1, #2 ...) is its place in the list - Up / Down move it and
everything is renumbered.

Import CSV...    Reads his table (one COLUMN per release, left to right =
                 #1, #2 ...; the rows Grupp, Titel, År, Datum, Var, Format,
                 Släppt, Exemplar, Låtar, then the songs).  It replaces the
                 list - the old list is in the project backup.
Add release      A new empty release at the end (#17, #18 ...).
Remove           Deletes the selected release.
Tracklist box    One song per line.  A line  A)  or  B)  starts a side
                 (shown only when a release has two or more sides); a
                 blank line is put above every B) by itself, and your own
                 blank lines are kept.
Hidden           A release can be hidden: it is left off the pages and
                 gives no numbers, but keeps its number (#14 stays #14).
                 Importing hides the releases by another group than most
                 of them (Loss) - tick or untick it per release.
                 "Check matches" lists the songs that are on the music page
                 but only on hidden releases, with a button that hides them
                 on the music page too.
Dates            1/12 1989 is written 1989-12-01.
Credits box      Musicians and guests of a release, one per line:
                     Anna Berg, violin
                     * Bo Carlsson, guitar
                     *1 Cecilia Dahl, backing vocals
                 A line without a sign is for the whole release.  A line
                 that starts with *, ** or *1, *2 ... counts for the songs
                 whose line in the tracklist ENDS with the same sign
                 (Hej gay *1) - the sign is shown beside the song.
Words / credits  The credits file (Source tab) also works backwards: every
                 song on a release shows who is credited for it
                 ("Words: Malin Östh"), also songs that are not on the
                 music page.
Check matches    Shows which songs on the page were found on which release,
                 and every guess that was not an identical title - so a
                 wrong one is easy to spot.  Fix it by spelling the song on
                 the release the same as on the page.

The release numbers are put on the music page AUTOMATICALLY by matching
titles (like lyrics and covers): a song on #3 and #9 gets  #3 #9  in front
of its ? button.  A click opens discography.html scrolled to that release.
On discography.html every song that is on the music page is a link back.
The page is written by Build; untick "Show the discography page" to leave
it out (and the numbers) without losing the list.


TAB 7 - ABOUT ME
-------------------------------------------------------------------------
A separate page, about.html: a heading, your text (an empty line starts a
new paragraph) and, if you like, a picture (an address).  While the text
is empty the page says "This page is coming soon."  Untick "Show the about
page" and it is not built (and not in the menu).
All pages share the small menu at the top: Music / Discography / About me.


TAB 5 - UPLOAD  (what is newer here than online)
-------------------------------------------------------------------------
The master files live on your own disk; the cloud folder is a copy of
them.  This tab answers the only question that matters after you have
changed something: WHICH OF MY FILES ARE NOT UP THERE YET.

Local folder(s)  The folder your masters live in - the one with MP3 /
                 Cover / Text inside it.  One line per group, in the same
                 order as the Source tab, or "Name | C:\\path" to bind a
                 line to one group by name.
                 If there is no MP3 sub-folder in there, the files are
                 taken straight out of the folder and sorted by their
                 file type instead.
                 You may give the SAME group several folders - just put
                 them on several lines (with one group, every line belongs
                 to it).  That is worth doing: a fresh export usually lands
                 wherever you were working, not in the tidy library folder,
                 and a folder nobody is looking at is a file that never
                 gets uploaded.  If the same name is in two of them the
                 NEWER one is used, and the report says which.

Deep check       Asks the cloud for the exact size and time of every file
                 that exists in both places.  For Google Drive this needs
                 NO API key: the folder listing only shows the day, but a
                 single question about each file gives the exact size and
                 the exact time.  It is one request per file, so it takes
                 a few seconds for a big folder - and it is the only way
                 to be certain.  With it off, only names and days are
                 compared and more files end up as "CHECK".

Minutes          Clock slack.  Cloud clocks and your clock are never quite
                 the same, so a difference smaller than this is ignored.

Hide from        Songs, covers AND lyrics are always compared - a missing
the list         cover is exactly the sort of thing you forget about.  These
                 three boxes only decide what is worth looking at: what is
                 already up to date, covers, lyrics.
                 A hidden file is still compared, still counted, still
                 ticked and still copied to Temp_to_drive.  When the filter
                 hides something that is ticked, the summary line says so:
                 "4 ticked (8.8 MB), 2 of them hidden below".

"I HAVE UPLOADED THESE"  -  the half-tick
-------------------------------------------------------------------------
Sometimes you know something is up there and the program cannot see it -
you uploaded it from the phone, from another machine, or in a way it has
no way of noticing.  Mark those rows and press "I have uploaded these".

They turn into "you say it is uploaded", they stop being ticked, and they
stop nagging.  Undo takes the mark back.

It is your word, not a fact, and the program never pretends otherwise:

  * The mark holds only for the file as it is right now.  Change the file
    here and the mark drops off by itself - "you marked this as uploaded,
    but the file here has changed since".
  * If the name is not in the cloud folder AT ALL, the mark cannot save it:
    that is free to see, so it is said at once.
  * "Clean comparison" is the judge.  It really asks the cloud about every
    file, and then a wrong mark comes out in the open:

        !! You marked 2 file(s) as uploaded, but they are NOT up there: ...
           They are back in the list, ticked, and the mark is gone.

  * When the cloud finally agrees, the mark quietly cleans itself away and
    the row is just "up to date".

The report of every ordinary comparison ends with a reminder of how many
rows are only marked by you, so a slip cannot hide for long.


THE SAME NAME TWICE IN THE CLOUD
-------------------------------------------------------------------------
Google Drive does NOT replace a file when you drop a new one with the same
name on it.  It puts a SECOND file there with the same name, and both stay.

MusicSite handles that the only sensible way: it uses the NEWER of the two
everywhere - on the page and in the comparison - and tells you, both on the
Source tab ("'X.mp3' is up there TWICE ... using the newer one") and in the
row's own note ("2 copies of this name are online - delete the old one").

So the page is right even before you clean up, but do clean up: open the
cloud folder, sort by name, and delete the older copy of each.

A file you uploaded TODAY is listed by Drive with a time of day instead of a
date ("9:44 am").  That is read as today at that minute, so a fresh upload
is recognised immediately.


WHY IT IS FAST THE SECOND TIME  (and what "Clean comparison" is for)
-------------------------------------------------------------------------
Reading the LIST of a folder is one question and takes a second, and that
is what finds new and removed files - so it is always read fresh.

The slow part is the exact size and time, which is one question per file.
71 songs and 478 covers is over five hundred questions, and that is the
"forever" you noticed.

So the answers are remembered, in

    Helpfiles/MusicSite/cloud_memory.json

The listing hands out two things that change as soon as a file up there
changes: its id, and the day it was last touched.  As long as those are the
same, the numbers from last time are still true and nothing is asked again.
A file that has been re-uploaded gets a new id or a new day, so it asks
about itself.  The report says which is which:

    Audio: 66 answer(s) straight from memory, asked the cloud about 5.

Clean comparison       Ask about every single file again and write down the
                       new answers.  Use it if you have moved files around
                       in the cloud by hand, if something looks wrong, or
                       just to be certain.  Shift+F6, and the log says
                       "CLEAN COMPARISON" so you can see it happened.

Every file you copy to Temp_to_drive is also marked as on its way up.
Those are NEVER answered from memory - they are the ones most likely to
have changed - and the next comparison tells you what became of them:

    (uploaded since last time)                       it landed, all is well
    copied to Temp_to_drive 2026-09-05 19:40 - not up there yet


WHAT THE STATUSES MEAN
    NEW - not online      there is no file of that name up there
    CHANGED - other size  it is up there, but a different size
    NEWER here            same size unknown, but your file is newer
    WAITING in            it has to go up, and it is already lying in
    Temp_to_drive         Temp_to_drive from an earlier round.  It is not
                          ticked and not copied again - upload it and press
                          Compare, and it turns into "up to date" by itself.
                          Emptying Temp_to_drive never removes these.
    you say it is        you pressed "I have uploaded these" on it.  The
    uploaded             program takes your word for it and stops asking -
                         but it has NOT checked, and it says so.  See below.
    CHECK - cannot tell   the source will not say enough - turn Deep
                          check on, or look at it yourself
    up to date            same size (or the cloud copy is newer)
    only online           it is up there but not here.  Nothing is ever
                          deleted from the cloud by this program.

Size decides before time on purpose.  A file that was only re-saved,
moved or touched keeps its size, and nagging about those would make the
list useless.  Two different exports of the same song practically never
end up on the same byte count.

THE TICK COLUMN
Click the narrow column on the left to tick a file, or select several rows
and press Space.  The three "Tick:" buttons set them all at once.
Everything that has to go up is ticked for you after a comparison.

TEMP_TO_DRIVE
MusicSite cannot upload to Google Drive by itself: writing to Drive needs
a signed-in Google account (OAuth), not a public link.  So it does the
next best thing.

'Copy the ticked files to Temp_to_drive' copies them into

    Temp_to_drive/MP3/     Temp_to_drive/Cover/     Temp_to_drive/Text/

- the same shape as the cloud folder (one folder per group when you have
several).  Then: open the cloud folder in the browser ('Open the cloud
folder' does it for you), open Temp_to_drive in Explorer, and drag the
contents of each sub-folder into the folder of the same name up there.
Say yes when it asks whether to replace.  Come back, press Compare again,
and it should all say "up to date".

The folder is emptied and refilled every time, so nothing is left over to
be uploaded twice.  Turn that off with the checkbox if you would rather
collect several rounds in there.

Nothing on your disk and nothing in the cloud is ever changed by this
tab - it only reads, and it only writes into Temp_to_drive.


TAGS IN THE MP3 FILES  (Upload tab, 'Tag mp3...')
MusicSite knows the title, the band, the year, who wrote the words, the
words themselves and your notes.  This puts them INSIDE the mp3 (ID3 tags),
so they follow the file to phones, car stereos, players and the cloud.

    title                the Tracks tab (or the file name)
    artist / album artist  the track's artist, else the Site tab's artist
    album                the track's group, else the site title
    year                 'Year', else the year in 'Made'
    words by             'Lyrics by' / the credits file
    composer             a credit with the role music / composer
    comment              the description + the other credits
    lyrics               what the page publishes (no chords, no notes),
                         and only when 'Show lyrics' is on for the page
    cover                optional, scaled down to 700 px

- The folders are the ones in 'Local folder(s)'.  List the permanent library
  AND the folder where fresh exports land, one per line; every mp3 in the
  MP3 sub-folder of each one is tagged.
- A song that is not on the page yet gets its data straight from the lyric
  files and the credits file, so brand-new songs are tagged too.
- The sound is not touched, only the tag at the start of the file.  A file
  whose tags are already right is NOT written (date and size stay put).
- Before a file is changed the FIRST time, the untouched original is copied
  to Backups\\MP3_originals.  Delete that folder when you trust the result.
- Fields with nothing to say are left as they are, and tags of other kinds
  already in the file stay.
- With the box 'Write title, band, words ... into my mp3 files first' ticked
  (it is, from the start) every comparison tags first.  The tagged files
  then differ in size from the ones in the cloud, so they show up as
  CHANGED - copy them to Temp_to_drive and drag them over the old ones.
- 'Check (changes nothing)' in the dialog lists what WOULD be written.

WAV TO MP3  (Upload tab, 'WAV to MP3...' or Tools menu)
Replaces WaveForge for this one job.  ffmpeg does the work (Helpfiles\\
1---Movie\\ffmpeg.exe, or 'Find ffmpeg...').
- Add files or a whole folder (with sub-folders).  Each row says if the mp3
  is NEW, if the wav is NEWER than the mp3, or if the mp3 is done already.
  'Hide those that already have an mp3' keeps the list short.  Select rows
  to convert only those, or select none to convert everything listed.
- Settings: CBR / VBR / ABR, bitrate, VBR quality, sample rate, mono/stereo,
  loudness.  The defaults (CBR 192, as the original) give the same file
  WaveForge makes.  The last settings, the folders and the choice of what to
  do with an existing mp3 are remembered.
- The mp3 gets the name of the wav (name.wav -> name.mp3) and goes into
  'Put the mp3 files in', which starts as the MP3 folder of your first local
  folder.  It is written under a temporary name and swapped in at the end,
  so a stopped or failed conversion never damages an mp3 that was there.
- 'Write the tags into the new mp3 files' tags each new mp3 at once.
- 'Even out the loudness' uses -14 LUFS.  (WaveForge asks ffmpeg for -3,
  which ffmpeg refuses, so that box has never worked there.)


WHY GOOGLE DRIVE CANNOT SERVE THE SOUND
-------------------------------------------------------------------------
This one is worth understanding, because nothing looks broken.

When a browser fetches a file for a page on a DIFFERENT site, it adds a
header of its own: 'Sec-Fetch-Site: cross-site'.  The page cannot remove
it - the browser controls it.  Google Drive answers 403 Forbidden to that
header for audio files.  The very same link downloads perfectly in a
browser tab or with a download tool, which is why it looks like it ought
to work.

So a Drive link gives you a page that looks right and plays nothing.

  * It is not a broken link, and not a bad file.
  * Changing the 'Audio link style' does not help - every format ends up
    at the same server, and it refuses all of them.
  * Covers are NOT affected: Drive's image endpoint is meant for
    embedding and allows it.  Lyrics are not affected either, because
    MusicSite reads those while building, not from the visitor's browser.

Press 'Check playback' on the Source tab to see the answer for yourself.
It asks the host exactly the way a browser will, and tells you straight
out whether the finished page will make a sound.

WHAT TO DO INSTEAD
-------------------------------------------------------------------------
1. Keep using Drive as your working library, and set Audio handling to
   'Download the audio into the output folder'.  Build, then upload
   index.html plus the mp3 folder to your web server.  Simplest if you
   already have somewhere to upload the page.
2. Put MP3/ Cover/ Text/ on your own web server and use the 'Web folder'
   source type.  Then nothing needs downloading at all.
3. Use an object store meant for media, with the 'S3 bucket' source type:
   Scaleway or OVH (France), Infomaniak kDrive (Switzerland), Hetzner
   (Germany), Backblaze B2, or your own Nextcloud.

THINGS WORTH KNOWING
-------------------------------------------------------------------------
* Even where hotlinking is allowed, a free cloud drive is not a music
  host: there are daily traffic limits per file.  The page tells the
  visitor when a file will not load instead of failing silently.
* A real object store is much better for audio: Scaleway (France), OVH
  (France), Infomaniak kDrive (Switzerland), Hetzner (Germany) or a
  Nextcloud of your own.  Switching is exactly the same three steps:
  copy the folders, paste the address, Build.
* File names are the whole system.  Keep the audio, the cover and the text
  named the same and everything pairs itself up.
* Keep a copy of your project file (.msite).  It holds all the text you
  typed; the cloud only holds the media.


KEYBOARD (on the finished web page)
-------------------------------------------------------------------------
    Space        play / pause
    Left/Right   jump 5 seconds
    N / P        next / previous track
    Esc          close the big cover / the letter list

ON THE FINISHED PAGE
-------------------------------------------------------------------------
    Click a cover    shows it big (click anywhere, X or Esc closes).
                     The title and the play button still play.
    Contributors     a title with ONE credit shows it on the line under
                     the title ("Words: Malin Östh").  With two or more,
                     a small button beside the pencil opens a panel with
                     all of them, role and name in two columns.  The big
                     cover and the player at the bottom list them all.
    Letter row       above the list: the letters your titles start with
                     (# = digits, A-Z, Å Ä Ö, then other alphabets such as
                     Cyrillic if there are titles in them).  Click one to
                     scroll there.  It scrolls away with the list - and
                     when it is out of sight a small round button (A-Ö)
                     appears in the corner, opening the same letters when
                     you want them.  From 12 tracks up; it follows the
                     search box and the group buttons.


FILES
-------------------------------------------------------------------------
    (Helpfiles/MusicSite_<profile>/ instead of Helpfiles/MusicSite/ in a profile)
    Helpfiles/MusicSite/settings.json   window size, last project, servers
    Helpfiles/MusicSite/Projects/       your .msite project files
    Helpfiles/MusicSite/Backups/        automatic backups (name + date)
    Helpfiles/MusicSite/Site/           default output folder
    Helpfiles/MusicSite/Temp_to_drive/  files waiting to be uploaded
    Helpfiles/MusicSite/cloud_memory.json  what the cloud has answered
                                        before (delete it and the next
                                        comparison simply asks again)
    Helpfiles/0---Empty/MusicSite_log.txt   (MusicSite_<profile>_log.txt)
    Helpfiles/AppSite/settings.json     READ only: the Webdock server
"""


# *****************************************************************************
# DEL 14 - MAIN WINDOW
# *****************************************************************************
class MusicSiteApp:

    def __init__(self, root):
        self.root = root
        self.settings = load_settings()
        self.project = Project()
        self.project.output_dir = self.settings.get("last_output",
                                                    OUT_DIR_DEFAULT)
        self.msgq = queue.Queue()
        self.busy = False
        self._suspend_editor = False
        self._editor_track = None              # the track the boxes show
        self.memory = CloudMemory()            # what the cloud already told us

        root.title(APP_TITLE)
        root.configure(bg=C_BG)
        root.geometry(self.settings.get("geometry", "1180x760"))
        root.minsize(940, 600)
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.report_callback_exception = CrashGuard.tk_callback

        self._style()
        self._menu()
        self._body()
        self._statusbar()

        self.root.after(120, self._pump)

        last = self.settings.get("last_project", "")
        if last and os.path.isfile(last):
            try:
                self.project.load(last)
                self._adopt_remembered_output()
                self._project_to_gui()
                self.status("Loaded %s" % os.path.basename(last))
                self.root.after(60, self._lyrics_after_load)
            except Exception as exc:
                log_exception("autoload project", exc)
                self.status("Could not open the last project", C_WARN)
        else:
            mem = self.settings.get("folder_memory") or {}
            self.project.source.update(
                {k: v for k, v in mem.items() if k in self.FOLDER_KEYS})
            self._project_to_gui()

    # ---------------------------------------------------------------- style
    def _style(self):
        st = ttk.Style()
        try:
            st.theme_use("clam")
        except Exception:
            pass
        st.configure("TNotebook", background=C_BG, borderwidth=0)
        st.configure("TNotebook.Tab", background=C_BG2, foreground=C_FG,
                     padding=(16, 7), font=("Segoe UI", 9, "bold"))
        st.map("TNotebook.Tab",
               background=[("selected", C_BG3)],
               foreground=[("selected", C_ACCENT)])
        st.configure("Treeview", background=C_BG2, fieldbackground=C_BG2,
                     foreground=C_FG, rowheight=24, borderwidth=0)
        st.configure("Treeview.Heading", background=C_BG3, foreground=C_FG,
                     font=("Segoe UI", 9, "bold"), relief="flat")
        st.map("Treeview", background=[("selected", "#3c5a78")],
               foreground=[("selected", "white")])
        # A readonly ttk.Combobox shows no text caret at all (so it can never
        # blink) - but clam paints it grey-on-grey, so the colours are mapped
        # explicitly for every state here.
        st.configure("TCombobox", fieldbackground=C_FIELD, background=C_BG3,
                     foreground=C_FG, arrowcolor=C_FG, borderwidth=1,
                     lightcolor=C_SEP, darkcolor=C_SEP, bordercolor=C_SEP)
        st.map("TCombobox",
               fieldbackground=[("readonly", C_FIELD), ("disabled", C_BG2),
                                ("!disabled", C_FIELD)],
               foreground=[("readonly", C_FG), ("disabled", C_FG_DIM),
                           ("!disabled", C_FG)],
               selectbackground=[("readonly", C_FIELD), ("focus", C_FIELD)],
               selectforeground=[("readonly", C_FG), ("focus", C_FG)],
               background=[("readonly", C_BG3), ("active", C_BG3)],
               arrowcolor=[("readonly", C_FG), ("disabled", C_FG_DIM)])
        # the drop-down list is a plain Tk listbox - only option_add reaches it
        for opt, val in (("Listbox.background", C_FIELD),
                         ("Listbox.foreground", C_FG),
                         ("Listbox.selectBackground", "#3c5a78"),
                         ("Listbox.selectForeground", "white"),
                         ("Listbox.font", "{Segoe UI} 9")):
            self.root.option_add("*TCombobox*" + opt, val)
        st.configure("TCheckbutton", background=C_BG2, foreground=C_FG)
        st.configure("Horizontal.TProgressbar", background=C_ACCENT,
                     troughcolor=C_BG2, borderwidth=0)

    # ----------------------------------------------------------------- menu
    def _menu(self):
        m = tk.Menu(self.root, tearoff=0)

        fm = tk.Menu(m, tearoff=0)
        fm.add_command(label="New project", command=self.new_project,
                       accelerator="Ctrl+N")
        fm.add_command(label="Open project...", command=self.open_project,
                       accelerator="Ctrl+O")
        fm.add_command(label="Save project", command=self.save_project,
                       accelerator="Ctrl+S")
        fm.add_command(label="Save project as...",
                       command=self.save_project_as)
        fm.add_separator()
        fm.add_command(label="Delete project...",
                       command=self.delete_project)
        fm.add_separator()
        self.profile_menu = tk.Menu(fm, tearoff=0, postcommand=self._fill_profile_menu)
        fm.add_cascade(label="Profile", menu=self.profile_menu)
        fm.add_separator()
        fm.add_command(label="Exit", command=self.on_close)
        m.add_cascade(label="File", menu=fm)

        tm = tk.Menu(m, tearoff=0)
        tm.add_command(label="Fetch / refresh from source",
                       command=self.do_fetch, accelerator="F5")
        tm.add_command(label="Compare with the cloud",
                       command=self.do_sync_compare, accelerator="F6")
        tm.add_command(label="Clean comparison (ask about every file again)",
                       command=lambda: self.do_sync_compare(True),
                       accelerator="Shift+F6")
        tm.add_command(label="WAV to MP3...", command=self.show_wav_dialog)
        tm.add_command(label="Tag the mp3 files...",
                       command=self.show_tag_dialog)
        tm.add_separator()
        tm.add_command(label="Build page", command=self.do_build,
                       accelerator="F9")
        tm.add_command(label="Preview in browser", command=self.do_preview)
        tm.add_command(label="Update everything (fetch, build, send)", command=self.do_update,
                       accelerator="F11")
        tm.add_command(label="Send to server", command=self.do_send,
                       accelerator="F10")
        tm.add_command(label="Server...", command=self.show_servers_dialog)
        tm.add_separator()
        tm.add_command(label="Open output folder",
                       command=lambda: open_in_explorer(
                           self.project.output_dir))
        tm.add_command(label="Check the lyrics",
                       command=self.show_lyrics_check)
        tm.add_command(label="Open Temp_to_drive",
                       command=lambda: open_in_explorer(self._stagedir()))
        tm.add_command(label="Open Helpfiles folder",
                       command=lambda: open_in_explorer(HELP_DIR))
        tm.add_separator()
        tm.add_command(label="Diagnostics",
                       command=lambda: show_diagnostics(self.root))
        m.add_cascade(label="Tools", menu=tm)

        hm = tk.Menu(m, tearoff=0)
        hm.add_command(label="Help", command=self.show_help, accelerator="F1")
        hm.add_command(label="About", command=self.show_about)
        m.add_cascade(label="Help", menu=hm)

        self.root.config(menu=m)
        self.root.bind("<Control-n>", lambda e: self.new_project())
        self.root.bind("<Control-o>", lambda e: self.open_project())
        self.root.bind("<Control-s>", lambda e: self.save_project())
        self.root.bind("<F5>", lambda e: self.do_fetch())
        self.root.bind("<F6>", lambda e: self.do_sync_compare())
        self.root.bind("<Shift-F6>", lambda e: self.do_sync_compare(True))
        self.root.bind("<F9>", lambda e: self.do_build())
        self.root.bind("<F10>", lambda e: self.do_send())
        self.root.bind("<F11>", lambda e: self.do_update())
        self.root.bind("<F1>", lambda e: self.show_help())

    # ----------------------------------------------------------------- body
    def _body(self):
        self.nb = ttk.Notebook(self.root)
        self.nb.pack(fill="both", expand=True, padx=8, pady=(8, 4))
        self._tab_source()
        self._tab_tracks()
        self._tab_site()
        self._tab_build()
        self._tab_upload()
        self._tab_disco()
        self._tab_about()

    # ================================================== DEL 14a - SOURCE TAB
    def _tab_source(self):
        f = tk.Frame(self.nb, bg=C_BG2, padx=16, pady=14)
        self.nb.add(f, text="  1. Source  ")

        tk.Label(f, text="Where the music lives", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).grid(row=0, column=0,
                                                     columnspan=3,
                                                     sticky="w")
        tk.Label(f, text="One main folder with the sub-folders MP3, Cover "
                         "and Text inside it.",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).grid(row=1, column=0,
                                                      columnspan=3,
                                                      sticky="w",
                                                      pady=(0, 12))
        r = 2

        def row(label, widget, hint=""):
            nonlocal r
            tk.Label(f, text=label, bg=C_BG2, fg=C_FG,
                     font=("Segoe UI", 9, "bold")).grid(row=r, column=0,
                                                        sticky="w",
                                                        pady=4, padx=(0, 10))
            widget.grid(row=r, column=1, sticky="we", pady=4)
            if hint:
                tk.Label(f, text=hint, bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 8), justify="left",
                         anchor="w").grid(row=r, column=2, sticky="w",
                                          padx=(10, 0))
            r += 1

        self.v_srctype = tk.StringVar(value=DEFAULT_SOURCE["type"])
        cb = ttk.Combobox(f, textvariable=self.v_srctype, state="readonly",
                          values=list(SOURCE_TYPES.keys()), width=32)
        cb.bind("<<ComboboxSelected>>", lambda e: self._source_type_changed())
        row("Source type", cb)

        addr_frame = tk.Frame(f, bg=C_BG2)
        abox = tk.Frame(addr_frame, bg=C_BG2)
        abox.pack(side="left", fill="both", expand=True)
        asb = tk.Scrollbar(abox)
        asb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_addr = mk_text(abox, height=4, yscrollcommand=asb.set,
                              font=("Segoe UI", 10))
        self.t_addr.pack(side="left", fill="both", expand=True)
        asb.configure(command=self.t_addr.yview)
        bind_mousewheel(self.t_addr)
        self.t_addr.bind("<Control-Return>", lambda e: (self.do_fetch(),
                                                        "break")[1])
        abtn = tk.Frame(addr_frame, bg=C_BG2)
        abtn.pack(side="left", padx=(6, 0), fill="y")
        self.b_browse = mk_button(abtn, "Browse...", self._browse_main,
                                  BTN_NORM, width=10)
        self.b_browse.pack(side="top")
        mk_button(abtn, "Fetch", self.do_fetch, BTN_MAIN,
                  width=10).pack(side="top", pady=(4, 0))
        row("Main folder(s)", addr_frame,
            "ONE PER LINE.  Just the address, or\n"
            "\"Name | address\" to name the group\n"
            "yourself.  Several lines = several\n"
            "sections on the page.  Ctrl+Enter = Fetch")

        bkf = tk.Frame(f, bg=C_BG2)
        bkbox = tk.Frame(bkf, bg=C_BG2)
        bkbox.pack(side="left", fill="both", expand=True)
        bksb = tk.Scrollbar(bkbox)
        bksb.pack(side="right", fill="y")          # scrollbar FIRST
        self.t_backups = mk_text(bkbox, height=3, yscrollcommand=bksb.set,
                                 font=("Segoe UI", 10))
        self.t_backups.pack(side="left", fill="both", expand=True)
        bksb.configure(command=self.t_backups.yview)
        bind_mousewheel(self.t_backups)
        row("Backup source(s)", bkf,
            "OPTIONAL, ONE PER LINE:  Name | address\n"
            "The SAME folders (MP3 / Cover, same file\n"
            "names) somewhere else - a second Drive\n"
            "folder or a web folder.  Several main\n"
            "lines: Name | address 1 | address 2.\n"
            "The page gets a switch Original | Name.\n"
            "Fetch looks the files up there.")

        self.e_audio_folder = mk_entry(f, width=24)
        row("Audio sub-folder", self.e_audio_folder, "default: MP3")
        self.e_cover_folder = mk_entry(f, width=24)
        row("Cover sub-folder", self.e_cover_folder, "default: Cover")
        self.e_text_folder = mk_entry(f, width=24)
        row("Text sub-folder", self.e_text_folder,
            "default: Text  (leave empty to skip)")

        lyr = tk.Frame(f, bg=C_BG2)
        lbox = tk.Frame(lyr, bg=C_BG2)
        lbox.pack(side="left", fill="both", expand=True)
        lysb = tk.Scrollbar(lbox)
        lysb.pack(side="right", fill="y")          # scrollbar FIRST
        self.t_lyrfiles = mk_text(lbox, height=3, yscrollcommand=lysb.set,
                                  font=("Segoe UI", 10))
        self.t_lyrfiles.pack(side="left", fill="both", expand=True)
        lysb.configure(command=self.t_lyrfiles.yview)
        bind_mousewheel(self.t_lyrfiles)
        lybtn = tk.Frame(lyr, bg=C_BG2)
        lybtn.pack(side="left", padx=(6, 0), fill="y")
        mk_button(lybtn, "Browse...", self._browse_lyrics, BTN_NORM,
                  width=10).pack(side="top")
        mk_button(lybtn, "Check", self.show_lyrics_check, BTN_INFO,
                  width=10).pack(side="top", pady=(4, 0))
        row("Lyric file(s) here", lyr,
            "ONE PER LINE.  Your own text files,\n"
            "several songs in each, split by a\n"
            "line of dashes.  Chords and your own\n"
            "notes are never published - press\n"
            "Check to see exactly what is dropped.")

        crow = tk.Frame(f, bg=C_BG2)
        self.e_credits = mk_entry(crow)
        self.e_credits.pack(side="left", fill="x", expand=True)
        for txt, cmd in (("Browse...", self._browse_credits),
                         ("Open", self._open_credits),
                         ("Read", self._read_credits)):
            mk_button(crow, txt, cmd, BTN_NORM,
                      width=8).pack(side="left", padx=(6, 0))
        row("Credits file", crow,
            "ONE file for everybody who helped:\n"
            "Song title | Name, role   (role\n"
            "'lyrics' = Words: ...).  Read = apply\n"
            "it now and list lines with no song.")

        tk.Frame(f, bg=C_SEP, height=1).grid(row=r, column=0, columnspan=3,
                                             sticky="we", pady=12)
        r += 1

        tk.Label(f, text="Google Drive options", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).grid(row=r, column=0,
                                                     columnspan=3,
                                                     sticky="w")
        r += 1
        self.e_apikey = mk_entry(f, show="•")
        row("API key (optional)", self.e_apikey,
            "only for big folders / if the free listing fails")

        self.v_audio_style = tk.StringVar(
            value=DEFAULT_SOURCE["audio_style"])
        row("Audio link style",
            ttk.Combobox(f, textvariable=self.v_audio_style, state="readonly",
                         values=list(GDRIVE_AUDIO_STYLES.keys()), width=32),
            "change this if the sound stops working")
        self.v_image_style = tk.StringVar(
            value=DEFAULT_SOURCE["image_style"])
        row("Image link style",
            ttk.Combobox(f, textvariable=self.v_image_style, state="readonly",
                         values=list(GDRIVE_IMAGE_STYLES.keys()), width=32),
            "change this if the covers stop showing")

        tk.Frame(f, bg=C_SEP, height=1).grid(row=r, column=0, columnspan=3,
                                             sticky="we", pady=12)
        r += 1

        tk.Label(f, text="Matching", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).grid(row=r, column=0,
                                                     columnspan=3, sticky="w")
        r += 1
        self.v_dropnum = tk.BooleanVar(value=True)
        tk.Checkbutton(f, text="Ignore a leading track number in file names "
                               "(\"01 - Song.mp3\" = \"Song.jpg\")",
                       variable=self.v_dropnum, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).grid(row=r, column=0,
                                                  columnspan=3, sticky="w")
        r += 1
        fz = tk.Frame(f, bg=C_BG2)
        self.v_fuzzy = tk.DoubleVar(value=0.84)
        tk.Scale(fz, from_=0.60, to=1.00, resolution=0.01, orient="horizontal",
                 variable=self.v_fuzzy, bg=C_BG2, fg=C_FG, troughcolor=C_FIELD,
                 highlightthickness=0, length=220, bd=1, sliderrelief="raised",
                 activebackground=C_ACCENT,
                 font=("Segoe UI", 8)).pack(side="left")
        tk.Label(fz, text="1.00 = only near-identical names",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(10, 0))
        row("Fuzzy name matching", fz)

        tk.Frame(f, bg=C_SEP, height=1).grid(row=r, column=0, columnspan=3,
                                             sticky="we", pady=12)
        r += 1

        btns = tk.Frame(f, bg=C_BG2)
        btns.grid(row=r, column=0, columnspan=3, sticky="w")
        mk_button(btns, "Fetch / refresh from source", self.do_fetch,
                  BTN_MAIN, width=26).pack(side="left")
        mk_button(btns, "Test the address", self.do_test, BTN_NORM,
                  width=16).pack(side="left", padx=6)
        mk_button(btns, "Check playback", self.do_check_playback, BTN_WARN,
                  width=16).pack(side="left", padx=6)
        mk_button(btns, "Help", self.show_help, BTN_INFO,
                  width=10).pack(side="left", padx=6)
        r += 1

        wrap = tk.Frame(f, bg=C_BG2)
        wrap.grid(row=r, column=0, columnspan=3, sticky="nsew", pady=(12, 0))
        f.rowconfigure(r, weight=1)
        f.columnconfigure(1, weight=1)
        tk.Label(wrap, text="Report", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w")
        inner = tk.Frame(wrap, bg=C_BG2)
        inner.pack(fill="both", expand=True)
        sb = tk.Scrollbar(inner)
        sb.pack(side="right", fill="y")            # scrollbar FIRST
        self.t_report = mk_text(inner, height=8, yscrollcommand=sb.set,
                                font=("Consolas", 9))
        self.t_report.pack(side="left", fill="both", expand=True)
        sb.configure(command=self.t_report.yview)
        bind_mousewheel(self.t_report)

    def _source_type_changed(self):
        is_local = self.v_srctype.get().startswith("Local")
        try:
            self.b_browse.configure(state="normal" if is_local else "disabled")
        except Exception:
            pass

    def _browse_lyrics(self):
        names = filedialog.askopenfilenames(
            title="Pick your lyric file(s)",
            filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
        if not names:
            return
        cur = self.t_lyrfiles.get("1.0", "end-1c").strip()
        add = "\n".join(names)
        self.t_lyrfiles.delete("1.0", "end")
        self.t_lyrfiles.insert("1.0", (cur + "\n" + add) if cur else add)

    def _browse_credits(self):
        p = filedialog.askopenfilename(
            parent=self.root, title="Pick the credits file",
            filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
        if p:
            self.e_credits.delete(0, "end")
            self.e_credits.insert(0, p)
            self._read_credits()

    def _open_credits(self):
        p = self.e_credits.get().strip().strip('"')
        if not p:
            messagebox.showinfo(APP_NAME, "Type where the credits file "
                                "should live (or Browse to it) first.",
                                parent=self.root)
            return
        if not os.path.isfile(p):
            if not messagebox.askyesno(APP_NAME, "There is no file\n\n%s\n\n"
                                       "Create it, with the instructions "
                                       "at the top?" % p, parent=self.root):
                return
            try:
                with open(p, "w", encoding="utf-8-sig", newline="\r\n") as f:
                    f.write(CREDITS_FILE_HEAD)
            except OSError as exc:
                messagebox.showerror(APP_NAME, "Could not create it:\n%s" % exc,
                                     parent=self.root)
                return
        open_in_explorer(p)

    def _read_credits(self, quiet=False):
        """Apply the credits file to the tracks now.  Returns the number of
        tracks that have credits."""
        p = self.e_credits.get().strip().strip('"')
        if not p:
            return 0
        index, report = build_credits_index(p)
        if not os.path.isfile(p):
            if not quiet:
                messagebox.showwarning(APP_NAME, "\n".join(report),
                                       parent=self.root)
            return 0
        self._editor_to_track()
        was_dirty = self.project.dirty
        n = apply_credits(self.project.tracks, index)
        left = credits_unused(index)
        # on open it is only re-reading the file - nothing HE changed
        self.project.dirty = True if not quiet else was_dirty
        self._refresh_tree(self._sel_index())
        self._update_titlebar()
        self.status("Credits: %d track(s) credited" % n, C_OK)
        if not quiet:
            msg = "%s\n%d track(s) on your page now carry credits." % (
                "\n".join(report), n)
            if left:
                msg += ("\n\nNo song on the page matches these lines - "
                        "check the spelling:\n  " + "\n  ".join(sorted(left)))
            messagebox.showinfo(APP_NAME, msg, parent=self.root)
        return n

    def _browse_main(self):
        d = filedialog.askdirectory(title="Pick a main music folder")
        if not d:
            return
        cur = self.t_addr.get("1.0", "end-1c").strip()
        self.t_addr.delete("1.0", "end")
        self.t_addr.insert("1.0", (cur + "\n" + d) if cur else d)

    # ================================================== DEL 14b - TRACKS TAB
    def _tab_tracks(self):
        f = tk.Frame(self.nb, bg=C_BG2)
        self.nb.add(f, text="  2. Tracks  ")

        pane = tk.PanedWindow(f, orient="horizontal", bg=C_BG,
                              sashwidth=6, sashrelief="flat", bd=0)
        pane.pack(fill="both", expand=True, padx=10, pady=10)
        self.pane = pane

        # ---- left: list
        left = tk.Frame(pane, bg=C_BG2)
        pane.add(left, minsize=380)

        top = tk.Frame(left, bg=C_BG2)
        top.pack(fill="x", pady=(0, 6))
        mk_button(top, "Up", lambda: self._move(-1), BTN_NORM,
                  width=5).pack(side="left")
        mk_button(top, "Down", lambda: self._move(1), BTN_NORM,
                  width=6).pack(side="left", padx=4)
        mk_button(top, "Sort by title", lambda: self._sort("title"),
                  BTN_NORM).pack(side="left", padx=(10, 4))
        mk_button(top, "Sort by number", lambda: self._sort("number"),
                  BTN_NORM).pack(side="left")
        mk_button(top, "Share cover", self._share_cover, BTN_NORM,
                  width=12).pack(side="left", padx=(10, 0))
        mk_button(top, "Set cover...", self._set_cover, BTN_NORM,
                  width=12).pack(side="left", padx=(4, 0))
        mk_button(top, "Remove", self._remove_track, BTN_DANGER,
                  width=9).pack(side="right")

        holder = tk.Frame(left, bg=C_BG2)
        holder.pack(fill="both", expand=True)
        vsb = tk.Scrollbar(holder)
        vsb.pack(side="right", fill="y")           # scrollbar FIRST
        hsb = tk.Scrollbar(holder, orient="horizontal")
        hsb.pack(side="bottom", fill="x")
        cols = ("n", "group", "title", "cover", "text", "match")
        self.tree = ttk.Treeview(holder, columns=cols, show="headings",
                                 selectmode="extended",
                                 yscrollcommand=vsb.set,
                                 xscrollcommand=hsb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        vsb.configure(command=self.tree.yview)
        hsb.configure(command=self.tree.xview)
        for c, txt, w, anchor in (("n", "#", 36, "e"),
                                  ("group", "Group", 110, "w"),
                                  ("title", "Title", 210, "w"),
                                  ("cover", "Cover", 58, "center"),
                                  ("text", "Text", 50, "center"),
                                  ("match", "Match", 170, "w")):
            self.tree.heading(c, text=txt, anchor=anchor)
            self.tree.column(c, width=w, anchor=anchor,
                             stretch=(c in ("title", "match")))
        self.tree.tag_configure("hidden", foreground=C_FG_DIM)
        self.tree.tag_configure("nocover", foreground=C_WARN)
        self.tree.bind("<<TreeviewSelect>>", self._on_tree_select)
        bind_mousewheel(self.tree)

        # ---- right: editor
        right = tk.Frame(pane, bg=C_BG2, padx=14)
        pane.add(right, minsize=340)

        tk.Label(right, text="Track details", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w", pady=(0, 8))

        def field(label, widget, hint=""):
            tk.Label(right, text=label, bg=C_BG2, fg=C_FG,
                     font=("Segoe UI", 9, "bold")).pack(anchor="w",
                                                        pady=(8, 2))
            widget.pack(fill="x")
            if hint:
                tk.Label(right, text=hint, bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 8)).pack(anchor="w")

        self.e_title = mk_entry(right, font=("Segoe UI", 11))
        field("Title", self.e_title)

        rowf = tk.Frame(right, bg=C_BG2)
        self.e_tartist = mk_entry(rowf)
        self.e_tartist.pack(side="left", fill="x", expand=True)
        tk.Label(rowf, text="  Year ", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.e_year = mk_entry(rowf, width=8)
        self.e_year.pack(side="left")
        field("Artist (only if different from the site artist)", rowf)

        self.e_lyrby = mk_entry(right)
        field("Lyrics by (if someone else wrote the words)", self.e_lyrby)

        self.e_desc = mk_entry(right)
        field("Description (one short line under the title)", self.e_desc)

        # ---- behind the "?" button on the page
        mrow = tk.Frame(right, bg=C_BG2)
        self.e_made = mk_entry(mrow, width=12)
        self.e_made.pack(side="left")
        tk.Label(mrow, text="  About a person ", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.e_about = mk_entry(mrow)
        self.e_about.pack(side="left", fill="x", expand=True)
        field("Made (a date, or just the year)  -  shown behind the ? button",
              mrow)

        tk.Label(right, text="Released before on (cassette, vinyl, CD ...)",
                 bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(8, 2))
        rrow = tk.Frame(right, bg=C_BG2)
        rrow.pack(fill="x")
        self.lb_rel = tk.Listbox(rrow, height=3, bg=C_FIELD, fg=C_FG,
                                 selectbackground=C_ACCENT,
                                 selectforeground="black", relief="flat",
                                 highlightthickness=1,
                                 highlightbackground=C_SEP,
                                 exportselection=False,
                                 font=("Segoe UI", 9))
        self.lb_rel.pack(side="left", fill="x", expand=True)
        self.lb_rel.bind("<Double-Button-1>", lambda e: self._release_edit())
        rbtn = tk.Frame(rrow, bg=C_BG2)
        rbtn.pack(side="left", padx=(6, 0))
        mk_button(rbtn, "Add...", self._release_add, BTN_NORM,
                  width=8).pack(pady=1)
        mk_button(rbtn, "Edit...", self._release_edit, BTN_NORM,
                  width=8).pack(pady=1)
        mk_button(rbtn, "Remove", self._release_remove, BTN_NORM,
                  width=8).pack(pady=1)

        wrow = tk.Frame(right, bg=C_BG2)
        wrow.pack(fill="x", pady=(10, 2))
        tk.Label(wrow, text="Words / text", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.l_lyrsrc = tk.Label(wrow, text="", bg=C_BG2, fg=C_FG_DIM,
                                 font=("Segoe UI", 8))
        self.l_lyrsrc.pack(side="left", padx=(8, 0))
        mk_button(wrow, "Choose lines...", self.show_line_picker, BTN_INFO,
                  width=15).pack(side="right")
        lw = tk.Frame(right, bg=C_BG2)
        lw.pack(fill="both", expand=True)
        lsb = tk.Scrollbar(lw)
        lsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_lyrics = mk_text(lw, height=10, yscrollcommand=lsb.set,
                                font=("Segoe UI", 10))
        self.t_lyrics.pack(side="left", fill="both", expand=True)
        lsb.configure(command=self.t_lyrics.yview)
        bind_mousewheel(self.t_lyrics)

        self.v_hidden = tk.BooleanVar(value=False)
        tk.Checkbutton(right, text="Hidden (kept in the project, "
                                   "left out of the page)",
                       variable=self.v_hidden, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG,
                       command=self._editor_to_track,
                       font=("Segoe UI", 9)).pack(anchor="w", pady=(8, 2))

        self.l_files = tk.Label(right, text="", bg=C_BG2, fg=C_FG_DIM,
                                font=("Consolas", 8), justify="left",
                                anchor="w")
        self.l_files.pack(fill="x", pady=(4, 0))

        brow = tk.Frame(right, bg=C_BG2)
        brow.pack(fill="x", pady=(10, 12))
        mk_button(brow, "Apply changes", self._editor_to_track, BTN_MAIN,
                  width=16).pack(side="left")
        mk_button(brow, "Open audio link",
                  self._open_audio, BTN_NORM, width=16).pack(side="left",
                                                             padx=6)
        mk_button(brow, "Title from file", self._title_from_file, BTN_NORM,
                  width=14).pack(side="left")

        for w in (self.e_title, self.e_tartist, self.e_year, self.e_desc,
                  self.e_lyrby, self.e_made, self.e_about):
            w.bind("<Return>", lambda e: self._editor_to_track())
            w.bind("<FocusOut>", lambda e: self._editor_to_track())
        self.t_lyrics.bind("<FocusOut>", lambda e: self._editor_to_track())

        try:
            pane.paneconfigure(left, stretch="always")
        except Exception:
            pass

    # ==================================================== DEL 14c - SITE TAB
    def _tab_site(self):
        outer = tk.Frame(self.nb, bg=C_BG2)
        self.nb.add(outer, text="  3. Site  ")

        vsb = tk.Scrollbar(outer)
        vsb.pack(side="right", fill="y")           # scrollbar FIRST
        canvas = tk.Canvas(outer, bg=C_BG2, highlightthickness=0,
                           yscrollcommand=vsb.set)
        canvas.pack(side="left", fill="both", expand=True)
        vsb.configure(command=canvas.yview)
        f = tk.Frame(canvas, bg=C_BG2, padx=18, pady=14)
        win = canvas.create_window((0, 0), window=f, anchor="nw")
        f.bind("<Configure>",
               lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfigure(win, width=e.width))
        bind_mousewheel(canvas)
        bind_mousewheel(f, canvas)

        tk.Label(f, text="How the page looks", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w")
        tk.Label(f, text="All of this is written into the page itself - "
                         "no external files, no tracking.",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(anchor="w",
                                                      pady=(0, 12))

        def field(label, widget, hint=""):
            tk.Label(f, text=label, bg=C_BG2, fg=C_FG,
                     font=("Segoe UI", 9, "bold")).pack(anchor="w",
                                                        pady=(10, 2))
            widget.pack(fill="x")
            if hint:
                tk.Label(f, text=hint, bg=C_BG2, fg=C_FG_DIM,
                         font=("Segoe UI", 8)).pack(anchor="w")

        self.e_sitetitle = mk_entry(f, font=("Segoe UI", 11))
        field("Site title", self.e_sitetitle)
        self.e_siteartist = mk_entry(f)
        field("Artist", self.e_siteartist)
        self.e_tagline = mk_entry(f)
        field("Tagline", self.e_tagline, "one line, shown in italics")

        tk.Label(f, text="About text", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(10, 2))
        aw = tk.Frame(f, bg=C_BG2)
        aw.pack(fill="x")
        asb = tk.Scrollbar(aw)
        asb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_about = mk_text(aw, height=5, yscrollcommand=asb.set,
                               font=("Segoe UI", 10))
        self.t_about.pack(side="left", fill="both", expand=True)
        asb.configure(command=self.t_about.yview)
        bind_mousewheel(self.t_about)

        # colour + theme
        crow = tk.Frame(f, bg=C_BG2)
        crow.pack(fill="x", pady=(14, 0))
        tk.Label(crow, text="Accent colour", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.e_accent = mk_entry(crow, width=10)
        self.e_accent.pack(side="left", padx=(10, 6))
        self.sw_accent = tk.Label(crow, text="        ", bg="#e8663a",
                                  relief="solid", bd=1)
        self.sw_accent.pack(side="left")
        mk_button(crow, "Pick...", self._pick_colour, BTN_NORM,
                  width=8).pack(side="left", padx=6)
        self.e_accent.bind("<KeyRelease>", lambda e: self._accent_preview())
        self.e_accent.bind("<Return>", lambda e: self._accent_preview())

        tk.Label(crow, text="     Theme", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.v_theme = tk.StringVar(value="auto")
        ttk.Combobox(crow, textvariable=self.v_theme, state="readonly",
                     width=10,
                     values=["auto", "dark", "light"]).pack(side="left",
                                                            padx=(10, 0))

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=14)

        tk.Label(f, text="The box at the bottom  -  what it costs, and how "
                         "to pay if you want to", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w")
        tk.Label(f, text="Your own words, in your own order.  Nothing here "
                         "is fixed in the program: change the heading, "
                         "rewrite the text, add or remove a payment link.  "
                         "An empty line starts a new paragraph.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=820, justify="left").pack(anchor="w", pady=(0, 6))
        self.v_support = tk.BooleanVar(value=True)
        tk.Checkbutton(f, text="Show the box", variable=self.v_support,
                       bg=C_BG2, fg=C_FG, selectcolor=C_FIELD,
                       activebackground=C_BG2, activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(anchor="w")
        self.e_suptitle = mk_entry(f)
        field("Heading of the box", self.e_suptitle)

        tk.Label(f, text="Your text", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(8, 2))
        sw = tk.Frame(f, bg=C_BG2)
        sw.pack(fill="x")
        ssb = tk.Scrollbar(sw)
        ssb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_support = mk_text(sw, height=6, yscrollcommand=ssb.set,
                                 font=("Segoe UI", 10))
        self.t_support.pack(side="left", fill="both", expand=True)
        ssb.configure(command=self.t_support.yview)
        bind_mousewheel(self.t_support)

        tk.Label(f, text="Payment links      one per line:  Name | address",
                 bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(8, 2))
        pw = tk.Frame(f, bg=C_BG2)
        pw.pack(fill="x")
        psb = tk.Scrollbar(pw)
        psb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_paylinks = mk_text(pw, height=4, yscrollcommand=psb.set,
                                  font=("Segoe UI", 10))
        self.t_paylinks.pack(side="left", fill="both", expand=True)
        psb.configure(command=self.t_paylinks.yview)
        bind_mousewheel(self.t_paylinks)

        self.v_made = tk.BooleanVar(value=True)
        tk.Checkbutton(f, text="Show the small \"Built with MusicSite\" line "
                               "at the very bottom",
                       variable=self.v_made, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(anchor="w", pady=(8, 0))

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=14)

        tk.Label(f, text="The Android app  -  a box at the top of the page "
                         "with a download button", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w")
        tk.Label(f, text="Put the app file (the .apk) on Google Drive or on "
                         "your own server and paste its address here.  A "
                         "Google Drive share link is turned into a direct "
                         "download by itself.  The box also shows the "
                         "visitor how to install it and which address to "
                         "type into the app.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=820, justify="left").pack(anchor="w", pady=(0, 6))
        self.v_app = tk.BooleanVar(value=True)
        tk.Checkbutton(f, text="Show the app box", variable=self.v_app,
                       bg=C_BG2, fg=C_FG, selectcolor=C_FIELD,
                       activebackground=C_BG2, activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(anchor="w")
        self.e_apptitle = mk_entry(f)
        field("Heading of the box", self.e_apptitle)
        self.e_appurl = mk_entry(f)
        field("Address of the app file (.apk)", self.e_appurl,
              "empty = no box.  A drive.google.com/file/d/... link is fine")
        self.e_appbutton = mk_entry(f)
        field("Text on the button", self.e_appbutton)

        tk.Label(f, text="Text about the app", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(8, 2))
        apw = tk.Frame(f, bg=C_BG2)
        apw.pack(fill="x")
        apsb = tk.Scrollbar(apw)
        apsb.pack(side="right", fill="y")          # scrollbar FIRST
        self.t_apptext = mk_text(apw, height=5, yscrollcommand=apsb.set,
                                 font=("Segoe UI", 10))
        self.t_apptext.pack(side="left", fill="both", expand=True)
        apsb.configure(command=self.t_apptext.yview)
        bind_mousewheel(self.t_apptext)

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=14)

        tk.Label(f, text="Page features", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w")
        self.v_downloads = tk.BooleanVar(value=True)
        self.v_showlyrics = tk.BooleanVar(value=True)
        self.v_search = tk.BooleanVar(value=True)
        self.v_shuffle = tk.BooleanVar(value=True)
        self.v_autonext = tk.BooleanVar(value=True)
        for var, txt in ((self.v_downloads, "Show a download button per track"),
                         (self.v_showlyrics, "Show words / lyrics"),
                         (self.v_search, "Show the search box"),
                         (self.v_shuffle, "Show the shuffle button"),
                         (self.v_autonext, "Play the next track automatically")):
            tk.Checkbutton(f, text=txt, variable=var, bg=C_BG2, fg=C_FG,
                           selectcolor=C_FIELD, activebackground=C_BG2,
                           activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(anchor="w")

        tk.Label(f, text="What the page offers", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(14, 2))
        tk.Label(f, text="Some hosts (Google Drive) refuse to let another "
                         "page PLAY their files, but serve a download without "
                         "any complaint. 'Decide automatically' tests the real "
                         "host at build time and picks the right page for you.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=820, justify="left").pack(anchor="w", pady=(0, 4))
        self.v_playermode = tk.StringVar(value="auto")
        for val, txt in (
                ("auto",
                 "Decide automatically - player if the host allows it, "
                 "otherwise a download page  (recommended)"),
                ("player",
                 "Always a player with play buttons"),
                ("download",
                 "Always a download page - no player, one Download button "
                 "per track")):
            tk.Radiobutton(f, text=txt, value=val, variable=self.v_playermode,
                           bg=C_BG2, fg=C_FG, selectcolor=C_FIELD,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(anchor="w")

        tk.Label(f, text="Audio handling", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(14, 2))
        tk.Label(f, text="Google Drive hands a file over to a download but "
                         "refuses to let another web page play it (HTTP 403). "
                         "If your audio lives there, pick the second option "
                         "and upload the mp3 folder together with the page.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=820, justify="left").pack(anchor="w",
                                                      pady=(0, 4))
        self.v_audiomode = tk.StringVar(value="remote")
        for val, txt in (("remote",
                          "Link straight to the host "
                          "(works for a web folder or an S3 bucket)"),
                         ("local",
                          "Download the audio into the output folder "
                          "(needed for Google Drive - slow, but it works)")):
            tk.Radiobutton(f, text=txt, value=val, variable=self.v_audiomode,
                           bg=C_BG2, fg=C_FG, selectcolor=C_FIELD,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(anchor="w")

        tk.Label(f, text="Cover handling", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(14, 2))
        self.v_covermode = tk.StringVar(value="remote")
        for val, txt in (("remote",
                          "Keep the covers on the cloud host "
                          "(fine on Google Drive - images are allowed)"),
                         ("local",
                          "Download the covers into the output folder "
                          "(upload them with the page - safest)")):
            tk.Radiobutton(f, text=txt, value=val, variable=self.v_covermode,
                           bg=C_BG2, fg=C_FG, selectcolor=C_FIELD,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(anchor="w")

        tk.Frame(f, bg=C_SEP, height=1).pack(fill="x", pady=14)

        tk.Label(f, text="Footer", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w")
        self.e_footer = mk_entry(f)
        field("Footer text", self.e_footer)

        tk.Label(f, text="Links  (one per line:  Label | https://address)",
                 bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(10, 2))
        lw = tk.Frame(f, bg=C_BG2)
        lw.pack(fill="x")
        lsb = tk.Scrollbar(lw)
        lsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_links = mk_text(lw, height=5, yscrollcommand=lsb.set,
                               font=("Consolas", 9))
        self.t_links.pack(side="left", fill="both", expand=True)
        lsb.configure(command=self.t_links.yview)
        bind_mousewheel(self.t_links)

        self.e_pagename = mk_entry(f, width=24)
        field("Page file name", self.e_pagename, "default: index.html")

        tk.Label(f, text="Order on the page", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(14, 2))
        self.v_sortmode = tk.StringVar(value="alpha")
        for val, txt in (
                ("alpha", "Alphabetical - numbers first, then A-Z, Å Ä Ö, "
                          "other alphabets  (recommended)"),
                ("own", "My own order from the Tracks tab")):
            tk.Radiobutton(f, text=txt, value=val, variable=self.v_sortmode,
                           bg=C_BG2, fg=C_FG, selectcolor=C_FIELD,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(anchor="w")

        tk.Frame(f, bg=C_BG2, height=18).pack()

    def _pick_colour(self):
        cur = self.e_accent.get().strip() or "#e8663a"
        try:
            rgb, hexcol = colorchooser.askcolor(color=cur,
                                                title="Accent colour")
        except Exception:
            hexcol = None
        if hexcol:
            self.e_accent.delete(0, "end")
            self.e_accent.insert(0, hexcol)
            self._accent_preview()

    def _accent_preview(self):
        c = self.e_accent.get().strip()
        if re.fullmatch(r"#[0-9a-fA-F]{6}", c or ""):
            try:
                self.sw_accent.configure(bg=c)
            except Exception:
                pass

    # =================================================== DEL 14d - BUILD TAB
    def _tab_build(self):
        f = tk.Frame(self.nb, bg=C_BG2, padx=18, pady=16)
        self.nb.add(f, text="  4. Build  ")

        tk.Label(f, text="Build the page", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w")
        tk.Label(f, text="One self-contained HTML file. Send it to your "
                         "servers with the button below (or upload it by hand).",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(anchor="w",
                                                      pady=(0, 2))
        # He has made web pages since FrontPage 98 and asked, reasonably,
        # whether his site is now called ".msite".  It is not, and the
        # program should say so where he is standing.
        tk.Label(f, text="The page is an ordinary .html file - index.html by "
                         "default.  The .msite in the title bar is only your "
                         "project (addresses, the words you typed, the "
                         "order); it is never uploaded anywhere.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=900, justify="left").pack(anchor="w",
                                                      pady=(0, 14))

        orow = tk.Frame(f, bg=C_BG2)
        orow.pack(fill="x")
        tk.Label(orow, text="Output folder", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.e_outdir = mk_entry(orow)
        self.e_outdir.pack(side="left", fill="x", expand=True, padx=(10, 6))
        self.e_outdir.bind("<Return>", lambda e: self.do_build())
        mk_button(orow, "Browse...", self._browse_out, BTN_NORM,
                  width=10).pack(side="left")
        self.e_outdir.bind("<FocusOut>", lambda e: self._gui_to_project())

        # the five latest folders as quick links (always five rows, so the
        # tab does not change size)
        qrow = tk.Frame(f, bg=C_BG2)
        qrow.pack(fill="x", pady=(4, 0))
        tk.Label(qrow, text="Recent", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8), width=12,
                 anchor="nw").pack(side="left", anchor="n")
        qcol = tk.Frame(qrow, bg=C_BG2)
        qcol.pack(side="left", fill="x", expand=True)
        self.recent_labels = []
        for _n in range(5):
            lab = tk.Label(qcol, text="", bg=C_BG2, fg=C_ACCENT,
                           font=("Segoe UI", 9, "underline"), anchor="w")
            lab.pack(fill="x")
            lab.bind("<Button-1>",
                     lambda e, l=lab: self._set_outdir(l.cget("text")))
            self.recent_labels.append(lab)
        self._refresh_recent_links()

        brow = tk.Frame(f, bg=C_BG2)
        brow.pack(fill="x", pady=(16, 6))
        mk_button(brow, "Build page  (F9)", self.do_build, BTN_MAIN,
                  width=18).pack(side="left")
        mk_button(brow, "Preview in browser", self.do_preview, BTN_NORM,
                  width=20).pack(side="left", padx=6)
        mk_button(brow, "Open output folder",
                  lambda: open_in_explorer(self._outdir()), BTN_NORM,
                  width=20).pack(side="left")

        # v1.15.0: send the small files to Webdock (DEL 12C); v1.16.0: HTG is gone, "Update everything" added (DEL 12D)
        srow = tk.Frame(f, bg=C_BG2)
        srow.pack(fill="x", pady=(0, 6))
        self.v_srv_web = tk.BooleanVar(value=bool(self.settings.get("srv_webdock", True)))
        self.v_srv_auto = tk.BooleanVar(value=bool(self.settings.get("srv_auto", False)))
        mk_button(srow, "Update everything  (F11)", self.do_update, BTN_MAIN,
                  width=24).pack(side="left")
        mk_button(srow, "Send to server  (F10)", self.do_send, BTN_NORM,
                  width=20).pack(side="left", padx=(8, 0))
        for txt, var in (("Webdock", self.v_srv_web), ("send after Build", self.v_srv_auto)):
            tk.Checkbutton(srow, text=txt, variable=var, command=self._srv_ticks_changed,
                           bg=C_BG2, fg=C_FG, selectcolor=C_FIELD, activebackground=C_BG2,
                           activeforeground=C_FG, font=("Segoe UI", 9)).pack(side="left", padx=(10, 0))
        mk_button(srow, "Server...", self.show_servers_dialog, BTN_NORM,
                  width=12).pack(side="left", padx=(14, 0))
        mk_button(srow, "Open Webdock page", self.open_webdock_page, BTN_NORM,
                  width=18).pack(side="left", padx=6)

        self.pb = ttk.Progressbar(f, mode="determinate", maximum=100,
                                  style="Horizontal.TProgressbar")
        self.pb.pack(fill="x", pady=(12, 6))

        tk.Label(f, text="Build log", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(8, 2))
        lw = tk.Frame(f, bg=C_BG2)
        lw.pack(fill="both", expand=True)
        lsb = tk.Scrollbar(lw)
        lsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_build = mk_text(lw, yscrollcommand=lsb.set,
                               font=("Consolas", 9))
        self.t_build.pack(side="left", fill="both", expand=True)
        lsb.configure(command=self.t_build.yview)
        bind_mousewheel(self.t_build)

        tk.Label(f, text="Tip: if the covers or the sound stop working after "
                         "a while, the cloud host is rate-limiting them. "
                         "Switch the link style on the Source tab, or move "
                         "the files to a real object store.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=900, justify="left").pack(anchor="w",
                                                      pady=(8, 0))

    def _browse_out(self):
        d = filedialog.askdirectory(title="Where should index.html go?",
                                    initialdir=self._outdir())
        if d:
            self._set_outdir(d)

    def _set_outdir(self, d):
        """Choose an output folder: box, project, settings and quick links."""
        d = (d or "").strip()
        if not d:
            return
        self.e_outdir.delete(0, "end")
        self.e_outdir.insert(0, d)
        self._gui_to_project()
        self._remember_output(d)

    def _remember_output(self, d):
        """Put D first in the list of the five latest output folders."""
        key = os.path.normcase(os.path.normpath(d))
        recent = [r for r in (self.settings.get("recent_outputs") or [])
                  if os.path.normcase(os.path.normpath(r)) != key]
        self.settings["recent_outputs"] = ([d] + recent)[:5]
        self.settings["last_output"] = d
        save_settings(self.settings)
        self._refresh_recent_links()

    def _refresh_recent_links(self):
        recent = self.settings.get("recent_outputs") or []
        for n, lab in enumerate(self.recent_labels):
            if n < len(recent):
                lab.configure(text=recent[n], cursor="hand2")
            else:
                lab.configure(text="", cursor="")

    def _adopt_remembered_output(self):
        """The folder used last wins over the one stored in the project."""
        last = self.settings.get("last_output")
        if last:
            self.project.output_dir = last

    def _outdir(self):
        return self.e_outdir.get().strip() or OUT_DIR_DEFAULT

    # ============================================ DEL 14f - DISCOGRAPHY TAB
    # ToDo: the releases are edited in place (boxes on the right, written
    # back when a box loses focus, on another row, on save and on build).
    def _tab_disco(self):
        f = tk.Frame(self.nb, bg=C_BG2)
        self.nb.add(f, text="  6. Discography  ")
        self._disco_cur = None             # index of the release in the boxes
        self._disco_loading = False

        pane = tk.PanedWindow(f, orient="horizontal", bg=C_BG,
                              sashwidth=6, sashrelief="flat", bd=0)
        pane.pack(fill="both", expand=True, padx=10, pady=10)

        # ---- left: the list and the page switches
        left = tk.Frame(pane, bg=C_BG2)
        pane.add(left, minsize=420)

        top = tk.Frame(left, bg=C_BG2)
        top.pack(fill="x", pady=(0, 6))
        mk_button(top, "Import CSV...", self._disco_import, BTN_MAIN,
                  width=13).pack(side="left")
        mk_button(top, "Add release", self._disco_add, BTN_NORM,
                  width=11).pack(side="left", padx=(6, 0))
        mk_button(top, "Up", lambda: self._disco_move(-1), BTN_NORM,
                  width=5).pack(side="left", padx=(10, 0))
        mk_button(top, "Down", lambda: self._disco_move(1), BTN_NORM,
                  width=6).pack(side="left", padx=4)
        mk_button(top, "Remove", self._disco_remove, BTN_DANGER,
                  width=9).pack(side="right")

        holder = tk.Frame(left, bg=C_BG2)
        holder.pack(fill="both", expand=True)
        vsb = tk.Scrollbar(holder)
        vsb.pack(side="right", fill="y")           # scrollbar FIRST
        cols = ("n", "title", "group", "year", "format", "songs", "shown")
        self.dtree = ttk.Treeview(holder, columns=cols, show="headings",
                                  selectmode="browse",
                                  yscrollcommand=vsb.set, height=10)
        self.dtree.pack(side="left", fill="both", expand=True)
        vsb.configure(command=self.dtree.yview)
        for c, txt, w, anchor in (("n", "#", 36, "e"),
                                  ("title", "Title", 190, "w"),
                                  ("group", "Group", 80, "w"),
                                  ("year", "Year", 46, "center"),
                                  ("format", "Format", 64, "w"),
                                  ("songs", "Songs", 46, "e"),
                                  ("shown", "Shown", 56, "center")):
            self.dtree.heading(c, text=txt, anchor=anchor)
            self.dtree.column(c, width=w, anchor=anchor,
                              stretch=(c == "title"))
        self.dtree.tag_configure("hidden", foreground=C_FG_DIM)
        self.dtree.bind("<<TreeviewSelect>>", self._disco_on_select)
        bind_mousewheel(self.dtree)

        self.l_dsum = tk.Label(left, text="", bg=C_BG2, fg=C_FG_DIM,
                               font=("Segoe UI", 8), anchor="w")
        self.l_dsum.pack(fill="x", pady=(4, 0))

        tk.Frame(left, bg=C_SEP, height=1).pack(fill="x", pady=8)
        tk.Label(left, text="The page  (discography.html)", bg=C_BG2,
                 fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w")
        self.v_show_disco = tk.BooleanVar(value=True)
        tk.Checkbutton(left, text="Show the discography page, and the #N "
                                  "numbers on the music page",
                       variable=self.v_show_disco, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       command=self._disco_site_changed).pack(anchor="w")
        hrow = tk.Frame(left, bg=C_BG2)
        hrow.pack(fill="x", pady=(4, 0))
        tk.Label(hrow, text="Heading ", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.e_disco_title = mk_entry(hrow)
        self.e_disco_title.pack(side="left", fill="x", expand=True)
        self.e_disco_title.bind("<FocusOut>",
                                lambda e: self._disco_site_changed())
        tk.Label(left, text="A few words above the releases (optional)",
                 bg=C_BG2, fg=C_FG, font=("Segoe UI", 9, "bold")
                 ).pack(anchor="w", pady=(8, 2))
        self.t_disco_intro = mk_text(left, height=3, font=("Segoe UI", 10))
        self.t_disco_intro.pack(fill="x")
        self.t_disco_intro.bind("<FocusOut>",
                                lambda e: self._disco_site_changed())

        brow = tk.Frame(left, bg=C_BG2)
        brow.pack(fill="x", pady=(10, 0))
        mk_button(brow, "Check matches", self._disco_check, BTN_INFO,
                  width=14).pack(side="left")
        mk_button(brow, "Open in browser",
                  lambda: self._open_built_page(DISCO_FILE), BTN_NORM,
                  width=15).pack(side="left", padx=6)

        # ---- right: one release
        right = tk.Frame(pane, bg=C_BG2, padx=14)
        pane.add(right, minsize=380)
        tk.Label(right, text="Release", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w", pady=(0, 4))
        self.l_dnum = tk.Label(right, text="", bg=C_BG2, fg=C_FG_DIM,
                               font=("Segoe UI", 8))
        self.l_dnum.pack(anchor="w")

        def lab(parent, text):
            return tk.Label(parent, text=text, bg=C_BG2, fg=C_FG,
                            font=("Segoe UI", 9, "bold"))

        def row_of(*pairs):
            """pairs of (label, field, width); the first field stretches."""
            r = tk.Frame(right, bg=C_BG2)
            r.pack(fill="x", pady=(6, 0))
            first = True
            for text, key, width in pairs:
                lab(r, ("" if first else "   ") + text + " ").pack(side="left")
                e = mk_entry(r, width=width) if width else mk_entry(r)
                if width:
                    e.pack(side="left")
                else:
                    e.pack(side="left", fill="x", expand=True)
                self.d_entries[key] = e
                first = False

        self.d_entries = {}
        row_of(("Title", "title", None))
        row_of(("Group", "group", None), ("Year", "year", 7),
               ("Format", "format", 11))
        row_of(("Recorded", "dates", None), ("Where", "where", 18))
        row_of(("Released", "released", None), ("Copies", "copies", 10))
        row_of(("Note", "note", None))
        for e in self.d_entries.values():
            e.bind("<Return>", lambda ev: self._disco_commit())
            e.bind("<FocusOut>", lambda ev: self._disco_commit())

        self.v_dhidden = tk.BooleanVar(value=False)
        tk.Checkbutton(right, text="Hidden - leave this release off the "
                                   "pages (it keeps its number)",
                       variable=self.v_dhidden, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       command=self._disco_commit).pack(anchor="w",
                                                        pady=(6, 0))

        crow = tk.Frame(right, bg=C_BG2)
        crow.pack(fill="x", pady=(8, 2))
        lab(crow, "Musicians & credits").pack(side="left")
        tk.Label(crow, text="   one per line;  *  or  *1  first = only the "
                            "songs marked the same",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left")
        self.t_dcred = mk_text(right, height=4, font=("Segoe UI", 10))
        self.t_dcred.pack(fill="x")
        self.t_dcred.bind("<FocusOut>", lambda e: self._disco_commit())

        wrow = tk.Frame(right, bg=C_BG2)
        wrow.pack(fill="x", pady=(10, 2))
        lab(wrow, "Tracklist").pack(side="left")
        tk.Label(wrow, text="   one song per line;  A)  or  B)  starts a side;"
                            "  *  *1  after a song marks it",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left")
        self.l_dcount = tk.Label(wrow, text="", bg=C_BG2, fg=C_FG_DIM,
                                 font=("Segoe UI", 8))
        self.l_dcount.pack(side="right")
        tw = tk.Frame(right, bg=C_BG2)
        tw.pack(fill="both", expand=True)
        tsb = tk.Scrollbar(tw)
        tsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_dtracks = mk_text(tw, height=10, yscrollcommand=tsb.set,
                                 font=("Segoe UI", 10), wrap="none")
        self.t_dtracks.pack(side="left", fill="both", expand=True)
        tsb.configure(command=self.t_dtracks.yview)
        bind_mousewheel(self.t_dtracks)
        self.t_dtracks.bind("<FocusOut>", lambda e: self._disco_commit())
        self.t_dtracks.bind("<KeyRelease>", lambda e: self._disco_count())
        try:
            pane.paneconfigure(right, stretch="always")
        except Exception:
            pass

    def _disco_row_values(self, i):
        r = self.project.discography[i]
        return (i + 1, r.get("title", ""), r.get("group", ""),
                r.get("year", ""), r.get("format", ""), disco_song_count(r),
                "hidden" if r.get("hidden") else "yes")

    def _disco_refresh(self, keep=None):
        """Fill the list from the project and show the selected release."""
        self._disco_cur = None
        self.dtree.delete(*self.dtree.get_children())
        rels = self.project.discography
        for i in range(len(rels)):
            self.dtree.insert("", "end", iid=str(i),
                              values=self._disco_row_values(i),
                              tags=(("hidden",) if rels[i].get("hidden")
                                    else ()))
        total = sum(disco_song_count(r) for r in rels)
        self.l_dsum.configure(text="%d release(s), %d song(s) in all"
                              % (len(rels), total) if rels else
                              "No releases yet - press Import CSV... or "
                              "Add release.")
        if rels:
            idx = min(max(keep or 0, 0), len(rels) - 1)
            self.dtree.selection_set(str(idx))
            self.dtree.see(str(idx))
        self._disco_load(None if not rels else
                         min(max(keep or 0, 0), len(rels) - 1))

    def _disco_sel(self):
        sel = self.dtree.selection()
        try:
            return int(sel[0]) if sel else None
        except ValueError:
            return None

    def _disco_on_select(self, _event=None):
        self._disco_commit()                  # the row we are leaving
        self._disco_load(self._disco_sel())

    def _disco_load(self, i):
        """Show release I (or an empty form) in the boxes."""
        self._disco_loading = True
        try:
            rels = self.project.discography
            ok = i is not None and 0 <= i < len(rels)
            self._disco_cur = i if ok else None
            r = rels[i] if ok else new_release()
            for k, e in self.d_entries.items():
                e.delete(0, "end")
                e.insert(0, r.get(k, ""))
            self.t_dtracks.delete("1.0", "end")
            self.t_dtracks.insert("1.0", "\n".join(r.get("tracks", [])))
            self.t_dcred.delete("1.0", "end")
            self.t_dcred.insert("1.0", r.get("credits", ""))
            self.v_dhidden.set(bool(r.get("hidden")))
            self.l_dnum.configure(text=("Release #%d" % (i + 1)) if ok else
                                  "Nothing selected")
            self._disco_count()
        finally:
            self._disco_loading = False

    def _disco_count(self):
        lines = [x.strip() for x in
                 self.t_dtracks.get("1.0", "end-1c").splitlines() if x.strip()]
        n = sum(1 for x in lines if not SIDE_MARK_RE.match(x))
        self.l_dcount.configure(text="%d song(s)" % n)

    def _disco_commit(self):
        """Write the boxes back into the release they were loaded for."""
        i = self._disco_cur
        rels = self.project.discography
        if self._disco_loading or i is None or not (0 <= i < len(rels)):
            return
        r = rels[i]
        new = {k: e.get().strip() for k, e in self.d_entries.items()}
        new["released"] = norm_date(new.get("released", ""))   # 1/12 1989 -> ISO
        new["credits"] = self.t_dcred.get("1.0", "end-1c").strip()
        # blank lines are kept (one at a time) and a blank is put above B)
        new["tracks"] = normalize_tracks(
            self.t_dtracks.get("1.0", "end-1c").splitlines())
        new["hidden"] = bool(self.v_dhidden.get())
        changed = not all(r.get(k, "" if k != "hidden" else False) == v
                          for k, v in new.items())
        if changed:
            r.update(new)
            self.project.dirty = True
            try:
                self.dtree.item(str(i), values=self._disco_row_values(i),
                                tags=(("hidden",) if r.get("hidden") else ()))
            except tk.TclError:
                pass
        # show what was tidied (the date, the blank above B) in the boxes
        self._disco_loading = True
        try:
            if self.d_entries["released"].get().strip() != r["released"]:
                self.d_entries["released"].delete(0, "end")
                self.d_entries["released"].insert(0, r["released"])
            if self.t_dtracks.get("1.0", "end-1c") != "\n".join(r["tracks"]):
                self.t_dtracks.delete("1.0", "end")
                self.t_dtracks.insert("1.0", "\n".join(r["tracks"]))
        finally:
            self._disco_loading = False
        self._update_titlebar()

    def _disco_site_changed(self):
        """The page switches (show / heading / intro) -> the project."""
        site = self.project.site
        new = {"show_discography": bool(self.v_show_disco.get()),
               "disco_title": self.e_disco_title.get().strip()
               or "Discography",
               "disco_intro": self.t_disco_intro.get("1.0", "end-1c").strip()}
        if any(site.get(k) != v for k, v in new.items()):
            site.update(new)
            self.project.dirty = True
            self._update_titlebar()

    def _disco_import(self):
        self._disco_commit()
        start = self.settings.get("disco_csv", "")
        p = filedialog.askopenfilename(
            title="Pick the discography table (CSV)",
            initialdir=os.path.dirname(start) if start else None,
            initialfile=os.path.basename(start) if start else "",
            filetypes=[("CSV table", "*.csv"), ("All files", "*.*")])
        if not p:
            return
        try:
            rels = parse_discography_csv(p)
        except Exception as exc:
            log_exception("disco import", exc)
            messagebox.showerror(APP_NAME, "Could not read the table:\n\n%s"
                                 % exc, parent=self.root)
            return
        if self.project.discography and not messagebox.askyesno(
                APP_NAME,
                "Replace the %d release(s) in the list with the %d from "
                "this file?\n\nWhatever you changed by hand in the list is "
                "lost (the project's old version is kept in Backups the "
                "next time you save)." % (len(self.project.discography),
                                          len(rels)),
                icon="warning", default="no", parent=self.root):
            return
        self.project.discography = rels
        self.project.dirty = True
        self.settings["disco_csv"] = p
        save_settings(self.settings)
        self._disco_refresh(0)
        self._update_titlebar()
        rel_of, _links, _how = match_discography(rels, self.project.tracks)
        nhid = sum(1 for r in rels if r.get("hidden"))
        self.status("Imported %d release(s), %d song(s); %d song(s) on the "
                    "page have a release number%s"
                    % (len(rels), sum(disco_song_count(r) for r in rels),
                       len(rel_of),
                       "; %d release(s) by another group are hidden (Shown "
                       "column)" % nhid if nhid else ""), C_OK)
        toast(self.root, "%d releases" % len(rels))

    def _disco_add(self):
        self._disco_commit()
        self.project.discography.append(new_release())
        self.project.dirty = True
        n = len(self.project.discography) - 1
        self._disco_refresh(n)
        self._update_titlebar()
        self.d_entries["title"].focus_set()

    def _disco_remove(self):
        i = self._disco_sel()
        if i is None:
            return
        r = self.project.discography[i]
        if not messagebox.askyesno(
                APP_NAME, "Remove release #%d  \"%s\"  (%d songs)?\n\nThe "
                "releases after it move up one number."
                % (i + 1, r.get("title", ""), disco_song_count(r)),
                icon="warning", default="no", parent=self.root):
            return
        self._disco_cur = None                # nothing to write back
        del self.project.discography[i]
        self.project.dirty = True
        self._disco_refresh(i)
        self._update_titlebar()

    def _disco_move(self, d):
        self._disco_commit()
        i = self._disco_sel()
        rels = self.project.discography
        if i is None or not (0 <= i + d < len(rels)):
            return
        rels[i], rels[i + d] = rels[i + d], rels[i]
        self.project.dirty = True
        self._disco_refresh(i + d)
        self._update_titlebar()

    def _disco_check_text(self):
        """The report: what was matched, and every match that was a guess."""
        self._disco_commit()
        self._editor_to_track()
        rels = self.project.discography
        rel_of, _links, how = match_discography(rels, self.project.tracks)
        shown = [t for t in self.project.tracks if not t.get("hidden")]
        lines = ["%d of the %d songs on the page are on at least one "
                 "release." % (len(rel_of), len(shown)), ""]
        if how:
            lines += ["MATCHED BY SIMILARITY - check these (fix a wrong one "
                      "by spelling the song the same on the release):", ""]
            for kind, num, line, title in how:
                lines.append("  #%-3d \"%s\"  =  page: \"%s\"   (%s)"
                             % (num, line, title, kind))
            lines.append("")
        self._disco_only_hidden = self._songs_only_on_hidden()
        if self._disco_only_hidden:
            lines += ["ON THE MUSIC PAGE, BUT ONLY ON HIDDEN RELEASES - "
                      "press 'Hide these songs' to leave them off the music "
                      "page too (or hide them one by one on the Tracks tab):",
                      ""]
            for i in self._disco_only_hidden:
                lines.append("  " + self.project.tracks[i].get("title", ""))
            lines.append("")
        lines += ["SONG ON THE PAGE  ->  RELEASES", ""]
        for i, t in enumerate(self.project.tracks):
            if t.get("hidden"):
                continue
            nums = rel_of.get(i)
            lines.append("  %-52s %s" % (t.get("title", "")[:52],
                                         " ".join("#%d" % n for n in nums)
                                         if nums else "-"))
        return "\n".join(lines)

    def _songs_only_on_hidden(self):
        """Indexes of the visible songs that are on hidden releases only
        (Loss songs that ended up on the Issus barn music page)."""
        rels = self.project.discography
        seen, _l, _h = match_discography(rels, self.project.tracks)
        every, _l2, _h2 = match_discography(rels, self.project.tracks,
                                            include_hidden=True)
        return [i for i in sorted(every)
                if i not in seen and not self.project.tracks[i].get("hidden")]

    def _disco_hide_songs(self):
        """Hide the songs that are only on hidden releases (Tracks tab flag)."""
        idx = self._songs_only_on_hidden()
        if not idx:
            messagebox.showinfo(APP_NAME, "Nothing to hide.",
                                parent=self._disco_win)
            return
        if not messagebox.askyesno(
                APP_NAME, "Hide these %d song(s) from the music page?\n\n"
                "They stay in the project - untick 'Hidden' on the Tracks tab "
                "to bring one back." % len(idx), parent=self._disco_win):
            return
        for i in idx:
            self.project.tracks[i]["hidden"] = True
        self.project.dirty = True
        self._refresh_tree()
        self._disco_win_fill()
        self.status("%d song(s) hidden from the music page" % len(idx), C_OK)

    def _disco_check(self):
        """The match report in a window that stays open beside the main one.

        Deliberately NOT modal (no grab_set): he edits the releases in the
        main window and presses Refresh to see the effect.  Escape closes it.
        """
        if not self.project.discography:
            messagebox.showinfo(APP_NAME, "There are no releases yet.",
                                parent=self.root)
            return
        win = getattr(self, "_disco_win", None)
        try:
            if win is not None and win.winfo_exists():
                self._disco_win_fill()
                win.deiconify()
                win.lift()
                return
        except tk.TclError:
            pass
        top = tk.Toplevel(self.root)
        self._disco_win = top
        top.title("MusicSite - discography matches")
        top.configure(bg=C_BG3)
        top.geometry("820x600")
        top.transient(self.root)               # stays above the main window
        bar = tk.Frame(top, bg=C_BG3)
        bar.pack(fill="x", padx=12, pady=(10, 0))
        mk_button(bar, "Refresh", self._disco_win_fill, BTN_MAIN,
                  width=10).pack(side="left")
        mk_button(bar, "Hide these songs", self._disco_hide_songs, BTN_WARN,
                  width=15).pack(side="left", padx=6)
        mk_button(bar, "Close", top.destroy, BTN_NORM,
                  width=8).pack(side="left")
        tk.Label(bar, text="You can keep editing in the main window; "
                           "press Refresh to check again.", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=8)
        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=12, pady=12)
        sb = tk.Scrollbar(wrap)
        sb.pack(side="right", fill="y")            # scrollbar FIRST
        self._disco_txt = mk_text(wrap, yscrollcommand=sb.set,
                                  font=("Consolas", 9), wrap="none")
        self._disco_txt.pack(side="left", fill="both", expand=True)
        sb.configure(command=self._disco_txt.yview)
        bind_mousewheel(self._disco_txt)
        top.bind("<Escape>", lambda e: top.destroy())
        self._disco_win_fill()
        top.focus_force()

    def _disco_win_fill(self):
        """(Re)write the report, keeping the scroll position."""
        try:
            txt = self._disco_txt
            pos = txt.yview()[0]
            txt.configure(state="normal")
            txt.delete("1.0", "end")
            txt.insert("1.0", self._disco_check_text())
            txt.configure(state="disabled")
            txt.yview_moveto(pos)
        except tk.TclError:
            pass

    def _open_built_page(self, fname):
        """Show a page of the last build in HIS browser (or offer to build)."""
        self._gui_to_project()
        out = os.path.join(self._outdir(), fname)
        if not os.path.isfile(out):
            if messagebox.askyesno(APP_NAME,
                                   "%s has not been built yet.\n\nBuild the "
                                   "pages now?" % fname, parent=self.root):
                self.do_build()
            return
        open_in_browser(out)
        self.status("Opened %s in your browser" % fname)

    # ================================================ DEL 14g - ABOUT ME TAB
    def _tab_about(self):
        f = tk.Frame(self.nb, bg=C_BG2, padx=18, pady=14)
        self.nb.add(f, text="  7. About me  ")

        tk.Label(f, text="About me  (about.html)", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w")
        tk.Label(f, text="A page of its own, with the same menu as the "
                         "others.  Fill it in whenever you like - until then "
                         "it says \"This page is coming soon.\"",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                 wraplength=860, justify="left").pack(anchor="w",
                                                      pady=(0, 10))
        self.v_show_about = tk.BooleanVar(value=True)
        tk.Checkbutton(f, text="Show the about page (built with the others, "
                               "and in the menu)",
                       variable=self.v_show_about, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG, font=("Segoe UI", 9),
                       command=self._about_changed).pack(anchor="w")

        tk.Label(f, text="Heading  (also the name in the menu)", bg=C_BG2,
                 fg=C_FG, font=("Segoe UI", 9, "bold")
                 ).pack(anchor="w", pady=(10, 2))
        self.e_about_title = mk_entry(f, font=("Segoe UI", 11))
        self.e_about_title.pack(fill="x")
        self.e_about_title.bind("<FocusOut>", lambda e: self._about_changed())

        tk.Label(f, text="Picture  (an address, optional)", bg=C_BG2,
                 fg=C_FG, font=("Segoe UI", 9, "bold")
                 ).pack(anchor="w", pady=(10, 2))
        self.e_about_image = mk_entry(f)
        self.e_about_image.pack(fill="x")
        self.e_about_image.bind("<FocusOut>", lambda e: self._about_changed())

        tk.Label(f, text="Your text  (an empty line starts a new paragraph)",
                 bg=C_BG2, fg=C_FG, font=("Segoe UI", 9, "bold")
                 ).pack(anchor="w", pady=(10, 2))
        tw = tk.Frame(f, bg=C_BG2)
        tw.pack(fill="both", expand=True)
        tsb = tk.Scrollbar(tw)
        tsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_about_text = mk_text(tw, height=12, yscrollcommand=tsb.set,
                                    font=("Segoe UI", 10))
        self.t_about_text.pack(side="left", fill="both", expand=True)
        tsb.configure(command=self.t_about_text.yview)
        bind_mousewheel(self.t_about_text)
        self.t_about_text.bind("<FocusOut>", lambda e: self._about_changed())

        brow = tk.Frame(f, bg=C_BG2)
        brow.pack(fill="x", pady=(10, 0))
        mk_button(brow, "Open in browser",
                  lambda: self._open_built_page(ABOUT_FILE), BTN_NORM,
                  width=15).pack(side="left")

    def _about_changed(self):
        site = self.project.site
        new = {"show_aboutpage": bool(self.v_show_about.get()),
               "aboutpage_title": self.e_about_title.get().strip()
               or "About me",
               "aboutpage_image": self.e_about_image.get().strip(),
               "aboutpage_text": self.t_about_text.get("1.0", "end-1c"
                                                       ).strip()}
        if any(site.get(k) != v for k, v in new.items()):
            site.update(new)
            self.project.dirty = True
            self._update_titlebar()

    # ================================================== DEL 14e - UPLOAD TAB
    def _tab_upload(self):
        f = tk.Frame(self.nb, bg=C_BG2, padx=16, pady=14)
        self.nb.add(f, text="  5. Upload  ")
        f.columnconfigure(1, weight=1)

        tk.Label(f, text="My folders here  vs  the folders online",
                 bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).grid(row=0, column=0,
                                                     columnspan=3, sticky="w")
        tk.Label(f, text="Point at the folder your master files live in. "
                         "MusicSite compares it with the cloud folder and "
                         "says what has to go up.",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).grid(row=1, column=0,
                                                      columnspan=3,
                                                      sticky="w",
                                                      pady=(0, 12))

        tk.Label(f, text="Local folder(s)", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).grid(row=2, column=0,
                                                    sticky="nw", pady=4,
                                                    padx=(0, 10))
        lframe = tk.Frame(f, bg=C_BG2)
        lframe.grid(row=2, column=1, sticky="we", pady=4)
        lbox = tk.Frame(lframe, bg=C_BG2)
        lbox.pack(side="left", fill="both", expand=True)
        lsb = tk.Scrollbar(lbox)
        lsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_local = mk_text(lbox, height=3, yscrollcommand=lsb.set,
                               font=("Segoe UI", 10))
        self.t_local.pack(side="left", fill="both", expand=True)
        lsb.configure(command=self.t_local.yview)
        bind_mousewheel(self.t_local)
        lbtn = tk.Frame(lframe, bg=C_BG2)
        lbtn.pack(side="left", padx=(6, 0), fill="y")
        mk_button(lbtn, "Browse...", self._browse_local, BTN_NORM,
                  width=10).pack(side="top")
        mk_button(lbtn, "Compare", self.do_sync_compare, BTN_MAIN,
                  width=10).pack(side="top", pady=(4, 0))
        tk.Label(f, text="ONE PER LINE, same order as the\n"
                         "groups on the Source tab, or\n"
                         "\"Name | C:\\path\" to bind it to\n"
                         "one group by name.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                 justify="left").grid(row=2, column=2, sticky="nw",
                                      padx=(10, 0), pady=4)

        opt = tk.Frame(f, bg=C_BG2)
        opt.grid(row=3, column=0, columnspan=3, sticky="w", pady=(8, 0))
        self.v_deep = tk.BooleanVar(value=True)
        tk.Checkbutton(opt, text="Deep check (ask the cloud for the exact "
                                 "size and time of every file - slower, but "
                                 "it is the only way to be sure)",
                       variable=self.v_deep, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(anchor="w")
        self.v_autotag = tk.BooleanVar(value=True)
        tk.Checkbutton(opt, text="Write title, band, words ... into my mp3 "
                                 "files first (tags), so the files that go "
                                 "up carry them",
                       variable=self.v_autotag, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(anchor="w")
        opt2 = tk.Frame(f, bg=C_BG2)
        opt2.grid(row=4, column=0, columnspan=3, sticky="w")
        # Covers and lyrics are ALWAYS compared - they are part of a song, and
        # a missing cover is exactly the kind of thing you forget.  Whether
        # they are worth looking at in the list is a different question, and
        # that one is answered by the "Hide from the list" row further down.
        tk.Label(opt2, text="Songs, covers and lyrics are always compared.",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(side="left",
                                                      padx=(0, 16))
        tk.Label(opt2, text="Ignore a difference smaller than",
                 bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self.e_tol = mk_entry(opt2, width=4)
        self.e_tol.pack(side="left", padx=6)
        tk.Label(opt2, text="minutes", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")

        srow = tk.Frame(f, bg=C_BG2)
        srow.grid(row=5, column=0, columnspan=3, sticky="we", pady=(10, 0))
        tk.Label(srow, text="Temp_to_drive", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        self.e_stage = mk_entry(srow)
        self.e_stage.pack(side="left", fill="x", expand=True, padx=(10, 6))
        mk_button(srow, "Browse...", self._browse_stage, BTN_NORM,
                  width=10).pack(side="left")
        mk_button(srow, "Open", lambda: open_in_explorer(self._stagedir()),
                  BTN_NORM, width=8).pack(side="left", padx=(6, 0))

        brow = tk.Frame(f, bg=C_BG2)
        brow.grid(row=6, column=0, columnspan=3, sticky="we", pady=(12, 6))
        mk_button(brow, "Compare with the cloud", self.do_sync_compare,
                  BTN_MAIN, width=22).pack(side="left")
        mk_button(brow, "Clean comparison", lambda: self.do_sync_compare(True),
                  BTN_INFO, width=16).pack(side="left", padx=6)
        mk_button(brow, "Copy ticked to Temp_to_drive", self.do_sync_stage,
                  BTN_WARN, width=27).pack(side="left")
        mk_button(brow, "Open the cloud folder", self._sync_open_cloud,
                  BTN_NORM, width=19).pack(side="left", padx=6)
        mk_button(brow, "Stop", self._sync_stop, BTN_DANGER,
                  width=6).pack(side="left")
        mk_button(brow, "Tag mp3...", self.show_tag_dialog, BTN_INFO,
                  width=10).pack(side="left", padx=(6, 0))
        mk_button(brow, "WAV to MP3...", self.show_wav_dialog, BTN_INFO,
                  width=13).pack(side="left", padx=(6, 0))
        mk_button(brow, "Help", self.show_help, BTN_INFO,
                  width=6).pack(side="left", padx=6)
        self.l_mem = tk.Label(f, text="", bg=C_BG2, fg=C_FG_DIM,
                              font=("Segoe UI", 8), anchor="w")
        self.l_mem.grid(row=7, column=0, columnspan=3, sticky="w")

        trow = tk.Frame(f, bg=C_BG2)
        trow.grid(row=8, column=0, columnspan=3, sticky="w")
        tk.Label(trow, text="Tick:", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(0, 6))
        for txt, mode in (("what has to go up", "upload"),
                          ("all", "all"), ("none", "none")):
            mk_button(trow, txt, lambda m=mode: self._sync_tick(m),
                      BTN_NORM).pack(side="left", padx=(0, 6))
        tk.Label(trow, text="  Marked rows:", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(6, 6))
        mk_button(trow, "I have uploaded these",
                  lambda: self._mark_uploaded(True), BTN_WARN,
                  width=21).pack(side="left")
        mk_button(trow, "Undo", lambda: self._mark_uploaded(False),
                  BTN_NORM, width=6).pack(side="left", padx=(6, 0))
        self.v_clear = tk.BooleanVar(value=True)
        tk.Checkbutton(trow, text="empty Temp_to_drive first",
                       variable=self.v_clear, bg=C_BG2, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG2,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(side="left", padx=(10, 0))

        # Hiding is only about the LIST.  Everything stays compared, stays
        # counted and - if it is ticked - still goes to Temp_to_drive; his
        # Cover folder alone holds 478 files online, and without this the
        # four rows that matter drown among them.
        hrow = tk.Frame(f, bg=C_BG2)
        hrow.grid(row=9, column=0, columnspan=3, sticky="w", pady=(6, 0))
        tk.Label(hrow, text="Hide from the list:", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(0, 8))
        self.v_only_todo = tk.BooleanVar(value=False)
        self.v_hide_cover = tk.BooleanVar(value=False)
        self.v_hide_text = tk.BooleanVar(value=False)
        for txt, var in (("what is already up to date", self.v_only_todo),
                         ("covers", self.v_hide_cover),
                         ("lyrics", self.v_hide_text)):
            tk.Checkbutton(hrow, text=txt, variable=var,
                           command=self._sync_fill, bg=C_BG2, fg=C_FG,
                           selectcolor=C_FIELD, activebackground=C_BG2,
                           activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(side="left",
                                                      padx=(0, 14))

        wrap = tk.Frame(f, bg=C_BG2)
        wrap.grid(row=10, column=0, columnspan=3, sticky="nsew",
                  pady=(10, 0))
        f.rowconfigure(10, weight=1)
        cols = ("status", "kind", "file", "mine", "online", "note")
        tsb = tk.Scrollbar(wrap)
        tsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.sync_tree = ttk.Treeview(wrap, columns=cols, show="tree headings",
                                      yscrollcommand=tsb.set, height=10,
                                      selectmode="extended")
        self.sync_tree.pack(side="left", fill="both", expand=True)
        tsb.configure(command=self.sync_tree.yview)
        self.sync_tree.heading("#0", text="Up")
        self.sync_tree.column("#0", width=38, minwidth=38, stretch=False,
                              anchor="center")
        for c, txt, w, anchor in (
                ("status", "Status", 150, "w"),
                ("kind", "Kind", 60, "w"),
                ("file", "File", 260, "w"),
                ("mine", "Here", 150, "w"),
                ("online", "Online", 150, "w"),
                ("note", "Note", 320, "w")):
            self.sync_tree.heading(c, text=txt)
            self.sync_tree.column(c, width=w, anchor=anchor,
                                  stretch=(c == "note"))
        self.sync_tree.tag_configure(STATUS_NEW, foreground=C_OK)
        self.sync_tree.tag_configure(STATUS_CHANGED, foreground=C_WARN)
        self.sync_tree.tag_configure(STATUS_NEWER, foreground=C_WARN)
        self.sync_tree.tag_configure(STATUS_STAGED, foreground=C_ACCENT)
        self.sync_tree.tag_configure(STATUS_ASSUMED, foreground="#b48ead")
        self.sync_tree.tag_configure(STATUS_CHECK, foreground=C_ACCENT)
        self.sync_tree.tag_configure(STATUS_SAME, foreground=C_FG_DIM)
        self.sync_tree.tag_configure(STATUS_ONLINE, foreground=C_FG_DIM)
        self.sync_tree.bind("<Button-1>", self._sync_click)
        self.sync_tree.bind("<space>", self._sync_space)
        self.sync_tree.bind("<Double-1>", self._sync_double)
        bind_mousewheel(self.sync_tree)

        self.l_syncsum = tk.Label(f, text="Nothing compared yet.", bg=C_BG2,
                                  fg=C_FG_DIM, font=("Segoe UI", 9, "bold"),
                                  anchor="w")
        self.l_syncsum.grid(row=11, column=0, columnspan=3, sticky="we",
                            pady=(8, 2))

        lw = tk.Frame(f, bg=C_BG2)
        lw.grid(row=12, column=0, columnspan=3, sticky="we")
        gsb = tk.Scrollbar(lw)
        gsb.pack(side="right", fill="y")           # scrollbar FIRST
        self.t_sync = mk_text(lw, height=6, yscrollcommand=gsb.set,
                              font=("Consolas", 9))
        self.t_sync.pack(side="left", fill="both", expand=True)
        gsb.configure(command=self.t_sync.yview)
        bind_mousewheel(self.t_sync)

        self.sync_items = []
        self.sync_stop = False

    def _browse_local(self):
        d = filedialog.askdirectory(
            title="Pick the folder your master files live in")
        if not d:
            return
        cur = self.t_local.get("1.0", "end-1c").strip()
        self.t_local.delete("1.0", "end")
        self.t_local.insert("1.0", (cur + "\n" + d) if cur else d)

    def show_tag_dialog(self):
        """Tag the mp3 files by hand: check first, then write."""
        if not self._guard():
            return
        self._editor_to_track()
        self._gui_to_project()
        s = self.project.source
        top = tk.Toplevel(self.root)
        top.title("MusicSite - tags in the mp3 files")
        top.configure(bg=C_BG3)
        top.geometry("820x560")
        tk.Label(top, text="Tags in the mp3 files", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w", padx=14,
                                                      pady=(12, 0))
        tk.Label(top, text="Title, band, year, words by, the words, notes "
                           "(and a cover if you like) are written INTO the "
                           "mp3 files in your 'Local folder(s)'.  The sound "
                           "is not touched; a file that is already right is "
                           "not written at all.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9, "italic"),
                 justify="left", wraplength=780).pack(anchor="w", padx=14,
                                                       pady=(0, 6))
        v_cover = tk.BooleanVar(value=bool(s.get("tag_cover", False)))
        v_keep = tk.BooleanVar(value=bool(s.get("tag_keep_original", True)))
        for txt, var in (("Put the cover picture inside the file too "
                          "(scaled to 700 px)", v_cover),
                         ("Keep a copy of the untouched file the first time "
                          "(Backups\\MP3_originals)", v_keep)):
            tk.Checkbutton(top, text=txt, variable=var, bg=C_BG3, fg=C_FG,
                           selectcolor=C_FIELD, activebackground=C_BG3,
                           activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(anchor="w", padx=14)
        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=14, pady=8)
        sb = tk.Scrollbar(wrap)
        sb.pack(side="right", fill="y")                # scrollbar FIRST
        log_w = mk_text(wrap, yscrollcommand=sb.set, font=("Consolas", 9))
        log_w.pack(side="left", fill="both", expand=True)
        sb.configure(command=log_w.yview)
        bind_mousewheel(log_w)
        if not MUTAGEN_OK:
            log_w.insert("end", "The 'mutagen' package is missing.\n"
                                "Install it once:   pip install mutagen\n")
        cfg = dict(s)
        tracks = [dict(t) for t in self.project.tracks]
        site = dict(self.project.site)
        q = queue.Queue()
        state = {"busy": False}

        def run(write):
            if state["busy"]:
                return
            state["busy"] = True
            s["tag_cover"] = bool(v_cover.get())
            s["tag_keep_original"] = bool(v_keep.get())
            log_w.delete("1.0", "end")
            log_w.insert("end", "Working ...\n")

            def work():
                try:
                    r = tag_local_mp3s(cfg, tracks, site, write,
                                       bool(v_cover.get()),
                                       bool(v_keep.get()))
                    q.put("\n".join(([r.error] if r.error else [])
                                    + r.report))
                except Exception as exc:
                    log_exception("tag dialog", exc)
                    q.put("FAILED: %s" % exc)
            threading.Thread(target=work, daemon=True).start()

        def poll():
            try:
                txt = q.get_nowait()
                log_w.delete("1.0", "end")
                log_w.insert("end", txt.strip() + "\n")
                state["busy"] = False
            except queue.Empty:
                pass
            if top.winfo_exists():
                top.after(150, poll)

        row = tk.Frame(top, bg=C_BG3)
        row.pack(fill="x", padx=14, pady=(0, 12))
        mk_button(row, "Check (changes nothing)", lambda: run(False),
                  BTN_NORM, width=22).pack(side="left")
        mk_button(row, "Write the tags", lambda: run(True), BTN_MAIN,
                  width=16).pack(side="left", padx=6)
        mk_button(row, "Open the backups",
                  lambda: open_in_explorer(BAK_MP3_DIR), BTN_NORM,
                  width=16).pack(side="left")
        mk_button(row, "Close", top.destroy, BTN_INFO,
                  width=10).pack(side="right")
        dialog_setup(top, self.root)
        poll()

    def show_wav_dialog(self):
        """WAV -> MP3 with ffmpeg; the last settings are remembered."""
        if not self._guard():
            return
        self._editor_to_track()
        self._gui_to_project()
        cfg = dict(self.project.source)
        tracks = [dict(t) for t in self.project.tracks]
        site = dict(self.project.site)
        opt = dict(WAV2MP3_DEFAULT)
        opt.update(self.settings.get("wav2mp3") or {})
        folder = (cfg.get("audio_folder") or "MP3").strip() or "MP3"
        if not opt.get("out_dir"):
            for line in (cfg.get("local_folders") or "").splitlines():
                line = line.split("|")[-1].strip().strip('"')
                if line and not line.startswith("#"):
                    opt["out_dir"] = os.path.join(line, folder)
                    break

        top = tk.Toplevel(self.root)
        top.title("MusicSite - WAV to MP3")
        top.configure(bg=C_BG3)
        top.geometry("980x700")
        tk.Label(top, text="WAV  ->  MP3", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w", padx=14,
                                                      pady=(10, 0))
        l_ff = tk.Label(top, text="", bg=C_BG3, fg=C_FG_DIM,
                        font=("Segoe UI", 8), anchor="w")
        l_ff.pack(fill="x", padx=14)

        def ffmpeg_path():
            return find_ffmpeg(opt.get("ffmpeg", ""))

        def show_ff():
            p = ffmpeg_path()
            l_ff.configure(text=("ffmpeg: " + p) if p else
                           "ffmpeg NOT FOUND - press 'Find ffmpeg...' (it "
                           "lives in Helpfiles\\1---Movie)",
                           fg=C_FG_DIM if p else C_ERR)

        def pick_ff():
            p = filedialog.askopenfilename(
                parent=top, title="Where is ffmpeg.exe?",
                filetypes=[("ffmpeg", "ffmpeg*.exe ffmpeg"), ("all", "*.*")])
            if p:
                opt["ffmpeg"] = p
                show_ff()

        # ---- the files
        srcs = []                                  # full paths, in order
        v_hide = tk.BooleanVar(value=bool(opt.get("hide_have", True)))
        v_rec = tk.BooleanVar(value=bool(opt.get("recurse", True)))
        v_filter = tk.StringVar()
        v_out = tk.StringVar(value=opt.get("out_dir", ""))

        fr = tk.Frame(top, bg=C_BG3)
        fr.pack(fill="both", expand=True, padx=14, pady=(6, 0))
        bar = tk.Frame(fr, bg=C_BG3)
        bar.pack(fill="x")

        def add_paths(paths):
            n0 = len(srcs)
            have = {s.casefold() for s in srcs}
            for p in find_wavs(paths, bool(v_rec.get())):
                if p.casefold() not in have:
                    srcs.append(p)
            fill()
            toast(top, "%d file(s) added" % (len(srcs) - n0), 900)

        def add_files():
            ps = filedialog.askopenfilenames(
                parent=top, title="Pick the WAV files",
                initialdir=opt.get("last_wav_dir") or None,
                filetypes=[("Audio", "*.wav *.flac *.aif *.aiff"),
                           ("all", "*.*")])
            if ps:
                opt["last_wav_dir"] = os.path.dirname(ps[0])
                add_paths(list(ps))

        def add_folder():
            d = filedialog.askdirectory(
                parent=top, title="Pick a folder with WAV files",
                initialdir=opt.get("last_wav_dir") or None)
            if d:
                opt["last_wav_dir"] = d
                add_paths([d])

        mk_button(bar, "Add files...", add_files, BTN_MAIN,
                  width=12).pack(side="left")
        mk_button(bar, "Add folder...", add_folder, BTN_MAIN,
                  width=12).pack(side="left", padx=6)
        tk.Checkbutton(bar, text="with sub-folders", variable=v_rec,
                       bg=C_BG3, fg=C_FG, selectcolor=C_FIELD,
                       activebackground=C_BG3, activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(side="left", padx=(0, 10))
        mk_button(bar, "Remove selected", lambda: remove(), BTN_NORM,
                  width=15).pack(side="left")
        mk_button(bar, "Clear", lambda: (srcs.clear(), fill()), BTN_NORM,
                  width=7).pack(side="left", padx=6)
        mk_button(bar, "Find ffmpeg...", pick_ff, BTN_NORM,
                  width=13).pack(side="right")

        bar2 = tk.Frame(fr, bg=C_BG3)
        bar2.pack(fill="x", pady=(4, 2))
        tk.Checkbutton(bar2, text="hide those that already have an mp3 there",
                       variable=v_hide, command=lambda: fill(), bg=C_BG3,
                       fg=C_FG, selectcolor=C_FIELD, activebackground=C_BG3,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(side="left")
        tk.Label(bar2, text="   name contains", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        e_filter = mk_entry(bar2, textvariable=v_filter, width=22)
        e_filter.pack(side="left", padx=6)
        v_filter.trace_add("write", lambda *_: fill())
        l_count = tk.Label(bar2, text="", bg=C_BG3, fg=C_FG_DIM,
                           font=("Segoe UI", 9))
        l_count.pack(side="right")

        tw = tk.Frame(fr, bg=C_BG3)
        tw.pack(fill="both", expand=True)
        tsb = tk.Scrollbar(tw)
        tsb.pack(side="right", fill="y")               # scrollbar FIRST
        tree = ttk.Treeview(tw, columns=("status", "file", "where"),
                            show="headings", height=9,
                            yscrollcommand=tsb.set, selectmode="extended")
        tree.pack(side="left", fill="both", expand=True)
        tsb.configure(command=tree.yview)
        for c, txt, w in (("status", "Status", 150), ("file", "File", 300),
                          ("where", "Folder", 420)):
            tree.heading(c, text=txt)
            tree.column(c, width=w, anchor="w", stretch=(c == "where"))
        tree.tag_configure("new", foreground=C_OK)
        tree.tag_configure("newer", foreground=C_WARN)
        tree.tag_configure("have", foreground=C_FG_DIM)
        bind_mousewheel(tree)
        STT = {"new": "NEW - no mp3 yet", "newer": "wav is NEWER",
               "have": "has an mp3"}

        def fill(*_):
            tree.delete(*tree.get_children())
            out = v_out.get().strip()
            flt = v_filter.get().strip().casefold()
            shown = 0
            c = {"new": 0, "newer": 0, "have": 0}
            for i, s in enumerate(srcs):
                kind, _dst = wav_status(s, out) if out else ("new", "")
                c[kind] += 1
                if v_hide.get() and kind == "have":
                    continue
                if flt and flt not in os.path.basename(s).casefold():
                    continue
                shown += 1
                tree.insert("", "end", iid=str(i), tags=(kind,),
                            values=(STT[kind], os.path.basename(s),
                                    os.path.dirname(s)))
            l_count.configure(
                text="%d listed, %d shown:  %d new, %d newer, %d done"
                     % (len(srcs), shown, c["new"], c["newer"], c["have"]))

        def remove():
            gone = {int(i) for i in tree.selection()}
            srcs[:] = [s for i, s in enumerate(srcs) if i not in gone]
            fill()

        # ---- where to
        orow = tk.Frame(top, bg=C_BG3)
        orow.pack(fill="x", padx=14, pady=(6, 0))
        tk.Label(orow, text="Put the mp3 files in", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        e_out = mk_entry(orow, textvariable=v_out)
        e_out.pack(side="left", fill="x", expand=True, padx=(10, 6))
        v_out.trace_add("write", lambda *_: fill())

        def browse_out():
            d = filedialog.askdirectory(parent=top,
                                        title="Where should the mp3 files go?",
                                        initialdir=v_out.get() or None)
            if d:
                v_out.set(d)
        mk_button(orow, "Browse...", browse_out, BTN_NORM,
                  width=10).pack(side="left")

        # ---- the settings
        sf = tk.LabelFrame(top, text=" Settings (remembered) ", bg=C_BG3,
                           fg=C_ACCENT, font=("Segoe UI", 9, "bold"))
        sf.pack(fill="x", padx=14, pady=(8, 0))
        v_mode = tk.StringVar(value=opt.get("mode", "CBR"))
        v_br = tk.StringVar(value=str(opt.get("bitrate", "192")))
        v_q = tk.StringVar(value=str(opt.get("vbr_q", "4")))
        v_sr = tk.StringVar(value=str(opt.get("sample_rate", "0")))
        v_ch = tk.StringVar(value=str(opt.get("channels", "0")))
        v_norm = tk.BooleanVar(value=bool(opt.get("normalize", False)))
        v_ex = tk.StringVar(value=opt.get("existing", "newer"))
        v_tag = tk.BooleanVar(value=bool(opt.get("tag_after", True)))

        def menu(parent, label, var, values, width=8):
            tk.Label(parent, text=label, bg=C_BG3, fg=C_FG,
                     font=("Segoe UI", 9)).pack(side="left", padx=(8, 3))
            m = tk.OptionMenu(parent, var, *values)
            m.configure(bg=BTN_NORM, fg=BTN_FG, relief="raised", bd=1,
                        highlightthickness=0, width=width,
                        font=("Segoe UI", 9))
            m.pack(side="left")

        r1 = tk.Frame(sf, bg=C_BG3)
        r1.pack(fill="x", pady=4)
        menu(r1, "Mode", v_mode, ("CBR", "VBR", "ABR"), 5)
        menu(r1, "Bitrate (CBR/ABR) kbps", v_br,
             ("96", "128", "160", "192", "224", "256", "320"), 5)
        menu(r1, "VBR quality (0 best - 9 smallest)", v_q,
             tuple(str(i) for i in range(10)), 3)
        r2 = tk.Frame(sf, bg=C_BG3)
        r2.pack(fill="x", pady=(0, 4))
        menu(r2, "Sample rate", v_sr, ("0", "32000", "44100", "48000"), 7)
        menu(r2, "Channels (0 = as is)", v_ch, ("0", "1", "2"), 3)
        tk.Checkbutton(r2, text="even out the loudness (-14 LUFS)",
                       variable=v_norm, bg=C_BG3, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG3,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(side="left", padx=14)
        r3 = tk.Frame(sf, bg=C_BG3)
        r3.pack(fill="x", pady=(0, 4))
        tk.Label(r3, text="If the mp3 is already there:", bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left", padx=(8, 4))
        for txt, val in (("leave it", "skip"),
                         ("replace it if the wav is newer", "newer"),
                         ("always replace it", "overwrite")):
            tk.Radiobutton(r3, text=txt, variable=v_ex, value=val,
                           bg=C_BG3, fg=C_FG, selectcolor=C_FIELD,
                           activebackground=C_BG3, activeforeground=C_FG,
                           font=("Segoe UI", 9)).pack(side="left", padx=4)
        tk.Checkbutton(r3, text="write the tags into the new mp3 files",
                       variable=v_tag, bg=C_BG3, fg=C_FG,
                       selectcolor=C_FIELD, activebackground=C_BG3,
                       activeforeground=C_FG,
                       font=("Segoe UI", 9)).pack(side="left", padx=14)

        # ---- go
        gw = tk.Frame(top, bg=C_BG3)
        gw.pack(fill="x", padx=14, pady=(8, 0))
        lw = tk.Frame(top, bg=C_BG3)
        sb = tk.Scrollbar(lw)
        sb.pack(side="right", fill="y")                # scrollbar FIRST
        log_w = mk_text(lw, height=6, yscrollcommand=sb.set,
                        font=("Consolas", 9))
        log_w.pack(side="left", fill="both", expand=True)
        sb.configure(command=log_w.yview)
        bind_mousewheel(log_w)
        q = queue.Queue()
        st = {"busy": False, "stop": False}

        def remember():
            opt.update({
                "mode": v_mode.get(), "bitrate": v_br.get(),
                "vbr_q": v_q.get(), "sample_rate": v_sr.get(),
                "channels": v_ch.get(), "normalize": bool(v_norm.get()),
                "existing": v_ex.get(), "tag_after": bool(v_tag.get()),
                "out_dir": v_out.get().strip(),
                "recurse": bool(v_rec.get()), "hide_have": bool(v_hide.get())})
            self.settings["wav2mp3"] = dict(opt)
            save_settings(self.settings)

        def go():
            if st["busy"]:
                return
            ff = ffmpeg_path()
            if not ff:
                messagebox.showerror(APP_NAME, "ffmpeg was not found.\n\n"
                                     "Press 'Find ffmpeg...' and pick "
                                     "ffmpeg.exe.", parent=top)
                return
            out = v_out.get().strip()
            if not out:
                messagebox.showwarning(APP_NAME, "Where should the mp3 files "
                                       "go?  Fill in the folder.", parent=top)
                return
            remember()
            sel = [int(i) for i in tree.selection()] or \
                [int(i) for i in tree.get_children()]
            pol = v_ex.get()
            todo = []
            for i in sel:
                s = srcs[i]
                stt, dst = wav_status(s, out)
                if stt == "new" or (stt == "newer" and pol != "skip") \
                        or (stt == "have" and pol == "overwrite"):
                    todo.append((s, dst))
            if not todo:
                toast(top, "Nothing to convert", 1200, C_WARN)
                return
            st["busy"], st["stop"] = True, False
            log_w.delete("1.0", "end")
            b_go.configure(state="disabled")
            o = dict(opt)

            def work():
                done, bad, made = 0, 0, []
                for s, dst in todo:
                    if st["stop"]:
                        q.put(("log", "Stopped."))
                        break
                    q.put(("prog", "%d / %d   %s" % (done + 1, len(todo),
                                                      os.path.basename(s))))
                    ok, note = convert_to_mp3(ff, s, dst, o)
                    if ok:
                        made.append(dst)
                        q.put(("log", "OK      " + os.path.basename(dst)))
                    else:
                        bad += 1
                        q.put(("log", "FAILED  %s  - %s"
                               % (os.path.basename(s), note)))
                    done += 1
                if made and o.get("tag_after") and MUTAGEN_OK:
                    q.put(("prog", "Writing the tags ..."))
                    try:
                        r = tag_local_mp3s(
                            cfg, tracks, site, True,
                            bool(cfg.get("tag_cover")), False,
                            only_files=made)
                        for line in ([r.error] if r.error else []) + r.report:
                            q.put(("log", line))
                    except Exception as exc:
                        log_exception("tag after convert", exc)
                        q.put(("log", "Tagging failed: %s" % exc))
                q.put(("done", "%d converted, %d failed" % (len(made), bad)))
            threading.Thread(target=work, daemon=True).start()

        def poll():
            try:
                while True:
                    kind, txt = q.get_nowait()
                    if kind == "log":
                        log_w.insert("end", txt.rstrip() + "\n")
                        log_w.see("end")
                    elif kind == "prog":
                        l_prog.configure(text=txt)
                    else:
                        l_prog.configure(text=txt)
                        st["busy"] = False
                        b_go.configure(state="normal")
                        fill()
                        toast(top, txt, 1500)
            except queue.Empty:
                pass
            if top.winfo_exists():
                top.after(120, poll)

        b_go = mk_button(gw, "Convert", go, BTN_MAIN, width=12)
        b_go.pack(side="left")
        mk_button(gw, "Stop", lambda: st.update(stop=True), BTN_DANGER,
                  width=8).pack(side="left", padx=6)
        mk_button(gw, "Open the folder",
                  lambda: open_in_explorer(v_out.get().strip()), BTN_NORM,
                  width=14).pack(side="left")
        l_prog = tk.Label(gw, text="", bg=C_BG3, fg=C_FG_DIM,
                          font=("Segoe UI", 9))
        l_prog.pack(side="left", padx=10)

        def close():
            remember()
            top.destroy()
        mk_button(gw, "Close", close, BTN_INFO, width=10).pack(side="right")
        lw.pack(fill="both", expand=False, padx=14, pady=8)
        show_ff()
        fill()
        dialog_setup(top, self.root, close)
        top.protocol("WM_DELETE_WINDOW", close)
        poll()

    def _browse_stage(self):
        d = filedialog.askdirectory(title="Where should Temp_to_drive be?",
                                    initialdir=self._stagedir())
        if d:
            self.e_stage.delete(0, "end")
            self.e_stage.insert(0, d)

    def _stagedir(self):
        return self.e_stage.get().strip() or STAGE_DIR_DEFAULT

    # ------------------------------------------------------------ statusbar
    def _statusbar(self):
        bar = tk.Frame(self.root, bg=C_BG3, height=24)
        bar.pack(fill="x", side="bottom")
        self.l_status = tk.Label(bar, text="Ready", bg=C_BG3, fg=C_FG_DIM,
                                 font=("Segoe UI", 9), anchor="w", padx=10)
        self.l_status.pack(side="left", fill="x", expand=True)
        self.l_proj = tk.Label(bar, text="(unsaved project)", bg=C_BG3,
                               fg=C_FG_DIM, font=("Segoe UI", 8), padx=10)
        self.l_proj.pack(side="right")

    def status(self, msg, colour=C_FG_DIM):
        try:
            self.l_status.configure(text=msg, fg=colour)
        except Exception:
            pass
        log(msg)

    # *************************************************************************
    # DEL 15 - GUI <-> PROJECT
    # *************************************************************************
    def _project_to_gui(self):
        s, site = self.project.source, self.project.site
        self.v_srctype.set(s.get("type", DEFAULT_SOURCE["type"]))
        self.t_addr.delete("1.0", "end")
        self.t_addr.insert("1.0", s.get("folders", "") or s.get("address", ""))
        self.t_backups.delete("1.0", "end")
        self.t_backups.insert("1.0", s.get("backups", ""))
        for e, k in ((self.e_audio_folder, "audio_folder"),
                     (self.e_cover_folder, "cover_folder"),
                     (self.e_text_folder, "text_folder"),
                     (self.e_apikey, "api_key")):
            e.delete(0, "end")
            e.insert(0, s.get(k, ""))
        self.v_audio_style.set(s.get("audio_style",
                                     DEFAULT_SOURCE["audio_style"]))
        self.v_image_style.set(s.get("image_style",
                                     DEFAULT_SOURCE["image_style"]))
        self.v_dropnum.set(bool(s.get("drop_track_numbers", True)))
        self.v_fuzzy.set(float(s.get("fuzzy_cutoff", 0.84)))
        self.t_lyrfiles.delete("1.0", "end")
        self.t_lyrfiles.insert("1.0", s.get("lyrics_files", ""))
        self.e_credits.delete(0, "end")
        self.e_credits.insert(0, s.get("credits_file", ""))

        self.t_local.delete("1.0", "end")
        self.t_local.insert("1.0", s.get("local_folders", ""))
        self.v_deep.set(bool(s.get("deep_check", True)))
        self.v_autotag.set(bool(s.get("auto_tag", True)))
        self.v_hide_cover.set(bool(s.get("hide_cover", False)))
        self.v_hide_text.set(bool(s.get("hide_text", False)))
        self.e_tol.delete(0, "end")
        self.e_tol.insert(0, str(s.get("tolerance_min", 5)))
        self.e_stage.delete(0, "end")
        self.e_stage.insert(0, s.get("stage_dir", "") or
                            self.settings.get("last_stage",
                                              STAGE_DIR_DEFAULT))
        self.sync_items = []
        self.sync_tree.delete(*self.sync_tree.get_children())
        self._sync_summary()
        self._mem_label()

        for e, k in ((self.e_sitetitle, "site_title"),
                     (self.e_siteartist, "artist"),
                     (self.e_tagline, "tagline"),
                     (self.e_accent, "accent"),
                     (self.e_footer, "footer_text"),
                     (self.e_suptitle, "support_title"),
                     (self.e_apptitle, "app_title"),
                     (self.e_appurl, "app_url"),
                     (self.e_appbutton, "app_button"),
                     (self.e_pagename, "page_filename")):
            e.delete(0, "end")
            e.insert(0, site.get(k, ""))
        self.t_about.delete("1.0", "end")
        self.t_about.insert("1.0", site.get("about", ""))
        self.t_links.delete("1.0", "end")
        self.t_links.insert("1.0", "\n".join(
            "%s | %s" % (lk.get("label", ""), lk.get("url", ""))
            for lk in site.get("links", [])))
        self.t_support.delete("1.0", "end")
        self.t_support.insert("1.0", site.get("support_text", ""))
        self.t_paylinks.delete("1.0", "end")
        self.t_paylinks.insert("1.0", "\n".join(
            "%s | %s" % (lk.get("label", ""), lk.get("url", ""))
            for lk in site.get("support_links", [])))
        self.v_support.set(bool(site.get("show_support", True)))
        self.v_made.set(bool(site.get("show_made", True)))
        self.t_apptext.delete("1.0", "end")
        self.t_apptext.insert("1.0", site.get("app_text", ""))
        self.v_app.set(bool(site.get("show_app", True)))
        self.v_theme.set(site.get("theme", "auto"))
        self.v_downloads.set(bool(site.get("show_downloads", True)))
        self.v_showlyrics.set(bool(site.get("show_lyrics", True)))
        self.v_search.set(bool(site.get("show_search", True)))
        self.v_shuffle.set(bool(site.get("show_shuffle", True)))
        self.v_autonext.set(bool(site.get("autoplay_next", True)))
        self.v_covermode.set(site.get("cover_mode", "remote"))
        self.v_audiomode.set(site.get("audio_mode", "remote"))
        self.v_playermode.set(site.get("player_mode", "auto"))
        self.v_sortmode.set(site.get("sort_mode", "alpha"))
        self._accent_preview()

        # discography + about me (tabs 6 and 7)
        self.v_show_disco.set(bool(site.get("show_discography", True)))
        self.e_disco_title.delete(0, "end")
        self.e_disco_title.insert(0, site.get("disco_title", "Discography"))
        self.t_disco_intro.delete("1.0", "end")
        self.t_disco_intro.insert("1.0", site.get("disco_intro", ""))
        self.v_show_about.set(bool(site.get("show_aboutpage", True)))
        self.e_about_title.delete(0, "end")
        self.e_about_title.insert(0, site.get("aboutpage_title", "About me"))
        self.e_about_image.delete(0, "end")
        self.e_about_image.insert(0, site.get("aboutpage_image", ""))
        self.t_about_text.delete("1.0", "end")
        self.t_about_text.insert("1.0", site.get("aboutpage_text", ""))
        self._disco_refresh(0)

        self.e_outdir.delete(0, "end")
        self.e_outdir.insert(0, self.project.output_dir or OUT_DIR_DEFAULT)

        self._source_type_changed()
        self._refresh_tree()
        self._update_titlebar()

    def _gui_to_project(self):
        s = self.project.source
        s["type"] = self.v_srctype.get()
        s["folders"] = self.t_addr.get("1.0", "end-1c").strip()
        gs = parse_groups(s["folders"])
        s["address"] = gs[0]["address"] if gs else ""
        s["backups"] = self.t_backups.get("1.0", "end-1c").strip()
        s["audio_folder"] = self.e_audio_folder.get().strip() or "MP3"
        s["cover_folder"] = self.e_cover_folder.get().strip()
        s["text_folder"] = self.e_text_folder.get().strip()
        s["api_key"] = self.e_apikey.get().strip()
        s["audio_style"] = self.v_audio_style.get()
        s["image_style"] = self.v_image_style.get()
        s["drop_track_numbers"] = bool(self.v_dropnum.get())
        s["fuzzy_cutoff"] = float(self.v_fuzzy.get())
        s["lyrics_files"] = self.t_lyrfiles.get("1.0", "end-1c").strip()
        s["credits_file"] = self.e_credits.get().strip().strip('"')

        s["local_folders"] = self.t_local.get("1.0", "end-1c").strip()
        s["deep_check"] = bool(self.v_deep.get())
        s["auto_tag"] = bool(self.v_autotag.get())
        s["hide_cover"] = bool(self.v_hide_cover.get())
        s["hide_text"] = bool(self.v_hide_text.get())
        try:
            s["tolerance_min"] = max(0, int(float(self.e_tol.get().strip()
                                                  or 5)))
        except ValueError:
            s["tolerance_min"] = 5
        s["stage_dir"] = self.e_stage.get().strip()

        site = self.project.site
        site["site_title"] = self.e_sitetitle.get().strip() or "My Music"
        site["artist"] = self.e_siteartist.get().strip()
        site["tagline"] = self.e_tagline.get().strip()
        site["about"] = self.t_about.get("1.0", "end-1c").strip()
        site["accent"] = (self.e_accent.get().strip() or "#e8663a")
        site["theme"] = self.v_theme.get()
        site["show_downloads"] = bool(self.v_downloads.get())
        site["show_lyrics"] = bool(self.v_showlyrics.get())
        site["show_search"] = bool(self.v_search.get())
        site["show_shuffle"] = bool(self.v_shuffle.get())
        site["autoplay_next"] = bool(self.v_autonext.get())
        site["cover_mode"] = self.v_covermode.get()
        site["audio_mode"] = self.v_audiomode.get()
        site["player_mode"] = self.v_playermode.get()
        site["sort_mode"] = self.v_sortmode.get()
        site["footer_text"] = self.e_footer.get().strip()
        site["support_title"] = self.e_suptitle.get().strip()
        site["page_filename"] = self.e_pagename.get().strip() or "index.html"

        def link_lines(widget):
            out = []
            for line in widget.get("1.0", "end-1c").splitlines():
                line = line.strip()
                if not line:
                    continue
                if "|" in line:
                    lab, url = line.split("|", 1)
                else:
                    lab, url = line, line
                out.append({"label": lab.strip(), "url": url.strip()})
            return out

        site["links"] = link_lines(self.t_links)
        site["support_links"] = link_lines(self.t_paylinks)
        site["support_text"] = self.t_support.get("1.0", "end-1c").strip()
        site["show_support"] = bool(self.v_support.get())
        site["show_made"] = bool(self.v_made.get())
        site["show_app"] = bool(self.v_app.get())
        site["app_title"] = self.e_apptitle.get().strip()
        site["app_url"] = self.e_appurl.get().strip().strip('"')
        site["app_button"] = self.e_appbutton.get().strip()
        site["app_text"] = self.t_apptext.get("1.0", "end-1c").strip()

        self._disco_commit()                  # the release in the boxes
        self._disco_site_changed()
        self._about_changed()

        now = self._outdir()
        if now != self.project.output_dir:
            self.project.output_dir = now
            self.project.dirty = True            # the project file keeps it too
        if now != self.settings.get("last_output"):
            self.settings["last_output"] = now
            save_settings(self.settings)

    # ---------------------------------------------------------------- tree
    def _refresh_tree(self, keep=None):
        sel = keep if keep is not None else self._sel_index()
        self.tree.delete(*self.tree.get_children())
        for i, t in enumerate(self.project.tracks):
            tags = []
            if t.get("hidden"):
                tags.append("hidden")
            elif not t.get("cover_url"):
                tags.append("nocover")
            self.tree.insert("", "end", iid=str(i),
                             values=(i + 1,
                                     t.get("group", ""),
                                     t.get("title", ""),
                                     "yes" if t.get("cover_url") else "-",
                                     "yes" if t.get("lyrics") else "-",
                                     t.get("match_note", "")),
                             tags=tuple(tags))
        if self.project.tracks:
            idx = min(max(sel if sel is not None else 0, 0),
                      len(self.project.tracks) - 1)
            self.tree.selection_set(str(idx))
            self.tree.see(str(idx))
        self._load_editor()
        self._update_titlebar()

    def _sel_index(self):
        sel = self.tree.selection()
        if not sel:
            return None
        # several rows may be picked now (Share cover); the editor follows
        # the one with the focus, which is the row he clicked last
        focus = self.tree.focus()
        if focus and focus in sel:
            sel = (focus,)
        try:
            return int(sel[0])
        except Exception:
            return None

    def _on_tree_select(self, _event=None):
        # what was typed belongs to the track the boxes were showing, so
        # that one is saved BEFORE the boxes are filled with the new row
        self._editor_to_track()
        self._load_editor()

    def _load_editor(self):
        i = self._sel_index()
        self._suspend_editor = True
        try:
            self._editor_track = None
            if i is None or i >= len(self.project.tracks):
                for e in (self.e_title, self.e_tartist, self.e_year,
                          self.e_desc, self.e_lyrby, self.e_made,
                          self.e_about):
                    e.delete(0, "end")
                self.lb_rel.delete(0, "end")
                self.t_lyrics.delete("1.0", "end")
                self.v_hidden.set(False)
                self.l_files.configure(text="")
                self.l_lyrsrc.configure(text="")
                return
            t = self.project.tracks[i]
            self._editor_track = t
            for e, k in ((self.e_title, "title"), (self.e_tartist, "artist"),
                         (self.e_year, "year"), (self.e_desc, "description"),
                         (self.e_lyrby, "lyrics_by"),
                         (self.e_made, "made"),
                         (self.e_about, "about_person")):
                e.delete(0, "end")
                e.insert(0, str(t.get(k, "") or ""))
            self._fill_releases(t)
            self.t_lyrics.delete("1.0", "end")
            self.t_lyrics.insert("1.0", t.get("lyrics", ""))
            self.v_hidden.set(bool(t.get("hidden")))
            self.l_lyrsrc.configure(text={
                "file": "(from your lyric file)",
                "picked": "(from your lyric file, with your own corrections)",
                "hand": "(typed here - no file overwrites it)",
            }.get(t.get("lyrics_src", ""), ""))
            self.l_files.configure(
                text="group : %s\naudio : %s\ncover : %s\ntext  : %s\n"
                     "credit: %s"
                     % (t.get("group", "-") or "-",
                        t.get("audio_name", "-") or "-",
                        t.get("cover_name", "-") or "-",
                        t.get("text_name", "-") or "-",
                        "; ".join(
                            "%s%s" % (c.get("name", ""),
                                      ", " + c["role"] if c.get("role")
                                      else "")
                            for c in (t.get("credits") or [])) or "-"))
        finally:
            self._suspend_editor = False

    def _editor_to_track(self):
        """Write the boxes into the track they were loaded for.

        NOT into the selected row: a click on another row moves the
        selection first and the old box's FocusOut arrives afterwards, so
        the selection is already the wrong track by then.
        """
        if self._suspend_editor:
            return
        t = self._editor_track
        if t is None:
            return
        i = next((n for n, x in enumerate(self.project.tracks) if x is t),
                 None)
        if i is None:                   # the list was replaced meanwhile
            return
        fields = ("title", "artist", "year", "description", "lyrics_by",
                  "lyrics_by_src", "lyrics", "lyrics_src", "hidden",
                  "made", "about_person")
        before = tuple(t.get(k) for k in fields)
        t["title"] = self.e_title.get().strip() or t.get("title", "Untitled")
        t["artist"] = self.e_tartist.get().strip()
        t["year"] = self.e_year.get().strip()
        t["description"] = self.e_desc.get().strip()
        t["made"] = self.e_made.get().strip()
        t["about_person"] = self.e_about.get().strip()
        by = self.e_lyrby.get().strip()
        if by != (t.get("lyrics_by", "") or ""):
            # a name he typed himself is never replaced by a file credit
            t["lyrics_by"] = by
            t["lyrics_by_src"] = "hand" if by else ""
        words = self.t_lyrics.get("1.0", "end-1c").rstrip()
        if words != t.get("lyrics", ""):
            # once he has edited the words here, no lyric file overwrites
            # them again - his hand beats the file, every Fetch from now on
            t["lyrics_src"] = "hand"
            t["lyrics"] = words
        t["hidden"] = bool(self.v_hidden.get())
        if before != tuple(t.get(k) for k in fields):
            self.project.dirty = True
        vals = (i + 1, t.get("group", ""), t["title"],
                "yes" if t.get("cover_url") else "-",
                "yes" if t.get("lyrics") else "-",
                t.get("match_note", ""))
        try:
            self.tree.item(str(i), values=vals,
                           tags=("hidden",) if t["hidden"]
                           else (() if t.get("cover_url") else ("nocover",)))
        except Exception:
            self._refresh_tree(i)
        self._update_titlebar()

    # ---- earlier releases (cassette / vinyl / CD ...) of the track in the editor
    def _fill_releases(self, t):
        self.lb_rel.delete(0, "end")
        for r in (t.get("released") or []):
            self.lb_rel.insert("end", self._release_line(r))

    @staticmethod
    def _release_line(r):
        text = r.get("medium", "") or "?"
        if r.get("title"):
            text += "  -  " + r["title"]
        if r.get("when"):
            text += "  (" + r["when"] + ")"
        return text

    def _release_dialog(self, start=None):
        """Ask for medium, name and year of ONE release.  Returns a dict or None."""
        start = start or {}
        top = tk.Toplevel(self.root)
        top.title("MusicSite - earlier release")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        dialog_setup(top, self.root)
        result = {}
        box = tk.Frame(top, bg=C_BG3, padx=18, pady=14)
        box.pack()

        def lab(text, row):
            tk.Label(box, text=text, bg=C_BG3, fg=C_FG,
                     font=("Segoe UI", 9, "bold")).grid(row=row, column=0,
                                                        sticky="w", pady=4)

        lab("Medium", 0)
        v_med = tk.StringVar(value=start.get("medium", "") or "Cassette")
        cb = ttk.Combobox(box, textvariable=v_med, width=26,
                          values=("Cassette", "Vinyl", "CD", "Other"))
        cb.grid(row=0, column=1, sticky="w", padx=(10, 0))
        lab("Name of the release", 1)
        e_title = mk_entry(box, width=34)
        e_title.grid(row=1, column=1, padx=(10, 0))
        e_title.insert(0, start.get("title", ""))
        lab("Year (or a date)", 2)
        e_when = mk_entry(box, width=14)
        e_when.grid(row=2, column=1, sticky="w", padx=(10, 0))
        e_when.insert(0, start.get("when", ""))
        tk.Label(box, text="You can type your own medium too (Minidisc ...).",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).grid(row=3, column=0, columnspan=2,
                                            sticky="w", pady=(4, 0))

        def ok(_e=None):
            result.update({"medium": v_med.get().strip(),
                           "title": e_title.get().strip(),
                           "when": e_when.get().strip()})
            top.destroy()

        brow = tk.Frame(box, bg=C_BG3)
        brow.grid(row=4, column=0, columnspan=2, sticky="e", pady=(12, 0))
        mk_button(brow, "OK", ok, BTN_MAIN, width=10).pack(side="left")
        mk_button(brow, "Cancel", top.destroy, BTN_NORM,
                  width=10).pack(side="left", padx=(6, 0))
        e_title.bind("<Return>", ok)
        e_when.bind("<Return>", ok)
        e_title.focus_set()
        top.wait_window()
        return result or None

    def _release_changed(self, t, keep=None):
        self.project.dirty = True
        self._fill_releases(t)
        if keep is not None:
            self.lb_rel.selection_set(keep)
        self._update_titlebar()

    def _release_add(self):
        t = self._editor_track
        if t is None:
            messagebox.showinfo(APP_NAME, "Pick a track in the list first.",
                                parent=self.root)
            return
        row = self._release_dialog()
        if row:
            t.setdefault("released", []).append(row)
            self._release_changed(t, len(t["released"]) - 1)

    def _release_edit(self):
        t = self._editor_track
        sel = self.lb_rel.curselection()
        if t is None or not sel or sel[0] >= len(t.get("released") or []):
            return
        row = self._release_dialog(t["released"][sel[0]])
        if row:
            t["released"][sel[0]] = row
            self._release_changed(t, sel[0])

    def _release_remove(self):
        t = self._editor_track
        sel = self.lb_rel.curselection()
        if t is None or not sel or sel[0] >= len(t.get("released") or []):
            return
        del t["released"][sel[0]]
        self._release_changed(t)

    def _title_from_file(self):
        """Put the title the audio file's own name gives back in the box."""
        t = self._editor_track
        if t is None or not t.get("audio_name"):
            return
        drop = bool(self.project.source.get("drop_track_numbers", True))
        self.e_title.delete(0, "end")
        self.e_title.insert(0, pretty_title(t["audio_name"], drop))
        self._editor_to_track()

    def _move(self, d):
        i = self._sel_index()
        if i is None:
            return
        j = i + d
        if j < 0 or j >= len(self.project.tracks):
            return
        self._editor_to_track()
        ts = self.project.tracks
        ts[i], ts[j] = ts[j], ts[i]
        self.project.dirty = True
        self._refresh_tree(j)

    def _sort(self, how):
        self._editor_to_track()
        if how == "title":
            self.project.tracks.sort(
                key=lambda t: (t.get("group", ""),
                               title_sort_key(t.get("title", ""))))
        else:
            def keyf(t):
                _, n = strip_tracknumber(
                    os.path.splitext(t.get("audio_name", ""))[0])
                return (t.get("group", ""), 0, n, "") if n is not None else \
                       (t.get("group", ""), 1, 0,
                        (t.get("title", "") or "").casefold())
            self.project.tracks.sort(key=keyf)
        self.project.dirty = True
        self._refresh_tree(0)
        toast(self.root, "Sorted")

    def _set_cover(self):
        """Fix ONE track's cover by hand.

        The normal way: pick the right file from the cloud's Cover folder by
        name (the page then links to it like any other cover).  A picture
        from this PC is the fallback.
        """
        i = self._sel_index()
        if i is None or i >= len(self.project.tracks):
            messagebox.showinfo(APP_NAME, "Pick a track in the list first.",
                                parent=self.root)
            return
        t = self.project.tracks[i]
        files = list(self.project.cover_files or [])
        title_key = norm_key(t.get("audio_name") or t.get("title", ""))

        def closeness(cf):
            return difflib.SequenceMatcher(
                None, title_key, norm_key(cf["name"])).ratio()

        files.sort(key=lambda cf: (-closeness(cf), cf["name"].lower()))
        multi = len({cf.get("group", "") for cf in files}) > 1

        def label(cf):
            return ("%s   [%s]" % (cf["name"], cf["group"])
                    if multi and cf.get("group") else cf["name"])

        top = tk.Toplevel(self.root)
        top.title("MusicSite - cover")
        top.configure(bg=C_BG3)
        dialog_setup(top, self.root)
        box = tk.Frame(top, bg=C_BG3, padx=18, pady=14)
        box.pack(fill="both", expand=True)
        tk.Label(box, text=t.get("title", ""), bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w")
        now = t.get("cover_name") or t.get("cover_url") or "(none)"
        how = (" - set by hand" if t.get("cover_hand") else
               " - found by Fetch" if t.get("cover_url") else "")
        tk.Label(box, text="Cover now: %s%s" % (now, how), bg=C_BG3,
                 fg=C_FG, font=("Segoe UI", 9), wraplength=460,
                 justify="left").pack(anchor="w", pady=(4, 8))

        tk.Label(box, text="The files in the cloud's Cover folder "
                           "(closest names first) - type to narrow:",
                 bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w")
        v_filter = tk.StringVar()
        e_filter = mk_entry(box, textvariable=v_filter)
        e_filter.pack(fill="x", pady=(3, 4))
        lw = tk.Frame(box, bg=C_BG3)
        lw.pack(fill="both", expand=True)
        lsb = tk.Scrollbar(lw)
        lsb.pack(side="right", fill="y")           # scrollbar FIRST
        lst = tk.Listbox(lw, height=10, width=58, bg=C_FIELD, fg=C_FG,
                         selectbackground=C_ACCENT, selectforeground="black",
                         relief="flat", highlightthickness=1,
                         highlightbackground=C_SEP, exportselection=False,
                         font=("Segoe UI", 10), yscrollcommand=lsb.set)
        lst.pack(side="left", fill="both", expand=True)
        lsb.configure(command=lst.yview)
        shown = []

        def refill(*_a):
            q = v_filter.get().strip().lower()
            lst.delete(0, "end")
            del shown[:]
            for cf in files:
                if q and q not in cf["name"].lower():
                    continue
                shown.append(cf)
                lst.insert("end", label(cf))
            if shown:
                lst.selection_set(0)

        v_filter.trace_add("write", refill)
        refill()
        if not files:
            tk.Label(box, text="No list of cloud covers yet - press Fetch "
                               "on the Source tab once, then try again.",
                     bg=C_BG3, fg=C_WARN, font=("Segoe UI", 9),
                     wraplength=460, justify="left").pack(anchor="w",
                                                          pady=(4, 0))

        def done(msg):
            top.destroy()
            self.project.dirty = True
            self._refresh_tree(i)
            self._load_editor()
            self._update_titlebar()
            self.status(msg, C_OK)
            toast(self.root, msg, 1600, C_OK)

        def use_selected(_e=None):
            sel = lst.curselection()
            if not sel:
                return
            cf = shown[sel[0]]
            t["cover_url"] = cf["url"]
            t["cover_name"] = cf["name"]
            t["cover_hand"] = True
            t["match_note"] = "cover chosen by hand (%s)" % cf["name"]
            done("Cover set: %s" % cf["name"])

        def pick():
            path = filedialog.askopenfilename(
                parent=top, title="Cover for " + t.get("title", ""),
                filetypes=[("Pictures", "*.jpg *.jpeg *.png *.webp *.gif"),
                           ("All files", "*.*")])
            if not path:
                return
            t["cover_url"] = os.path.abspath(path)
            t["cover_name"] = os.path.basename(path)
            t["cover_hand"] = True
            t["match_note"] = "cover set by hand (file on this PC)"
            done("Cover set: %s" % t["cover_name"])

        def none():
            t["cover_url"] = ""
            t["cover_name"] = ""
            t["cover_hand"] = True
            t["match_note"] = "no cover (by hand)"
            done("This track now has no cover")

        def auto():
            t["cover_url"] = ""
            t["cover_name"] = ""
            t["cover_hand"] = False
            t["match_note"] = "no cover"
            done("Back to automatic - press Fetch to match it again")

        lst.bind("<Double-Button-1>", use_selected)
        e_filter.bind("<Return>", use_selected)
        brow = tk.Frame(box, bg=C_BG3)
        brow.pack(fill="x", pady=(10, 0))
        mk_button(brow, "Use the selected cover", use_selected, BTN_MAIN,
                  width=22).pack(side="left")
        mk_button(brow, "No cover", none, BTN_NORM,
                  width=10).pack(side="left", padx=(6, 0))
        mk_button(brow, "Back to automatic", auto, BTN_NORM,
                  width=16).pack(side="left", padx=(6, 0))
        mk_button(brow, "Cancel", top.destroy, BTN_NORM,
                  width=8).pack(side="right")
        row2 = tk.Frame(box, bg=C_BG3)
        row2.pack(fill="x", pady=(8, 0))
        mk_button(row2, "A picture from this PC...", pick, BTN_NORM,
                  width=22).pack(side="left")
        tk.Label(row2, text="  only if it is not in the cloud: the page then "
                            "needs the covers folder uploaded too.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 wraplength=300, justify="left").pack(side="left")
        e_filter.focus_set()

    def _share_cover(self):
        """Give every picked track the same cover.

        Mark two or more (Ctrl+click, or Shift+click for a run) and press.
        The picture comes from the row you clicked last if that one has a
        cover, otherwise from the first picked track that has one.
        """
        sel = self.tree.selection()
        if len(sel) < 2:
            messagebox.showinfo(APP_NAME,
                                "Mark two or more tracks first.\n\n"
                                "Ctrl+click picks single tracks, Shift+click "
                                "picks a run of them.  The cover of the "
                                "track you clicked last is given to the "
                                "others.", parent=self.root)
            return
        try:
            picked = [self.project.tracks[int(i)] for i in sel]
        except (ValueError, IndexError):
            return
        source = None
        focus = self.tree.focus()
        if focus in sel:
            try:
                cand = self.project.tracks[int(focus)]
                source = cand if cand.get("cover_url") else None
            except (ValueError, IndexError):
                source = None
        if source is None:
            source = next((t for t in picked if t.get("cover_url")), None)
        if source is None:
            messagebox.showwarning(APP_NAME,
                                   "None of the marked tracks has a cover to "
                                   "share.\n\nMark one that has a picture "
                                   "too - that one is the source.",
                                   parent=self.root)
            return
        n = 0
        for t in picked:
            if t is source or t.get("cover_url") == source.get("cover_url"):
                continue
            t["cover_url"] = source["cover_url"]
            t["cover_name"] = source["cover_name"]
            t["cover_hand"] = True            # Fetch must not undo it
            note = t.get("match_note", "").replace("no cover", "").strip("; ")
            t["match_note"] = "; ".join(
                x for x in (note, "cover shared with %s" % source["title"])
                if x)
            n += 1
        if not n:
            toast(self.root, "They already share that cover", 1400)
            return
        self.project.dirty = True
        keep = self._sel_index()
        self._refresh_tree(keep)
        try:
            self.tree.selection_set(sel)
        except Exception:
            pass
        self._load_editor()
        self._update_titlebar()
        self.status("%d track(s) now use the cover of %s"
                    % (n, source["title"]), C_OK)
        toast(self.root, "%d track(s) share the cover" % n, 1400, C_OK)

    def _remove_track(self):
        i = self._sel_index()
        if i is None:
            return
        t = self.project.tracks[i]
        if not messagebox.askyesno(
                "Remove track",
                "Remove \"%s\" from this project?\n\n"
                "The file itself is NOT touched. A new Fetch will bring it "
                "back." % t.get("title", ""), parent=self.root):
            return
        del self.project.tracks[i]
        self.project.dirty = True
        self._refresh_tree(max(0, i - 1))

    def _open_audio(self):
        i = self._sel_index()
        if i is None:
            return
        url = self.project.tracks[i].get("audio_url", "")
        if not url:
            return
        if re.match(r"^https?://", url):
            open_url(url)
        else:
            open_in_explorer(os.path.dirname(url) if os.path.isabs(url)
                             else self._outdir())

    def _update_titlebar(self):
        name = os.path.basename(self.project.path) if self.project.path \
            else "(unsaved project)"
        mark = " *" if self.project.dirty else ""
        self.root.title("%s - %s%s  [%d tracks]"
                        % (APP_TITLE, name, mark, len(self.project.tracks)))
        try:
            self.l_proj.configure(text=name + mark)
        except Exception:
            pass

    # *************************************************************************
    # DEL 16 - BACKGROUND WORK  (worker thread -> queue -> main thread poll)
    # *************************************************************************
    def _pump(self):
        """Runs on the MAIN thread only.  Workers never touch Tk."""
        try:
            while True:
                kind, payload = self.msgq.get_nowait()
                if kind == "status":
                    self.status(payload)
                elif kind == "report":
                    self._append(self.t_report, payload)
                elif kind == "build":
                    self._append(self.t_build, payload)
                elif kind == "sync":
                    self._append(self.t_sync, payload)
                elif kind == "sync_done":
                    self._sync_done(payload)
                elif kind == "stage_done":
                    self._stage_done(payload)
                elif kind == "progress":
                    try:
                        self.pb["value"] = payload
                    except Exception:
                        pass
                elif kind == "scan_done":
                    self._scan_done(payload)
                elif kind == "build_done":
                    self._build_done(payload)
                elif kind == "send_done":
                    self._send_done(payload)
                elif kind == "update_done":
                    self._update_done(payload)
                elif kind == "warn":
                    messagebox.showwarning(
                        APP_NAME + " - the sound will not play", payload,
                        parent=self.root)
                elif kind == "error":
                    self.busy = False
                    self.status("Failed", C_ERR)
                    messagebox.showerror(APP_NAME, payload, parent=self.root)
        except queue.Empty:
            pass
        except Exception as exc:
            log_exception("_pump", exc)
        self.root.after(120, self._pump)

    def _append(self, widget, text):
        try:
            widget.insert("end", text.rstrip() + "\n")
            widget.see("end")
        except Exception:
            pass

    def _guard(self):
        if self.busy:
            toast(self.root, "Still working...", 1000, C_WARN)
            return False
        return True

    # ------------------------------------------------------------ test only
    def do_test(self):
        if not self._guard():
            return
        self._gui_to_project()
        cfg = dict(self.project.source)
        if not cfg["address"]:
            messagebox.showwarning(APP_NAME,
                                   "Enter the address of the main folder "
                                   "first.", parent=self.root)
            return
        cfg["folders"] = cfg["address"]        # test only the first group
        self.busy = True
        self.status("Testing the address...")
        self.t_report.delete("1.0", "end")

        def work():
            try:
                src = make_source(cfg["type"], cfg["address"],
                                  cfg.get("api_key", ""),
                                  cfg.get("audio_style", ""),
                                  cfg.get("image_style", ""))
                self.msgq.put(("report", src.describe()))
                found = []
                for label, key in (("Audio", "audio_folder"),
                                   ("Cover", "cover_folder"),
                                   ("Text", "text_folder")):
                    name = cfg.get(key, "")
                    if not name:
                        continue
                    items = src.list_folder(name)
                    if items is None:
                        self.msgq.put(("report",
                                       "  %-6s '%s' : NOT FOUND"
                                       % (label, name)))
                    else:
                        found.append(len(items))
                        self.msgq.put(("report",
                                       "  %-6s '%s' : %d file(s)"
                                       % (label, name, len(items))))
                        for it in items[:5]:
                            self.msgq.put(("report", "           " + it.name))
                        if len(items) > 5:
                            self.msgq.put(("report", "           ... and %d "
                                                     "more" % (len(items) - 5)))
                self.msgq.put(("status",
                               "Address works" if found
                               else "Nothing found - check the folder names"))
            except Exception as exc:
                log_exception("do_test", exc)
                self.msgq.put(("error", str(exc)))
            finally:
                self.busy = False

        threading.Thread(target=work, daemon=True).start()

    # ------------------------------------------------- will it actually play?
    def do_check_playback(self):
        """Ask the host for one song and one cover the way a browser will.

        This is the check that a plain download test cannot do, and it is the
        difference between a page that plays and a page that only looks right.
        """
        if not self._guard():
            return
        self._gui_to_project()
        if not self.project.tracks:
            messagebox.showinfo(APP_NAME,
                                "Fetch the tracks first, then this can test "
                                "a real file.", parent=self.root)
            return
        audio = next((t.get("audio_url") for t in self.project.tracks
                      if t.get("audio_url")), "")
        cover = next((t.get("cover_url") for t in self.project.tracks
                      if t.get("cover_url")), "")
        self.busy = True
        self.nb.select(0)
        self.status("Asking the host the way a browser would...")

        def work():
            try:
                lines = ["", "--- Playback check "
                             "(exactly what a browser asks for) ---"]
                a_ok = True
                if audio:
                    a_ok, det = probe_embeddable(audio, "audio")
                    lines.append("  audio : %-8s %s"
                                 % ("ALLOWED" if a_ok else "REFUSED", det))
                else:
                    lines.append("  audio : no audio url yet")
                if cover:
                    c_ok, det = probe_embeddable(cover, "image")
                    lines.append("  cover : %-8s %s"
                                 % ("ALLOWED" if c_ok else "REFUSED", det))
                else:
                    lines.append("  cover : no cover found")
                if a_ok:
                    lines.append("  -> the finished page will play the sound.")
                else:
                    lines.append("  -> the sound will NOT play from this host."
                                 " See the message box.")
                for ln in lines:
                    self.msgq.put(("report", ln))
                self.msgq.put(("status",
                               "Playback OK" if a_ok
                               else "This host refuses to be embedded"))
                if not a_ok and audio:
                    self.msgq.put(("warn", HOTLINK_WARNING))
            except Exception as exc:
                log_exception("do_check_playback", exc)
                self.msgq.put(("error", str(exc)))
            finally:
                self.busy = False

        threading.Thread(target=work, daemon=True).start()

    # ----------------------------------------------------------------- scan
    def do_fetch(self):
        if not self._guard():
            return
        self._editor_to_track()
        self._heal_lyric_box()
        self._gui_to_project()
        cfg = dict(self.project.source)
        if not cfg["address"]:
            self.nb.select(0)
            messagebox.showwarning(APP_NAME,
                                   "Enter the address of the main folder "
                                   "first.\n\nFor Google Drive: the share "
                                   "link of the folder that contains MP3/ "
                                   "and Cover/.\n\nYou may list several "
                                   "folders, one per line - each becomes its "
                                   "own section on the page.",
                                   parent=self.root)
            return
        existing = [dict(t) for t in self.project.tracks]
        self.busy = True
        self.status("Reading the source...")
        self.t_report.delete("1.0", "end")
        self.nb.select(0)

        def work():
            try:
                res = scan_source(cfg, existing,
                                  lambda m: self.msgq.put(("status", m)))
                for line in res.report:
                    self.msgq.put(("report", line))
                self.msgq.put(("scan_done", res))
            except Exception as exc:
                log_exception("do_fetch", exc)
                self.msgq.put(("error", str(exc)))
            finally:
                self.busy = False

        threading.Thread(target=work, daemon=True).start()

    def _scan_done(self, res):
        self.busy = False
        if res.error:
            self.status("Nothing found", C_WARN)
            messagebox.showwarning(APP_NAME, res.error, parent=self.root)
            return
        self.project.tracks = res.tracks
        if res.cover_files:
            self.project.cover_files = res.cover_files
        self.project.dirty = True
        self._refresh_tree(0)
        self.status("Found %d track(s)" % len(res.tracks), C_OK)
        toast(self.root, "%d tracks" % len(res.tracks))
        said = [l for l in res.report
                if l.startswith("Gone from the source")
                or l.startswith("Title of ")]
        if said:
            messagebox.showinfo(APP_NAME, "\n\n".join(said)
                                + "\n\nSave the project to keep this.",
                                parent=self.root)
        if res.tracks:
            self.nb.select(1)

    # ---------------------------------------------------------------- build
    def do_build(self):
        if not self._guard():
            return
        self._editor_to_track()
        self._gui_to_project()
        if not self.project.tracks:
            messagebox.showwarning(APP_NAME,
                                   "There are no tracks yet.\n\n"
                                   "Go to the Source tab and press "
                                   "'Fetch / refresh from source'.",
                                   parent=self.root)
            return
        bad = foreign_profile_dir(self.project.output_dir or OUT_DIR_DEFAULT)
        if bad:                       # v1.15.0: a project copied from the other profile must not build into its Site folder
            messagebox.showwarning(APP_NAME,
                                   "The output folder belongs to another profile (%s):\n\n%s\n\n"
                                   "Nothing was built.  Pick this profile's own output folder on the "
                                   "Build tab (default: %s)." % (bad, self.project.output_dir, OUT_DIR_DEFAULT),
                                   parent=self.root)
            self.nb.select(3)
            return
        self.busy = True
        self.t_build.delete("1.0", "end")
        self.nb.select(3)
        self.status("Building...")
        try:
            self.pb["value"] = 5
        except Exception:
            pass
        proj = self.project

        def work():
            try:
                def say(m):
                    self.msgq.put(("build", m))
                    self.msgq.put(("status", m))
                out = build_site(proj, say)
                self.msgq.put(("build_done", out))
            except Exception as exc:
                log_exception("do_build", exc)
                self.msgq.put(("error", "Build failed:\n\n%s" % exc))
            finally:
                self.busy = False

        threading.Thread(target=work, daemon=True).start()

    def _build_done(self, out):
        self.busy = False
        try:
            self.pb["value"] = 100
        except Exception:
            pass
        size = os.path.getsize(out)
        self._append(self.t_build, "")
        self._append(self.t_build, "Wrote %s  (%.1f KB)" % (out, size / 1024.0))
        extra = [os.path.basename(p) for p in self.project.last_pages[1:]]
        self._append(self.t_build, "Upload this file%s to your web server."
                     % (" and " + ", ".join(extra) if extra else ""))
        outdir = self.project.output_dir or OUT_DIR_DEFAULT
        for sub in ("covers", "mp3"):
            if os.path.isdir(os.path.join(outdir, sub)):
                self._append(self.t_build,
                             "Also upload the '%s' folder next to it." % sub)
        self.status("Built %s  at %s" % (os.path.normpath(out),
                                         datetime.now().strftime("%H:%M:%S")),
                    C_OK)
        if os.path.normcase(os.path.normpath(outdir)) != os.path.normcase(
                os.path.normpath(OUT_DIR_DEFAULT)):
            self._append(self.t_build,
                         "Note: this is NOT the default output folder (%s) - "
                         "look for the file in the folder above."
                         % os.path.normpath(OUT_DIR_DEFAULT))
        toast(self.root, "Page built")
        self._remember_output(self.project.output_dir)
        if self.v_srv_auto.get():
            self.root.after(200, lambda: self.do_send(auto=True))

    def do_preview(self):
        self._gui_to_project()
        fname = self.project.site.get("page_filename") or "index.html"
        out = os.path.join(self._outdir(), fname)
        if not os.path.isfile(out):
            if messagebox.askyesno(APP_NAME,
                                   "The page has not been built yet.\n\n"
                                   "Build it now?", parent=self.root):
                self.do_build()
            return
        open_in_browser(out)
        self.status("Opened the page in your browser")

    # *************************************************************************
    # DEL 16B - SEND TO THE SERVERS  (v1.15.0; the work is in DEL 12C)
    # *************************************************************************
    def _srv_setting(self, key):
        """Server settings with their profile defaults (the folder name on Webdock = the profile name)."""
        v = self.settings.get(key)
        if key == "srv_name":
            return v or srv_default_folder_name()
        return v if v is not None else ""

    # ---- File > Profile (v1.15.1): every group is its own window, opened from here ----------------------------------
    def _fill_profile_menu(self):
        m = self.profile_menu
        m.delete(0, "end")
        here = PROFILE_TITLE or "no profile (old MusicSite folder)"
        m.add_command(label="This window: %s" % here, state="disabled")
        m.add_separator()
        others = [(n, note) for n, note in list_profiles() if n.lower() != PROFILE.lower()]
        for n, note in others:
            title = PROFILE_TITLES.get(n.lower(), n.upper())
            m.add_command(label="Open %s%s" % (title, ("   (%s)" % note) if note else ""),
                          command=lambda n=n: self._open_profile(n))
        if not others:
            m.add_command(label="(no other profile yet)", state="disabled")
        m.add_separator()
        m.add_command(label="New profile...", command=self.new_profile_dialog)

    def _open_profile(self, name):
        err = launch_profile(name)
        if err:
            messagebox.showwarning(APP_NAME, err, parent=self.root)
        else:
            self.status("Opened %s in a new window" % PROFILE_TITLES.get(name.lower(), name.upper()))

    def new_profile_dialog(self):
        top = tk.Toplevel(self.root)
        top.title("MusicSite - new profile")
        top.configure(bg=C_BG2)
        top.transient(self.root)
        top.geometry("520x270")
        top.resizable(False, False)
        tk.Label(top, text="A new group with its own site", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w", padx=14, pady=(12, 2))
        tk.Label(top, text="It gets its own settings, projects, backups, output folder, log and server folders, "
                 "and opens in a NEW window.  The name is also the default name of its folder on Webdock.",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9), wraplength=490, justify="left").pack(anchor="w", padx=14)
        tk.Label(top, text="Name (letters, digits, - and _)", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w", padx=14, pady=(12, 0))
        e = mk_entry(top)
        e.pack(fill="x", padx=14)
        e.focus_set()
        note = tk.Label(top, text="", bg=C_BG2, fg=C_WARN, font=("Segoe UI", 9), wraplength=490, justify="left")
        note.pack(anchor="w", padx=14, pady=(6, 0))

        def go(_e=None):
            raw = e.get().strip()
            name = _clean_profile(raw)
            if not name:
                note.configure(text="Use letters, digits, - and _ only, starting with a letter or digit.")
                return
            if name.lower() == PROFILE.lower() or any(n.lower() == name.lower() and not nt for n, nt in list_profiles()):
                note.configure(text="A profile called %s already exists - open it from the Profile menu." % name)
                return
            top.destroy()
            self._open_profile(name)

        bf = tk.Frame(top, bg=C_BG2)
        bf.pack(fill="x", padx=14, pady=14)
        mk_button(bf, "Create and open", go, BTN_MAIN, width=18).pack(side="left")
        mk_button(bf, "Cancel", top.destroy, BTN_NORM, width=12).pack(side="left", padx=8)
        top.bind("<Return>", go)
        top.bind("<Escape>", lambda ev: top.destroy())
        top.grab_set()
        top.focus_force()

    def _srv_ticks_changed(self):
        self.settings["srv_webdock"] = bool(self.v_srv_web.get())
        self.settings["srv_auto"] = bool(self.v_srv_auto.get())
        save_settings(self.settings)

    def open_webdock_page(self):
        try:
            cfg = srv_appsite_config()
        except ServerError as exc:
            messagebox.showwarning(APP_NAME, str(exc), parent=self.root)
            return
        name = srv_clean_name(self._srv_setting("srv_name"))
        if not cfg["url"] or not name:
            messagebox.showinfo(APP_NAME, "No public Webdock address is known yet (AppSite > Updates > Public address).",
                                parent=self.root)
            return
        open_url("%s/p/%s/" % (cfg["url"], name))

    def do_send(self, auto=False):
        """Send the built page's small files to the server (a worker thread; nothing here touches Tk)."""
        if not self._guard():
            return
        self._gui_to_project()
        outdir = self._outdir()
        bad = foreign_profile_dir(outdir)
        if bad:
            messagebox.showwarning(APP_NAME, "The output folder belongs to another profile (%s):\n\n%s\n\nPick this profile's own "
                                   "folder on the Build tab first." % (bad, outdir), parent=self.root)
            return
        page = self.project.site.get("page_filename") or "index.html"
        if not os.path.isfile(os.path.join(outdir, page)):
            if not auto:
                messagebox.showinfo(APP_NAME, "There is no %s in the output folder yet.\n\nPress 'Build page' first." % page,
                                    parent=self.root)
            return
        if not bool(self.v_srv_web.get()):
            if not auto:
                messagebox.showinfo(APP_NAME, "Tick Webdock first.", parent=self.root)
            return
        files, skipped = srv_collect(outdir)
        self._srv_run(files, skipped, set())

    def _srv_run(self, files, skipped, adopt):
        name = self._srv_setting("srv_name")
        self.busy = True
        self.nb.select(3)
        self.status("Sending...")
        for rel, why in skipped:
            self._append(self.t_build, "   not sent: %s (%s)" % (rel, why))

        def work():
            results, errors, ask = [], [], []

            def say(m):
                self.msgq.put(("build", m))
            try:
                for label, cfg in srv_servers():
                    try:
                        results.append(send_webdock(files, name, say, adopt="web" in adopt, cfg=cfg, label=label))
                    except NeedConfirm as exc:
                        ask.append(("web", str(exc)))
                    except ServerError as exc:
                        errors.append((label, str(exc)))
            except ServerError as exc:                      # the server settings themselves (AppSite > Updates)
                errors.append(("Webdock", str(exc)))
            except Exception as exc:
                log_exception("send_webdock", exc)
                errors.append(("Webdock", "Unexpected: %s" % exc))
            self.msgq.put(("send_done", {"results": results, "errors": errors, "ask": ask, "files": files,
                                         "skipped": skipped, "adopt": adopt}))

        threading.Thread(target=work, daemon=True).start()

    def _send_done(self, r):
        self.busy = False
        for res in r["results"]:
            line = "SENT to %s: %d file(s), %.0f KB" % (res["where"], res["count"], res["bytes"] / 1024.0)
            self._append(self.t_build, line)
            if res.get("url"):
                self._append(self.t_build, "   test address: " + res["url"])
        for where, msg in r["errors"]:
            self._append(self.t_build, "FAILED %s: %s" % (where, msg.splitlines()[0] if msg else ""))
        if r["errors"]:
            self.status("Sending failed", C_ERR)
            messagebox.showwarning(APP_NAME, "\n\n".join("%s:\n%s" % (w, m) for w, m in r["errors"]) +
                                   ("\n\nWhat did go is listed in the build log." if r["results"] else ""), parent=self.root)
        elif r["results"] and not r["ask"]:
            self.status("Sent to %s at %s" % (" + ".join(x["where"] for x in r["results"]), datetime.now().strftime("%H:%M:%S")), C_OK)
            toast(self.root, "Sent")
        # a folder that already holds files and has no marker: ask, then go again
        for key, msg in r["ask"]:
            if messagebox.askyesno(APP_NAME, msg, parent=self.root):
                self._srv_run(r["files"], [], set(r["adopt"]) | {key})
                return
            self._append(self.t_build, "Not taken over: Webdock")

    # ---- Update everything (v1.16.0, DEL 12D): Fetch -> Save -> Build -> Send in one press
    def do_update(self):
        if not self._guard():
            return
        self._editor_to_track()
        self._heal_lyric_box()
        self._gui_to_project()
        if not self.project.path:
            if not self.save_project_as():
                return
        proj = self.project
        bad = foreign_profile_dir(proj.output_dir or OUT_DIR_DEFAULT)
        if bad:
            messagebox.showwarning(APP_NAME, "The output folder belongs to another profile (%s).\n\nNothing was done.  Pick this "
                                   "profile's own folder on the Build tab." % bad, parent=self.root)
            return
        self.busy = True
        self.t_build.delete("1.0", "end")
        self.nb.select(3)
        self.status("Updating everything...")
        settings = dict(self.settings)
        settings["srv_webdock"] = bool(self.v_srv_web.get())
        settings["srv_name"] = self._srv_setting("srv_name")

        def work():
            def say(m):
                self.msgq.put(("build", m))
                self.msgq.put(("status", m.strip()))
            try:
                ok, text, results = update_pipeline(proj, settings, say)
            except Exception as exc:
                log_exception("do_update", exc)
                ok, text, results = False, "Crashed: %s" % exc, []
            self.msgq.put(("update_done", {"ok": ok, "text": text, "results": results}))

        threading.Thread(target=work, daemon=True).start()

    def _update_done(self, r):
        self.busy = False
        self._refresh_tree(0)
        self._update_titlebar()
        self._append(self.t_build, "")
        self._append(self.t_build, ("DONE: " if r["ok"] else "STOPPED: ") + r["text"])
        for res in r["results"]:
            if res.get("url"):
                self._append(self.t_build, "   test address: " + res["url"])
        if r["ok"]:
            self.status(r["text"], C_OK)
            toast(self.root, "Everything updated")
        else:
            self.status("Update stopped", C_ERR)
            messagebox.showwarning(APP_NAME, r["text"], parent=self.root)

    def show_servers_dialog(self):
        top = tk.Toplevel(self.root)
        top.title("MusicSite - server  (%s)" % (PROFILE_TITLE or "no profile"))
        top.configure(bg=C_BG2)
        top.transient(self.root)
        top.geometry("640x230")
        top.resizable(False, False)
        pad = {"padx": 14}
        tk.Label(top, text="Where the small files go", bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w", pady=(12, 2), **pad)
        tk.Label(top, text="Profile: %s   (separate folders per profile; one can never overwrite the other)"
                 % (PROFILE_TITLE or "none"), bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(anchor="w", **pad)
        fr = tk.Frame(top, bg=C_BG2)
        fr.pack(fill="x", pady=(10, 0), **pad)
        tk.Label(fr, text="Webdock folder name", bg=C_BG2, fg=C_FG, font=("Segoe UI", 9, "bold")).pack(anchor="w")
        tk.Label(fr, text="Pages go to <server folder>/p/<name>/ (server and key come from AppSite > Updates). "
                 "Test address: <public address>/p/<name>/", bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8), wraplength=600,
                 justify="left").pack(anchor="w")
        e_name = mk_entry(fr)
        e_name.pack(fill="x")
        e_name.insert(0, self._srv_setting("srv_name"))

        def save(_e=None):
            nm = e_name.get().strip().lower()
            if nm and not srv_clean_name(nm):
                messagebox.showwarning(APP_NAME, "The Webdock folder name may only hold letters, digits, - and _ (and not be a "
                                       "name AppSite already uses).", parent=top)
                return
            self.settings["srv_name"] = nm
            save_settings(self.settings)
            top.destroy()

        bf = tk.Frame(top, bg=C_BG2)
        bf.pack(fill="x", pady=16, **pad)
        mk_button(bf, "Save", save, BTN_MAIN, width=12).pack(side="left")
        mk_button(bf, "Cancel", top.destroy, BTN_NORM, width=12).pack(side="left", padx=8)
        top.bind("<Escape>", lambda e: top.destroy())
        top.grab_set()
        top.focus_force()

    # *************************************************************************
    # DEL 17 - PROJECT FILE COMMANDS
    # *************************************************************************
    # --------------------------------------------------------- upload check
    def do_sync_compare(self, fresh=False):
        if not self._guard():
            return
        self._editor_to_track()
        self._gui_to_project()
        cfg = dict(self.project.source)
        if not cfg.get("address"):
            self.nb.select(0)
            messagebox.showwarning(APP_NAME,
                                   "There is no cloud folder to compare "
                                   "with.\n\nFill in 'Main folder(s)' on the "
                                   "Source tab first.", parent=self.root)
            return
        if not (cfg.get("local_folders") or "").strip():
            self.nb.select(4)
            messagebox.showwarning(APP_NAME,
                                   "Which folder on this computer should be "
                                   "compared?\n\nPress Browse and pick the "
                                   "folder your master files live in - the "
                                   "one that has MP3 / Cover / Text inside "
                                   "it.", parent=self.root)
            return

        kinds = ("Audio", "Cover", "Text")     # always all three
        deep = bool(self.v_deep.get())
        tol = cfg.get("tolerance_min", 5)

        self.sync_stop = False
        self.busy = True
        self.t_sync.delete("1.0", "end")
        self.sync_items = []
        self.sync_tree.delete(*self.sync_tree.get_children())
        self.l_syncsum.configure(text="Comparing ...", fg=C_FG_DIM)
        self.nb.select(4)
        self.status("Asking the cloud about every single file ..." if fresh
                    else "Comparing with the cloud ...")
        if fresh:
            self._append(self.t_sync, "CLEAN COMPARISON - nothing is taken "
                                      "from memory this time.")

        tracks = [dict(t) for t in self.project.tracks]
        site = dict(self.project.site)

        def work():
            try:
                # the files must carry their tags BEFORE they are compared,
                # or the upload check would call them "up to date" and the
                # old, tag-less copy would stay in the cloud
                if cfg.get("auto_tag", True) and MUTAGEN_OK:
                    self.msgq.put(("sync", "--- Tags in the mp3 files ---"))
                    tres = tag_local_mp3s(
                        cfg, tracks, site, True,
                        bool(cfg.get("tag_cover")),
                        bool(cfg.get("tag_keep_original", True)),
                        lambda m: self.msgq.put(("status", m)),
                        lambda: self.sync_stop)
                    if tres.error:
                        self.msgq.put(("sync", "! " + tres.error.splitlines()[0]))
                    for line in tres.report:
                        self.msgq.put(("sync", line))
                    self.msgq.put(("sync", "--- Comparison ---"))
                res = compare_library(
                    cfg, kinds, deep, tol,
                    lambda m: self.msgq.put(("status", m)),
                    lambda: self.sync_stop, self.memory, fresh)
                for line in res.report:
                    self.msgq.put(("sync", line))
                self.msgq.put(("sync_done", res))
            except Exception as exc:
                log_exception("do_sync_compare", exc)
                self.msgq.put(("error", str(exc)))
            finally:
                self.busy = False

        threading.Thread(target=work, daemon=True).start()

    def _sync_done(self, res):
        self.busy = False
        if res.error:
            self.l_syncsum.configure(text="Nothing to compare.", fg=C_WARN)
            self.status("Nothing compared", C_WARN)
            messagebox.showwarning(APP_NAME, res.error, parent=self.root)
            return
        self.sync_items = res.items
        self._sync_fill()
        if res.cancelled:
            self.status("Stopped", C_WARN)
            toast(self.root, "Stopped", 1200, C_WARN)
            return
        self._mem_label()
        c = res.counts()
        todo = sum(c.get(s, 0) for s in UPLOAD_STATUSES)
        self.status("%d file(s) to upload" % todo, C_OK if todo else C_FG_DIM)
        toast(self.root, "%d to upload" % todo, 1200,
              C_WARN if todo else C_OK)

    def _hidden_row(self, it):
        """Is this row filtered away?  It is still compared and ticked."""
        if self.v_only_todo.get() and it["status"] in (STATUS_SAME,
                                                       STATUS_ONLINE):
            return True
        if self.v_hide_cover.get() and it["kind"] == "Cover":
            return True
        if self.v_hide_text.get() and it["kind"] == "Text":
            return True
        return False

    def _mem_label(self):
        """What the program remembers about the cloud, in one dim line."""
        try:
            st = self.memory.stats()
        except Exception:
            return
        if not st["files"]:
            txt = ("Nothing remembered about the cloud yet - the first "
                   "comparison is the slow one.")
        else:
            txt = ("Remembers the size and time of %d file(s) in the cloud, "
                   "last asked %s.  'Clean comparison' asks about every one "
                   "of them again." % (st["files"],
                                       human_when(st["asked"]) or "-"))
            if st["pending"]:
                txt += "  %d file(s) copied to Temp_to_drive are still " \
                       "waiting to appear up there." % st["pending"]
            if st.get("claimed"):
                txt += "  %d file(s) are marked by you as uploaded and have " \
                       "not been checked." % st["claimed"]
        try:
            self.l_mem.configure(text=txt)
        except Exception:
            pass

    def _sync_fill(self):
        self.sync_tree.delete(*self.sync_tree.get_children())
        for i, it in enumerate(self.sync_items):
            if self._hidden_row(it):
                continue
            self.sync_tree.insert(
                "", "end", iid=str(i),
                text="✔" if it["include"] else "",
                values=(STATUS_TEXT.get(it["status"], it["status"]),
                        it["kind"], it["name"], self._sync_mine(it),
                        self._sync_online(it), it["note"]),
                tags=(it["status"],))
        self._sync_summary()

    @staticmethod
    def _sync_mine(it):
        if not it["path"]:
            return "-"
        return "%s  %s" % (human_size(it["lsize"]),
                           human_when(it["lmtime"]))

    @staticmethod
    def _sync_online(it):
        if it["status"] == STATUS_NEW:
            return "-"
        size = human_size(it["rsize"]) if it["rsize"] else "?"
        when = human_when(it["rmtime"], it["rexact"])
        return ("%s  %s" % (size, when)).strip()

    def _sync_summary(self):
        picked = [it for it in self.sync_items if it["include"] and it["path"]]
        c = {}
        for it in self.sync_items:
            c[it["status"]] = c.get(it["status"], 0) + 1
        total = sum(it["lsize"] for it in picked)
        if not self.sync_items:
            self.l_syncsum.configure(text="Nothing compared yet.",
                                     fg=C_FG_DIM)
            return
        # a ticked row that the filter hides is still going to be copied, so
        # it has to be counted out loud - never silently
        hidden = sum(1 for it in picked if self._hidden_row(it))
        self.l_syncsum.configure(
            text="%d ticked (%s)%s     %d new, %d changed, %d newer here, "
                 "%d waiting, %d marked by you, %d to check, %d up to date, "
                 "%d only online"
                 % (len(picked), human_size(total),
                    ", %d of them hidden below" % hidden if hidden else "",
                    c.get(STATUS_NEW, 0), c.get(STATUS_CHANGED, 0),
                    c.get(STATUS_NEWER, 0), c.get(STATUS_STAGED, 0),
                    c.get(STATUS_ASSUMED, 0), c.get(STATUS_CHECK, 0),
                    c.get(STATUS_SAME, 0), c.get(STATUS_ONLINE, 0)),
            fg=C_WARN if picked else C_OK)

    def _sync_set(self, iid, on):
        try:
            it = self.sync_items[int(iid)]
        except (ValueError, IndexError):
            return
        if not it["path"]:                     # nothing here to upload
            return
        it["include"] = bool(on)
        if self.sync_tree.exists(iid):         # it may be filtered away
            self.sync_tree.item(iid, text="✔" if it["include"] else "")

    def _sync_click(self, ev):
        # only the narrow tick column toggles, so selecting rows still works
        if self.sync_tree.identify_region(ev.x, ev.y) != "tree":
            return None
        iid = self.sync_tree.identify_row(ev.y)
        if not iid:
            return None
        try:
            it = self.sync_items[int(iid)]
        except (ValueError, IndexError):
            return None
        self._sync_set(iid, not it["include"])
        self._sync_summary()
        return "break"

    def _sync_space(self, _ev=None):
        sel = self.sync_tree.selection()
        if not sel:
            return None
        try:
            on = not self.sync_items[int(sel[0])]["include"]
        except (ValueError, IndexError):
            return None
        for iid in sel:
            self._sync_set(iid, on)
        self._sync_summary()
        return "break"

    def _sync_double(self, ev):
        if self.sync_tree.identify_region(ev.x, ev.y) == "tree":
            return None
        iid = self.sync_tree.identify_row(ev.y)
        if not iid:
            return None
        try:
            it = self.sync_items[int(iid)]
        except (ValueError, IndexError):
            return None
        if it["path"]:
            open_in_explorer(os.path.dirname(it["path"]))
        return "break"

    def _sync_tick(self, mode):
        for i, it in enumerate(self.sync_items):
            if not it["path"]:
                continue
            if mode == "all":
                on = True
            elif mode == "none":
                on = False
            else:
                on = it["status"] in UPLOAD_STATUSES
            it["include"] = on
            if self.sync_tree.exists(str(i)):  # it may be filtered away
                self.sync_tree.item(str(i), text="✔" if on else "")
        self._sync_summary()

    def _mark_uploaded(self, on=True):
        """Half-tick: "I have already put these up", or take that back.

        It is written down as HIS word, not as a fact.  A plain Compare
        believes it and stops nagging; the moment the file here changes, or
        a Clean comparison really asks the cloud, a wrong mark comes out and
        the file is back in the list.
        """
        sel = self.sync_tree.selection()
        if not sel:
            messagebox.showinfo(APP_NAME,
                                "Mark the rows first.\n\nClick a row, or "
                                "Ctrl+click several, and press again.\n\n"
                                "This says 'I have already uploaded these', "
                                "so they stop asking to go up.  A Clean "
                                "comparison checks whether that was true.",
                                parent=self.root)
            return
        can = UPLOAD_STATUSES + (STATUS_STAGED, STATUS_CHECK, STATUS_ASSUMED)
        n = skipped = 0
        for iid in sel:
            try:
                it = self.sync_items[int(iid)]
            except (ValueError, IndexError):
                continue
            if not it.get("path") or not it.get("skey"):
                skipped += 1
                continue
            if on:
                if it["status"] not in can:
                    skipped += 1
                    continue
                self.memory.mark_claimed(it["skey"], it.get("folder", ""),
                                         it["name"], it.get("lsize", 0),
                                         it.get("lmtime", 0))
                if it["status"] != STATUS_ASSUMED:
                    it["was"] = it["status"]
                it["status"] = STATUS_ASSUMED
                it["include"] = False
                it["note"] = "you marked it as uploaded just now - not " \
                             "checked against the cloud"
            else:
                if not self.memory.clear_claimed(it["skey"],
                                                 it.get("folder", ""),
                                                 it["name"]):
                    skipped += 1
                    continue
                it["status"] = it.pop("was", STATUS_CHECK)
                it["include"] = it["status"] in UPLOAD_STATUSES
                it["note"] = "the mark is gone - compare again to be sure"
            n += 1
        self.memory.save()
        self._sync_fill()
        self._mem_label()
        if not n:
            toast(self.root, "Nothing to mark there", 1400, C_WARN)
            return
        self.status("%d file(s) %s" % (n, "marked as uploaded" if on
                                       else "no longer marked"), C_OK)
        toast(self.root, "%d %s%s" % (n, "marked" if on else "unmarked",
                                      ", %d skipped" % skipped
                                      if skipped else ""), 1500, C_OK)

    def _sync_stop(self):
        if self.busy:
            self.sync_stop = True
            self.status("Stopping ...", C_WARN)
        else:
            toast(self.root, "Nothing is running", 1000)

    def _sync_open_cloud(self):
        self._gui_to_project()
        addr = self.project.source.get("address", "").strip()
        if not addr:
            toast(self.root, "No cloud folder yet", 1200, C_WARN)
            return
        if os.path.isdir(addr):
            open_in_explorer(addr)
        else:
            open_url(addr)

    def do_sync_stage(self):
        if not self._guard():
            return
        picked = [it for it in self.sync_items if it["include"] and it["path"]]
        if not picked:
            messagebox.showinfo(APP_NAME,
                                "Nothing is ticked.\n\nPress 'Compare with "
                                "the cloud' first, or tick the files you want "
                                "to send up.", parent=self.root)
            return
        self._gui_to_project()
        dest = self._stagedir()
        multi = len(parse_groups(self.project.source.get("folders", ""),
                                 self.project.source.get("address", ""))) > 1
        clear = bool(self.v_clear.get())
        # everything that still has to go up keeps its place in Temp_to_drive,
        # ticked or not - emptying the folder must never throw away a file
        # that has been waiting there since yesterday
        keep = {(it.get("folder", ""), it["name"]) for it in self.sync_items
                if it.get("path") and
                (it["status"] in UPLOAD_STATUSES or
                 it["status"] == STATUS_STAGED)}
        total = sum(it["lsize"] for it in picked)
        old = 0
        if clear:
            for d in {stage_folder_for(it, dest, multi) for it in picked}:
                if not os.path.isdir(d):
                    continue
                sub = os.path.basename(d)
                old += sum(1 for e in os.listdir(d)
                           if os.path.isfile(os.path.join(d, e))
                           and (sub, e) not in keep)
        if not messagebox.askyesno(
                APP_NAME,
                "Copy %d file(s), %s, to\n\n%s\n\n%s"
                % (len(picked), human_size(total), dest,
                   ("%d file(s) already in there will be deleted first."
                    % old) if old else
                   "Then drag the contents of each sub-folder into the "
                   "matching folder in the cloud."),
                parent=self.root):
            return

        self.busy = True
        self.status("Copying ...")

        def work():
            try:
                info = stage_uploads(picked, dest, multi, clear,
                                     lambda m: self.msgq.put(("status", m)),
                                     self.memory, keep)
                self.msgq.put(("stage_done", info))
            except Exception as exc:
                log_exception("do_sync_stage", exc)
                self.msgq.put(("error", "Could not copy:\n\n%s" % exc))
            finally:
                self.busy = False

        threading.Thread(target=work, daemon=True).start()

    def _stage_done(self, info):
        self.busy = False
        self._append(self.t_sync, "")
        self._append(self.t_sync,
                     "Copied %d file(s), %s, into %s"
                     % (info["count"], human_size(info["bytes"]),
                        info["dest"]))
        if info.get("already"):
            self._append(self.t_sync,
                         "(%d of them were already there and were left "
                         "alone)" % info["already"])
        if info.get("removed"):
            self._append(self.t_sync,
                         "(%d file(s) that no longer have to go up were "
                         "deleted from Temp_to_drive)" % info["removed"])
        self._append(self.t_sync,
                     "Now drag the contents of each sub-folder into the "
                     "folder of the same name in the cloud, then Compare "
                     "again.")
        self._mem_label()
        self.status("%d file(s) ready in Temp_to_drive" % info["count"], C_OK)
        toast(self.root, "%d file(s) ready" % info["count"], 1400, C_OK)
        self.settings["last_stage"] = info["dest"]
        save_settings(self.settings)

    def _confirm_discard(self):
        if not self.project.dirty:
            return True
        ans = messagebox.askyesnocancel(
            APP_NAME, "Save the current project first?", parent=self.root)
        if ans is None:
            return False
        if ans:
            return self.save_project()
        return True

    # keys of the source that are WHERE things live - kept for a new project
    FOLDER_KEYS = ("type", "address", "folders", "backups", "audio_folder",
                   "cover_folder", "text_folder", "api_key", "audio_style",
                   "image_style", "lyrics_files", "credits_file", "local_folders",
                   "stage_dir", "drop_track_numbers", "fuzzy_cutoff",
                   "deep_check", "tolerance_min")

    def _remember_folders(self):
        """Keep the folders for the next new project, also between runs."""
        try:
            self.settings["folder_memory"] = {
                k: self.project.source.get(k) for k in self.FOLDER_KEYS}
            save_settings(self.settings)
        except Exception as exc:
            log_exception("remember folders", exc)

    def _fresh_project(self):
        """An empty project that still points at the same folders."""
        self._gui_to_project()
        keep = {k: self.project.source.get(k) for k in self.FOLDER_KEYS}
        out = self.project.output_dir
        # the band's releases and the about-me page are not about the songs
        # that Fetch finds, so a new project keeps them
        keep_disco = self.project.discography
        keep_pages = {k: self.project.site.get(k) for k in PAGE_SITE_KEYS}
        self.project = Project()
        self.project.output_dir = out
        self.project.source.update(
            {k: v for k, v in keep.items() if v is not None})
        self.project.discography = keep_disco
        self.project.site.update(
            {k: v for k, v in keep_pages.items() if v is not None})
        self._editor_track = None
        self._project_to_gui()
        self.t_report.delete("1.0", "end")
        self.t_build.delete("1.0", "end")

    def new_project(self):
        if not self._confirm_discard():
            return
        self._fresh_project()
        self.settings["last_project"] = ""
        save_settings(self.settings)
        self.status("New project - the folders are kept, change them here "
                    "if they should differ, then Fetch", C_OK)
        self.nb.select(0)

    def delete_project(self):
        """Remove the project FILE (a copy goes to Backups first)."""
        p = self.project.path
        if not p or not os.path.isfile(p):
            messagebox.showinfo(APP_NAME, "This project has not been saved, "
                                "so there is no file to delete.\n\nUse "
                                "File > New project to start again.",
                                parent=self.root)
            return
        if not messagebox.askyesno(
                APP_NAME,
                "Delete the project file\n\n%s\n\n"
                "(%d tracks and everything you typed on them)?\n\n"
                "A copy is kept in the Backups folder.  Your music, covers "
                "and lyric files are not touched."
                % (p, len(self.project.tracks)),
                icon="warning", default="no", parent=self.root):
            return
        try:
            self._gui_to_project()
            self._remember_folders()
            stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
            shutil.copy2(p, os.path.join(
                BAK_DIR, "%s_deleted_%s.bak" % (os.path.basename(p), stamp)))
            os.remove(p)
        except Exception as exc:
            log_exception("delete_project", exc)
            messagebox.showerror(APP_NAME, "Could not delete:\n%s" % exc,
                                 parent=self.root)
            return
        self._fresh_project()
        self.settings["last_project"] = ""
        save_settings(self.settings)
        self.status("Project deleted - an empty one with the same folders "
                    "is open", C_OK)
        self.nb.select(0)

    def open_project(self):
        if not self._confirm_discard():
            return
        p = filedialog.askopenfilename(
            title="Open a MusicSite project", initialdir=PROJ_DIR,
            filetypes=[("MusicSite project", "*.msite"),
                       ("JSON", "*.json"), ("All files", "*.*")])
        if not p:
            return
        try:
            self.project.load(p)
        except Exception as exc:
            log_exception("open_project", exc)
            messagebox.showerror(APP_NAME, "Could not open:\n%s" % exc,
                                 parent=self.root)
            return
        self._adopt_remembered_output()
        self._project_to_gui()
        self.settings["last_project"] = p
        save_settings(self.settings)
        self.status("Opened %s" % os.path.basename(p), C_OK)
        toast(self.root, "Project opened")
        self._lyrics_after_load()

    def save_project(self):
        if not self.project.path:
            return self.save_project_as()
        self._editor_to_track()
        self._gui_to_project()
        try:
            self.project.save()
        except Exception as exc:
            log_exception("save_project", exc)
            messagebox.showerror(APP_NAME, "Could not save:\n%s" % exc,
                                 parent=self.root)
            return False
        self.settings["last_project"] = self.project.path
        self._remember_folders()
        self._update_titlebar()
        self.status("Saved", C_OK)
        toast(self.root, "Saved")
        return True

    def save_project_as(self):
        self._editor_to_track()
        self._gui_to_project()
        default = slugify(self.project.site.get("site_title", "music")) \
            + ".msite"
        p = filedialog.asksaveasfilename(
            title="Save the project", initialdir=PROJ_DIR,
            initialfile=default, defaultextension=".msite",
            filetypes=[("MusicSite project", "*.msite"),
                       ("All files", "*.*")])
        if not p:
            return False
        try:
            self.project.save(p)
        except Exception as exc:
            log_exception("save_project_as", exc)
            messagebox.showerror(APP_NAME, "Could not save:\n%s" % exc,
                                 parent=self.root)
            return False
        self.settings["last_project"] = p
        save_settings(self.settings)
        self._update_titlebar()
        self.status("Saved as %s" % os.path.basename(p), C_OK)
        toast(self.root, "Saved")
        return True

    # *************************************************************************
    # DEL 18 - HELP AND ABOUT  (both close with ESC)
    # *************************************************************************
    def show_help(self):
        top = tk.Toplevel(self.root)
        top.title("MusicSite - Help")
        top.configure(bg=C_BG3)
        top.geometry("880x680")

        tk.Label(top, text="MusicSite - Help", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 14, "bold")).pack(pady=(12, 6))

        wrap = tk.Frame(top, bg=C_BG3)
        wrap.pack(fill="both", expand=True, padx=14, pady=(0, 10))
        sb = tk.Scrollbar(wrap)
        sb.pack(side="right", fill="y")            # scrollbar FIRST
        txt = mk_text(wrap, yscrollcommand=sb.set, font=("Consolas", 9))
        txt.pack(side="left", fill="both", expand=True)
        sb.configure(command=txt.yview)
        bind_mousewheel(txt)
        txt.insert("1.0", HELP_TEXT)

        row = tk.Frame(top, bg=C_BG3)
        row.pack(fill="x", padx=14, pady=(0, 12))
        mk_button(row, "Close  (Esc)", top.destroy, BTN_INFO,
                  width=14).pack(side="right")
        dialog_setup(top, self.root)

    def _heal_lyric_box(self):
        """Point lyric-file lines at the place a moved file now lives."""
        cur = self.t_lyrfiles.get("1.0", "end-1c")
        roots = [l.split("|", 1)[-1].strip() for l in
                 self.t_local.get("1.0", "end-1c").splitlines()
                 if l.strip() and not l.strip().startswith("#")]
        new, changes = heal_lyric_files_text(cur, roots)
        if not changes:
            return []
        self.t_lyrfiles.delete("1.0", "end")
        self.t_lyrfiles.insert("1.0", new)
        self.project.dirty = True
        self.status("Lyric file moved - now using %s"
                    % changes[0][1], C_OK)
        return changes

    def _lyrics_after_load(self):
        """Fill the words in as soon as a project is opened.

        A project remembers the words, but the words LIVE in his own files.
        One saved before the lyric files were pointed at - or one whose file
        has been rewritten since - would open with empty boxes, and nothing
        but "you should have pressed Fetch" would explain it.  Reading the
        files is local and takes no time, so it is simply done.
        """
        try:
            if not self.project.tracks:
                return
            self._heal_lyric_box()
            self._read_credits(quiet=True)
            self._gui_to_project()
            if not (self.project.source.get("lyrics_files") or "").strip():
                return
            index, paths = self._lyrics_index()
            if not index:
                return
            was_dirty = self.project.dirty
            got, gone = fill_lyrics(self.project.tracks, index)
            self.project.dirty = was_dirty     # nothing HE changed
            if got:
                self._refresh_tree(self._sel_index())
                self.status("Words filled in for %d track(s) from your "
                            "lyric file(s)%s"
                            % (len(got), ", %d without words" % len(gone)
                               if gone else ""), C_OK)
        except Exception as exc:
            log_exception("lyrics after load", exc)

    def _lyrics_index(self, refresh=False):
        """The songs in his lyric files, read once and kept."""
        self._heal_lyric_box()
        self._gui_to_project()
        pairs = parse_lyrics_files(self.project.source.get("lyrics_files", ""))
        paths = [p for _who, p in pairs]
        if not paths:
            return None, []
        key = tuple("%s|%s" % (w, p) for w, p in pairs) + tuple(
            str(os.path.getmtime(p)) if os.path.isfile(p) else "-"
            for p in paths)                    # a rewritten file is re-read
        if refresh or getattr(self, "_lyr_key", None) != key:
            index, report, songs = build_lyrics_index(pairs)
            self._lyr_index, self._lyr_key = index, key
            self._lyr_report, self._lyr_songs = report, songs
        return self._lyr_index, paths

    def show_line_picker(self):
        """Line by line for ONE song: what goes on the page and what does not.

        The rules are good but not infallible, and this is the answer to
        that: every line of the song, with a tick, and the reason the
        program gave for dropping it.  What he changes here is remembered
        as HIS choice and applied again after every Fetch, even if he
        rewrites the song around it.
        """
        i = self._sel_index()
        if i is None or i >= len(self.project.tracks):
            messagebox.showinfo(APP_NAME, "Pick a track in the list first.",
                                parent=self.root)
            return
        track = self.project.tracks[i]
        index, paths = self._lyrics_index()
        if not index:
            messagebox.showinfo(APP_NAME,
                                "There are no lyric files to pick lines "
                                "from.\n\nSource tab -> 'Lyric file(s) here' "
                                "-> Browse.", parent=self.root)
            return
        entry, how = find_lyrics(index, track.get("audio_name",
                                                  track.get("title", "")))
        if not entry:
            messagebox.showinfo(APP_NAME,
                                "No song called '%s' was found in your lyric "
                                "files.\n\nThe heading in the file has to "
                                "resemble the name of the mp3."
                                % (track.get("audio_name") or
                                   track.get("title", "?")),
                                parent=self.root)
            return

        rows = entry["rows"]
        keep = list(track.get("lyrics_keep") or [])
        drop = list(track.get("lyrics_drop") or [])
        state = []                             # one True/False per row
        keep_set = {x.strip() for x in keep if x.strip()}
        drop_set = {x.strip() for x in drop if x.strip()}
        for r in rows:
            on = r["keep"]
            s = r["line"].strip()
            if s and s in keep_set:
                on = True
            if s and s in drop_set:
                on = False
            state.append(on)

        top = tk.Toplevel(self.root)
        top.title("MusicSite - which lines go on the page?")
        top.configure(bg=C_BG3)
        top.geometry("980x680")

        tk.Label(top, text=entry["title"], bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w", padx=16,
                                                     pady=(14, 0))
        tk.Label(top, text="Ticked lines are published.  Click the tick "
                           "column, or mark rows and press Space.  "
                           "from %s" % os.path.basename(entry["file"]),
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(anchor="w", padx=16, pady=(2, 10))

        holder = tk.Frame(top, bg=C_BG3)
        holder.pack(fill="both", expand=True, padx=16)
        psb = tk.Scrollbar(holder)
        psb.pack(side="right", fill="y")           # scrollbar FIRST
        tree = ttk.Treeview(holder, columns=("line", "why"),
                            show="tree headings", yscrollcommand=psb.set,
                            selectmode="extended")
        tree.pack(side="left", fill="both", expand=True)
        psb.configure(command=tree.yview)
        tree.heading("#0", text="On")
        tree.column("#0", width=40, minwidth=40, stretch=False,
                    anchor="center")
        tree.heading("line", text="Line")
        tree.column("line", width=560, stretch=True)
        tree.heading("why", text="What the program calls it")
        tree.column("why", width=300, stretch=False)
        tree.tag_configure("off", foreground=C_FG_DIM)
        tree.tag_configure("blank", foreground=C_SEP)
        bind_mousewheel(tree)

        def draw():
            for n, (r, on) in enumerate(zip(rows, state)):
                text = r["line"] if r["line"].strip() else "     -"
                why = r["why"] or ("" if r["keep"] else r["kind"])
                if r["kind"] != "lyric" and not why:
                    why = r["kind"]
                tags = () if on else ("off",)
                if not r["line"].strip():
                    tags = ("blank",)
                iid = str(n)
                if tree.exists(iid):
                    tree.item(iid, text="✔" if on else "",
                              values=(text, why), tags=tags)
                else:
                    tree.insert("", "end", iid=iid, text="✔" if on else "",
                                values=(text, why), tags=tags)

        def toggle(indexes, value=None):
            for n in indexes:
                state[n] = (not state[n]) if value is None else value
            draw()

        def on_click(ev):
            if tree.identify_region(ev.x, ev.y) != "tree":
                return None
            iid = tree.identify_row(ev.y)
            if not iid:
                return None
            toggle([int(iid)])
            return "break"

        def on_space(_ev=None):
            sel = [int(x) for x in tree.selection()]
            if not sel:
                return None
            toggle(sel, not state[sel[0]])
            return "break"

        tree.bind("<Button-1>", on_click)
        tree.bind("<space>", on_space)
        draw()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=16, pady=12)

        def reset():
            for n, r in enumerate(rows):
                state[n] = r["keep"]
            draw()

        mk_button(btns, "Back to the program's choice", reset, BTN_NORM,
                  width=26).pack(side="left")
        mk_button(btns, "All on",
                  lambda: toggle(range(len(rows)), True), BTN_NORM,
                  width=8).pack(side="left", padx=6)
        mk_button(btns, "All off",
                  lambda: toggle(range(len(rows)), False), BTN_NORM,
                  width=8).pack(side="left")

        def save():
            new_keep, new_drop = [], []
            for r, on in zip(rows, state):
                s = r["line"].strip()
                if not s:
                    continue
                if on and not r["keep"]:
                    new_keep.append(s)
                elif not on and r["keep"]:
                    new_drop.append(s)
            track["lyrics_keep"] = new_keep
            track["lyrics_drop"] = new_drop
            track["lyrics"] = lyrics_from_rows(rows, new_keep, new_drop)
            track["lyrics_src"] = "picked" if (new_keep or new_drop) else "file"
            self.project.dirty = True
            self._suspend_editor = True
            try:
                self.t_lyrics.delete("1.0", "end")
                self.t_lyrics.insert("1.0", track["lyrics"])
            finally:
                self._suspend_editor = False
            self._load_editor()
            self._refresh_tree(i)
            self._update_titlebar()
            n = len(new_keep) + len(new_drop)
            self.status("%s: %d line(s) changed by hand"
                        % (track.get("title", ""), n), C_OK if n else C_FG_DIM)
            top.destroy()

        mk_button(btns, "Cancel", top.destroy, BTN_NORM,
                  width=10).pack(side="right")
        mk_button(btns, "Use these lines", save, BTN_MAIN,
                  width=16).pack(side="right", padx=6)
        dialog_setup(top, self.root)

    def show_lyrics_check(self):
        """Show, song by song, what is published and what is dropped.

        The whole point: he should never have to trust the rules blindly.
        Every line the program throws away is here, with the reason.
        """
        self._gui_to_project()
        pairs = parse_lyrics_files(self.project.source.get("lyrics_files", ""))
        paths = [p for _who, p in pairs]
        if not paths:
            messagebox.showinfo(APP_NAME,
                                "Point at your lyric files first.\n\n"
                                "Source tab -> 'Lyric file(s) here' -> "
                                "Browse.", parent=self.root)
            return
        index, report, songs = build_lyrics_index(pairs)
        if not index:
            messagebox.showwarning(APP_NAME,
                                   "No songs could be read out of:\n\n%s\n\n%s"
                                   % ("\n".join(paths), "\n".join(report)),
                                   parent=self.root)
            return

        rows = []                       # (label, entry or None, filename)
        if self.project.tracks:
            for t in self.project.tracks:
                entry, how = find_lyrics(index, t.get("audio_name",
                                                      t.get("title", "")))
                rows.append((t.get("title", "?"), entry, how))
        else:
            seen = set()
            for entry in index.values():
                if id(entry) in seen:
                    continue
                seen.add(id(entry))
                rows.append((entry["title"], entry, "exact"))
            rows.sort(key=lambda r: r[0].casefold())

        found = sum(1 for r in rows if r[1])
        top = tk.Toplevel(self.root)
        top.title("MusicSite - what is published, and what is not")
        top.configure(bg=C_BG3)
        top.geometry("1120x720")

        tk.Label(top, text="What goes on the page, and what stays yours",
                 bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w", padx=16,
                                                     pady=(14, 0))
        tk.Label(top, text="%d song(s) in %d file(s).  %d of %d here got "
                           "words.  Everything below the line in grey is "
                           "NOT published."
                           % (songs, len(paths), found, len(rows)),
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(anchor="w", padx=16, pady=(2, 10))

        body = tk.Frame(top, bg=C_BG3)
        body.pack(fill="both", expand=True, padx=16)

        left = tk.Frame(body, bg=C_BG3)
        left.pack(side="left", fill="y")
        lsb = tk.Scrollbar(left)
        lsb.pack(side="right", fill="y")           # scrollbar FIRST
        tree = ttk.Treeview(left, columns=("words", "cut"), show="tree headings",
                            yscrollcommand=lsb.set, height=24)
        tree.pack(side="left", fill="y")
        lsb.configure(command=tree.yview)
        tree.heading("#0", text="Song")
        tree.column("#0", width=300, stretch=False)
        tree.heading("words", text="Lines")
        tree.column("words", width=60, anchor="e", stretch=False)
        tree.heading("cut", text="Dropped")
        tree.column("cut", width=70, anchor="e", stretch=False)
        tree.tag_configure("none", foreground=C_WARN)

        right = tk.Frame(body, bg=C_BG3)
        right.pack(side="left", fill="both", expand=True, padx=(10, 0))
        rsb = tk.Scrollbar(right)
        rsb.pack(side="right", fill="y")           # scrollbar FIRST
        txt = mk_text(right, yscrollcommand=rsb.set, font=("Consolas", 10))
        txt.pack(side="left", fill="both", expand=True)
        rsb.configure(command=txt.yview)
        bind_mousewheel(txt)
        txt.tag_configure("head", foreground=C_ACCENT,
                          font=("Segoe UI", 11, "bold"))
        txt.tag_configure("cut", foreground=C_FG_DIM)
        txt.tag_configure("why", foreground=C_WARN)

        for i, (label, entry, how) in enumerate(rows):
            tree.insert("", "end", iid=str(i), text=label,
                        values=(len([x for x in entry["text"].splitlines()
                                     if x.strip()]) if entry else 0,
                                len(entry["dropped"]) if entry else "-"),
                        tags=() if entry else ("none",))

        def show(_ev=None):
            sel = tree.selection()
            if not sel:
                return
            label, entry, how = rows[int(sel[0])]
            txt.delete("1.0", "end")
            if not entry:
                txt.insert("end", label + "\n", "head")
                txt.insert("end", "\nNo words found for this song in your "
                                  "lyric files.\nThe heading in the file has "
                                  "to look like the file name of the song.\n")
                return
            txt.insert("end", entry["title"] + "\n", "head")
            txt.insert("end", "from %s%s\n\n"
                       % (os.path.basename(entry["file"]),
                          "" if how == "exact" else "  (matched by name)"),
                       "cut")
            txt.insert("end", entry["text"] + "\n")
            if entry["dropped"]:
                txt.insert("end", "\n" + "-" * 60 + "\n", "cut")
                txt.insert("end", "NOT PUBLISHED - %d line(s), yours alone\n"
                           % len(entry["dropped"]), "why")
                for kind, why, line in entry["dropped"]:
                    if not line.strip():
                        continue
                    txt.insert("end", "%-10s %s\n" % (kind, line), "cut")
            txt.see("1.0")

        tree.bind("<<TreeviewSelect>>", show)
        if rows:
            tree.selection_set("0")
            tree.focus("0")
            show()

        btns = tk.Frame(top, bg=C_BG3)
        btns.pack(fill="x", padx=16, pady=12)
        mk_button(btns, "Close  (Esc)", top.destroy, BTN_NORM,
                  width=14).pack(side="right")
        mk_button(btns, "Open the lyric file",
                  lambda: open_path(paths[0]), BTN_NORM,
                  width=20).pack(side="left")
        dialog_setup(top, self.root)

    def show_about(self):
        """Stylish About dialog with documentation link and donation info."""
        top = tk.Toplevel(self.root)
        top.title("About MusicSite")
        top.configure(bg=C_BG3)
        top.resizable(False, False)

        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr, text="\U0001F3B5", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text="MusicSite", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(hdr, text="Your own music page, built from one cloud folder",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 4))
        tk.Label(hdr, text="Version %s  (%s)" % (APP_VERSION, APP_DATE),
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(pady=(0, 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="\U0001F4C4  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 MusicSite, "
                           "a small gift is always welcome!",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=320, 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 in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                           ("Wise", WISE_URL)):
            lb = tk.Label(donate_frame, text="→  " + label, bg="#252535",
                          fg=C_ACCENT, font=("Segoe UI", 9, "underline"),
                          cursor="hand2", anchor="w")
            lb.pack(fill="x", pady=1)
            lb.bind("<Button-1>", lambda e, u=url: open_url(u))

        row = tk.Frame(top, bg=C_BG3)
        row.pack(fill="x", padx=20, pady=(6, 14))
        mk_button(row, "Help", lambda: (top.destroy(), self.show_help()),
                  BTN_INFO, width=10).pack(side="left")
        mk_button(row, "Close  (Esc)", top.destroy, BTN_NORM,
                  width=14).pack(side="right")
        dialog_setup(top, self.root)

    # *************************************************************************
    # DEL 19 - CLOSING
    # *************************************************************************
    def on_close(self):
        try:
            self._editor_to_track()
            self._gui_to_project()
        except Exception:
            pass
        if self.project.dirty:
            ans = messagebox.askyesnocancel(
                APP_NAME, "Save the project before closing?",
                parent=self.root)
            if ans is None:
                return
            if ans and not self.save_project():
                return
        try:
            self.settings["geometry"] = self.root.winfo_geometry()
            self.settings["last_output"] = self._outdir()
            if self.project.path:
                self.settings["last_project"] = self.project.path
            save_settings(self.settings)
        except Exception as exc:
            log_exception("on_close", exc)
        log("--- MusicSite closed ---")
        self.root.destroy()


# *****************************************************************************
# DEL 20 - WINDOW ICON  (external Icons/MusicSite.ico, never embedded)
# *****************************************************************************
def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = os.path.join(ICON_DIR, "%s.ico" % PROG)
    if not os.path.isfile(ico_path):                  # MusicSite_Loss.ico is optional: the plain icon is the fallback
        ico_path = os.path.join(ICON_DIR, "MusicSite.ico")
    if not os.path.isfile(ico_path):
        log("Icon not found: %s" % ico_path, "WARN")
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32
    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_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, 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 as exc:
        log_exception("_set_window_icon", exc)


# *****************************************************************************
# DEL 21 - MAIN
# *****************************************************************************
def main():
    CrashGuard.install()
    log("--- MusicSite %s starting (profile: %s, data: %s) ---"
        % (APP_VERSION, PROFILE or "none", HELP_DIR))
    if MIGRATION_NOTE:
        log(MIGRATION_NOTE)

    # AppUserModelID BEFORE tk.Tk()
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_ID)
    except Exception:
        pass

    root = tk.Tk()
    CrashGuard.root = root
    try:
        app = MusicSiteApp(root)
    except Exception as exc:
        text = log_exception("startup", exc)
        show_diagnostics(root, text)
        root.mainloop()
        return

    # after(0) - never directly, tkinter overwrites the icon otherwise
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()


if __name__ == "__main__":
    main()
