#!/usr/bin/env python3
"""Rewrite OBS browser_source URLs in a scene-collection JSON from `file://` to
`http://127.0.0.1:1118/`.

Usage:
    python3 scripts/rewrite-scene-urls.py basic/scenes/Default_Stream_HUD.json

Idempotent: runs against a partially-converted file are no-ops.

Also moves the landing/static-hum.wav ffmpeg_source path to its new home under
webapp/public/audio/.

OBS MUST be closed when this runs — OBS rewrites scene files on exit.
"""
import json
import re
import sys


BROWSER_MAPPING = {
    'landing/index.html':           'http://127.0.0.1:1118/landing',
    'loading/index.html':           'http://127.0.0.1:1118/loading',
    'game/index.html':              'http://127.0.0.1:1118/game',
    'desktop/index.html':           'http://127.0.0.1:1118/desktop',
    'goodbye/index.html':           'http://127.0.0.1:1118/goodbye',
    'music/index.html':             'http://127.0.0.1:1118/music-daemon',
    'music-box/index.html':         'http://127.0.0.1:1118/music-box',
    'music-box/widget.html':        'http://127.0.0.1:1118/music-box/widget',
    'music-box/cover.html':         'http://127.0.0.1:1118/music-box/cover',
    'music-box/nc-music-box.html':  'http://127.0.0.1:1118/music-box/nc',
}

AUDIO_OLD = 'landing/static-hum.wav'
AUDIO_NEW = 'webapp/public/audio/static-hum.wav'


def rewrite_browser_source(src):
    s = src.get('settings', {})
    for old, new in BROWSER_MAPPING.items():
        for k in ('url', 'local_file'):
            v = s.get(k, '')
            if old in v:
                # Preserve query strings (e.g. ?bars=0).
                m = re.search(r'\?[^"\s]*$', v)
                qs = m.group(0) if m else ''
                s['url'] = new + qs
                s.pop('local_file', None)
                s['is_local_file'] = False
                return True
    return False


def rewrite_audio_source(src):
    s = src.get('settings', {})
    lf = s.get('local_file', '')
    if lf.endswith(AUDIO_OLD):
        s['local_file'] = lf.replace(AUDIO_OLD, AUDIO_NEW)
        return True
    return False


def main():
    if len(sys.argv) != 2:
        print(__doc__, file=sys.stderr)
        return 2
    path = sys.argv[1]
    doc = json.load(open(path))
    rewrites = 0
    for src in doc.get('sources', []):
        sid = src.get('id', '')
        if sid == 'browser_source':
            if rewrite_browser_source(src):
                rewrites += 1
        elif sid == 'ffmpeg_source':
            if rewrite_audio_source(src):
                rewrites += 1
    json.dump(doc, open(path, 'w'), indent=4, ensure_ascii=False)
    print(f'wrote {path} ({rewrites} sources rewritten)')


if __name__ == '__main__':
    sys.exit(main() or 0)
