#!/usr/bin/env python3
"""SPDX-License-Identifier: GPL-2.0-or-later. Rebuild the pinned standalone editor.

Usage: python3 rebuild.py --source circuitjs1-8ac55f22-corresponding-source.zip --output ./rebuilt
Requires Python 3.9+ with icon-source/requirements.txt, Node 24 and npm 11.
Regenerates the icons and installs the upstream lockfile dependencies.
No production credentials, framework installation or site checkout are required.
"""
import argparse
import difflib
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import zipfile

COMMIT = '8ac55f22a03606579b822b3dccd4dc10de1ddc5b'
UPSTREAM_ARCHIVE_SHA256 = 'a4ce8ee4a3f969902e4b6041ac76cf43ea536dcb00891b4fa74ce49c0c41d014'
SOURCE_ARCHIVE = 'circuitjs1-8ac55f22-corresponding-source.zip'
SOURCE_ROOT = 'circuitjs1-8ac55f22-corresponding-source'
SOURCE_SHA256 = 'de48917ab70f2c30fde20a30974ca38caadc2c26e0e99847c624e4ae81502102'


def modified_source_notice(changes):
    return ('/*\n'
            ' * Modified by Electronics Workbench on 2026-11-19.\n'
            ' * Changes: ' + changes + '\n'
            ' * SPDX-License-Identifier: GPL-2.0-or-later\n'
            ' * This modified CircuitJS1 file is licensed under GNU GPL version 2\n'
            ' * or, at your option, any later version. Existing upstream notices\n'
            ' * and authorship are preserved.\n'
            ' */\n')


def patched_main_source(source):
    start = source.index('// Registered only in production builds')
    end = source.index('const app = new CirSim();')
    source = source[:start] + '// Electronics Workbench hosting patch (2026-11-19): no optional offline service worker.\n' + source[end:]
    return modified_source_notice('Remove optional offline service-worker registration for standalone hosting.') + source


def hosted_html(original):
    html = original.replace('  <link rel="manifest" href="/circuit/manifest.json">', '  <meta name="viewport" content="width=device-width, initial-scale=1">\n  <meta name="robots" content="noindex, follow">\n  <meta http-equiv="Content-Security-Policy" content="default-src \'self\' data: blob:; script-src \'self\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data: blob:; connect-src \'self\'; font-src \'self\'; object-src \'none\'; base-uri \'self\';">')
    start = html.index('  <!-- Include the next line')
    end = html.index('</body>')
    html = (html[:start] + html[end:]).replace('</head>', '  <link rel="stylesheet" href="engine-theme.css">\n</head>')
    notice = ('<!--\n'
              '  Modified by Electronics Workbench on 2026-11-19.\n'
              '  Hosting changes: remove optional external Dropbox loader and absolute manifest;\n'
              '  add viewport, robots/resource policy and local editor theme.\n'
              '  SPDX-License-Identifier: GPL-2.0-or-later\n'
              '  Existing upstream authorship and licence notices are preserved.\n'
              '-->')
    return html.replace('<!DOCTYPE html>', '<!DOCTYPE html>\n' + notice, 1)


def patched_ui_source(source):
    """Apply only the documented controls/colour UI changes to the fixed source."""
    replacements = [
        ('    static theUI: UIManager;', '    static theUI: UIManager;\n    static readonly LIGHT_CANVAS_BACKGROUND = new Color("#e2eaf4");'),
        ('this.vpw = UIManager.VERTICALPANELWIDTH;', 'this.vpw = UIManager.VERTICALPANELWIDTH - 25;'),
        ('    powerLabel: HTMLElement;', '    powerLabel: HTMLElement;\n    powerHelp: HTMLElement;'),
        ('        this.powerLabel.textContent = Locale.LS("Power Brightness");', '        this.powerLabel.id = "power-colour-intensity-label";\n        this.powerLabel.textContent = Locale.LS("Power colour intensity");'),
        ('''        this.verticalPanel.appendChild(this.powerBar.element);
        this.setPowerBarEnable();''', '''        this.verticalPanel.appendChild(this.powerBar.element);
        this.powerHelp = document.createElement('p');
        this.powerHelp.id = 'power-colour-intensity-help';
        this.powerHelp.className = 'power-help';
        this.powerBar.element.setAttribute('aria-labelledby', this.powerLabel.id);
        this.powerBar.element.setAttribute('aria-describedby', this.powerHelp.id);
        this.verticalPanel.appendChild(this.powerHelp);
        this.setPowerBarEnable();'''),
        ('''            g.setColor(Color.white);
            this.cv.style.backgroundColor = '#fff';''', '''            g.setColor(UIManager.LIGHT_CANVAS_BACKGROUND);
            this.cv.style.backgroundColor = '#e2eaf4';'''),
        ('''    getBackgroundColor(): Color {
        if (this.menus.printableCheckItem.getState())
            return Color.white;
        return Color.black;
    }''', '''    getBackgroundColor(): Color {
        if (this.menus.printableCheckItem.getState())
            return UIManager.LIGHT_CANVAS_BACKGROUND;
        return Color.black;
    }'''),
        ('''        g.setColor(this.menus.printableCheckItem.getState() ? "#eee" : "#111");
        g.fillRect(leftX, this.app.circuitArea.height - h,
                   this.app.circuitArea.width, this.canvasHeight - this.app.circuitArea.height + h);''', '''        const bottomTop = this.app.circuitArea.height - h;
        const bottomHeight = this.canvasHeight - this.app.circuitArea.height + h;
        g.setColor(this.menus.printableCheckItem.getState() ? "#edf5ff" : "#111");
        g.fillRect(leftX, bottomTop, this.app.circuitArea.width, bottomHeight);
        if (this.menus.printableCheckItem.getState() && bottomHeight > 0) {
            g.setColor("#cbdcef");
            g.setLineWidth(1.0);
            g.drawRect(leftX + .5, bottomTop + .5,
                Math.max(0, this.app.circuitArea.width - leftX - 1), Math.max(0, bottomHeight - 1));
        }'''),
        ('''    setPowerBarEnable(): void {
        if (this.menus.powerCheckItem.getState()) {
            this.powerLabel.classList.remove('disabled');
            this.powerBar.enable();
        } else {
            this.powerLabel.classList.add('disabled');
            this.powerBar.disable();
        }
    }''', '''    setPowerBarEnable(): void {
        if (this.menus.powerCheckItem.getState()) {
            this.powerLabel.classList.remove('disabled');
            this.powerBar.enable();
            this.powerHelp.textContent = 'Display intensity only; circuit power is unchanged.';
        } else {
            this.powerLabel.classList.add('disabled');
            this.powerBar.disable();
            this.powerHelp.textContent = 'Enable Options → Show Power to colour components by power dissipation.';
        }
    }'''),
    ]
    for before, after in replacements:
        if source.count(before) != 1:
            raise ValueError('Pinned UIManager source no longer matches a single documented UI patch.')
        source = source.replace(before, after, 1)
    return modified_source_notice('Adjust sidebar control geometry/help, light canvas colours and information-panel styling; numerical algorithms are unchanged.') + source


def patched_element_source(source):
    """Outline light-mode current dots without changing their phase or spacing."""
    replacements = [
        ('''        for (let di = pos; di < dn; di += ds) {
            const x0 = Math.trunc(pa.x + di*dx/dn);
            const y0 = Math.trunc(pa.y + di*dy/dn);
            g.fillRect(x0-2, y0-2, 4, 4);
        }''', '''        const lightBackground = CircuitElm.app.menus.printableCheckItem.getState();
        for (let di = pos; di < dn; di += ds) {
            const x0 = Math.trunc(pa.x + di*dx/dn);
            const y0 = Math.trunc(pa.y + di*dy/dn);
            if (lightBackground) {
                g.setColor("#6b3d13");
                g.fillRect(x0-3, y0-3, 6, 6);
                g.setColor(CircuitElm.currentColor);
            }
            g.fillRect(x0-2, y0-2, 4, 4);
        }'''),
    ]
    for before, after in replacements:
        if source.count(before) != 1:
            raise ValueError('Pinned CircuitElm source no longer matches a single documented display patch.')
        source = source.replace(before, after, 1)
    return modified_source_notice('Outline light-mode current dots for contrast; current calculation, animation positions and dark-mode drawing are unchanged.') + source


def patched_style_source(source):
    before = '    background: #e3e8f3 url(images/hborder.png) repeat-x 0px -2003px;'
    after = '    background: #e3e8f3;'
    if source.count(before) != 1:
        raise ValueError('Pinned style.css no longer matches the documented legacy-image removal.')
    return modified_source_notice('Remove the unused legacy menu-background image URL while preserving its original solid colour.') + source.replace(before, after, 1)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    options = parser.parse_args()
    archive = options.source.resolve()
    output = options.output.resolve()
    resources = Path(__file__).resolve().parent
    if output.exists() and (not output.is_dir() or any(output.iterdir())):
        raise SystemExit('Choose a new or empty output directory so no legacy assets can be carried into the rebuild.')
    if hashlib.sha256(archive.read_bytes()).hexdigest() != SOURCE_SHA256:
        raise SystemExit('Source SHA-256 does not match the recorded downstream corresponding-source package.')
    with tempfile.TemporaryDirectory(prefix='circuitjs-rebuild-') as temporary:
        root = Path(temporary).resolve()
        with zipfile.ZipFile(archive) as source:
            for entry in source.infolist():
                target = (root / entry.filename).resolve()
                if root not in target.parents and root != target:
                    raise SystemExit('Unsafe archive member.')
            source.extractall(root)
        upstream = root / SOURCE_ROOT
        font_output = upstream / 'ts/public/circuitjs/font'
        expected_fonts = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in font_output.iterdir() if p.is_file()}
        subprocess.run([sys.executable, str(upstream / 'icon-source/build-icons.py'), '--output', str(font_output)], cwd=upstream, check=True)
        generated_fonts = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in font_output.iterdir() if p.is_file()}
        if generated_fonts != expected_fonts:
            raise ValueError('Regenerated fonts differ from the offered assets; use the recorded icon-source/requirements.txt and toolchain.')
        entry = upstream / 'ts/main.ts'
        entry.write_text(patched_main_source(entry.read_text()))
        ui_entry = upstream / 'ts/UIManager.ts'
        ui_entry.write_text(patched_ui_source(ui_entry.read_text()))
        element_entry = upstream / 'ts/CircuitElm.ts'
        element_entry.write_text(patched_element_source(element_entry.read_text()))
        style_entry = upstream / 'ts/style.css'
        style_entry.write_text(patched_style_source(style_entry.read_text()))
        # The fixed upstream Vite copy hook expects this directory, but the
        # downstream source package deliberately excludes the unused old PNGs.
        (upstream / 'ts/public/images').mkdir(exist_ok=True)
        subprocess.run(['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], cwd=upstream / 'ts', check=True)
        runtime_source = upstream / 'third-party-source/lz-string'
        runtime_record = json.loads((runtime_source / 'SOURCE.json').read_text())
        for relative, expected in runtime_record['files'].items():
            offered = runtime_source / relative
            installed = upstream / 'ts/node_modules/lz-string' / relative
            if hashlib.sha256(offered.read_bytes()).hexdigest() != expected or offered.read_bytes() != installed.read_bytes():
                raise ValueError('Offered runtime source differs from the locked lz-string build dependency: ' + relative)
        subprocess.run(['npm', 'run', 'build'], cwd=upstream / 'ts', check=True)
        dist = upstream / 'ts/dist'
        output.mkdir(parents=True, exist_ok=True)
        shutil.copytree(dist / 'circuitjs', output / 'circuitjs', dirs_exist_ok=True)
        # The upstream sidebar loads this deliberately empty placeholder page.
        shutil.copy2(dist / 'iframe.html', output / 'iframe.html')
        original = (dist / 'circuitjs.html').read_text()
        modified = hosted_html(original)
        (output / 'circuitjs.html').write_text(modified)
        (output / 'hosting.patch').write_text(''.join(difflib.unified_diff(original.splitlines(keepends=True), modified.splitlines(keepends=True), fromfile='dist/circuitjs.html', tofile='hosted/circuitjs.html')))
        for name in ['workbench.html', 'workbench.js', 'workbench.css', 'engine-theme.css', 'NOTICE.html', 'ASSET-PROVENANCE.json', 'BUILD.txt', 'rebuild.py', 'package-source.py', 'engine.patch', 'main.ts.txt', 'UIManager.ts.txt', 'CircuitElm.ts.txt', 'style.css.txt']:
            if (resources / name).resolve() != (output / name).resolve():
                shutil.copy2(resources / name, output / name)
        shutil.copytree(resources / 'licenses', output / 'licenses', dirs_exist_ok=True)
        shutil.copytree(upstream / 'icon-source', output / 'icon-source', dirs_exist_ok=True)
        shutil.copytree(upstream / 'third-party-source', output / 'third-party-source', dirs_exist_ok=True)
        if archive != output / SOURCE_ARCHIVE:
            shutil.copy2(archive, output / SOURCE_ARCHIVE)
        manifest = {'upstream': 'https://github.com/pfalstad/circuitjs1', 'commit': COMMIT, 'sourceArchiveFile': SOURCE_ARCHIVE, 'sourceArchiveKind': 'downstream-ts-corresponding-source', 'sourceArchiveSha256': SOURCE_SHA256, 'upstreamArchiveSha256': UPSTREAM_ARCHIVE_SHA256, 'files': {str(p.relative_to(output)): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(output.rglob('*')) if p.is_file() and p.name != 'manifest.json'}}
        (output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
        print('Rebuilt standalone editor at', output)


if __name__ == '__main__':
    main()
