#!/usr/bin/env python3
"""Inject the standalone detail-page editor plugin into an HTML file.

Usage:
  python3 inject_detail_page_editor.py /path/to/detail.html
  python3 inject_detail_page_editor.py /path/to/detail.html --out /path/to/detail_editable.html

The script copies detail-page-editor.js next to the output HTML and inserts:
  <script src="./detail-page-editor.js" data-detail-page-editor></script>
"""
from __future__ import annotations

import argparse
import shutil
from pathlib import Path

SCRIPT_TAG = '<script src="./detail-page-editor.js" data-detail-page-editor></script>'


def inject(html: str) -> str:
    if 'data-detail-page-editor' in html or 'detail-page-editor.js' in html:
        return html
    lower = html.lower()
    idx = lower.rfind('</body>')
    if idx >= 0:
        return html[:idx] + '  ' + SCRIPT_TAG + '\n' + html[idx:]
    return html.rstrip() + '\n' + SCRIPT_TAG + '\n'


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument('html', type=Path)
    parser.add_argument('--out', type=Path, default=None)
    parser.add_argument('--no-backup', action='store_true')
    args = parser.parse_args()

    src = args.html.expanduser().resolve()
    if not src.exists():
        raise SystemExit(f'HTML not found: {src}')
    out = args.out.expanduser().resolve() if args.out else src

    plugin_src = Path(__file__).resolve().parent / 'detail-page-editor.js'
    if not plugin_src.exists():
        raise SystemExit(f'Plugin JS not found: {plugin_src}')

    if out == src and not args.no_backup:
        backup = src.with_suffix(src.suffix + '.before-editor.bak')
        if not backup.exists():
            shutil.copy2(src, backup)
            print(f'backup: {backup}')

    html = src.read_text(encoding='utf-8')
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(inject(html), encoding='utf-8')
    shutil.copy2(plugin_src, out.parent / 'detail-page-editor.js')
    print(f'html: {out}')
    print(f'plugin: {out.parent / "detail-page-editor.js"}')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
