#!/usr/bin/env python3
"""Windows Kodi in Standa's Whisky bottle "Kodi OLD" (Wine on the Mac): a real Windows Kodi 21.3 with an old addon.

The bottle's Kodi profile (drive_c/users/chudy/AppData/Roaming/Kodi) is Standa's prepared test state: Milionář 1.0
nightly, our repository.milionar from the Hub, TMDb and service logins saved. It is backed up once, read only, in
~/.milionar-test/whisky/ (outside the workspace: it holds credentials) and `restore` puts it back after every test.
Only the profile folder is backed up and restored, never the rest of the bottle.

Commands:
  prep                       JSON-RPC on 127.0.0.1:9193 (advancedsettings.xml) and the harness helper (builtins)
  start                      start Kodi in the bottle (WhiskyCmd run, Whisky's own Wine environment)
  stop                       quit Kodi (Application.Quit), kill it if it does not end
  restore                    Kodi not running: the profile back from the backup (then `prep` again for a test)
  serve / unserve            the workspace addon as repository.milionar on 127.0.0.1:8766 (bottle's repo pointed there)
  rpc Method '{"params"}'    any JSON-RPC call
  info Label ...             info labels
  keys Down Select ...       Input.* actions; text:"..." sends text
  click ID                   click control ID of the top window
  setting ID VALUE           a non-secret addon setting (account_server of a test backend: never Standa's Hub data)
  builtin 'ActivateWindow(Home)'
  shot NAME                  screenshot -> <shots>/NAME.png
  log [--all] [--grep RE]    the bottle's kodi.log since the last `log`
"""
import argparse
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import time

BOTTLE = os.path.expanduser('~/Library/Containers/com.franke.Whisky/Bottles/8B18C948-AA70-4999-89C4-63116DC3B139')
BOTTLE_NAME = 'Kodi OLD '                       # Whisky's name has the trailing space
WHISKY = '/Applications/Whisky.app/Contents/Resources/WhiskyCmd'
PROFILE = os.path.join(BOTTLE, 'drive_c', 'users', 'chudy', 'AppData', 'Roaming', 'Kodi')
KODI_EXE = r'C:\Program Files\Kodi\kodi.exe'
LOG = os.path.join(PROFILE, 'kodi.log')
HOME = os.path.expanduser('~/.milionar-test/whisky')
BACKUP = os.path.join(HOME, 'Kodi-profile-pristine-20261109')
SHOTS = os.environ.get('WHISKY_SHOTS') or os.path.join(HOME, 'shots')
STATE = os.path.join(HOME, 'state.json')
RPC_PORT = 9193                                  # Mac workspace Kodi 9090, fresh_kodi 9191, fresh_tv 9192
HELPER_ID = 'script.milionar.harness'
ADDON_ID = 'plugin.video.milionar'
REPO_PORT = 8766                                 # fresh_kodi's local repository has 8765
WORKSPACE = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))


def _state(**update):
    data = {}
    if os.path.exists(STATE):
        with open(STATE) as handle:
            data = json.load(handle)
    if update:
        data.update(update)
        with open(STATE, 'w') as handle:
            json.dump(data, handle)
    return data


def rpc(method, params=None, timeout=30):
    sock = socket.create_connection(('127.0.0.1', RPC_PORT), timeout=timeout)
    try:
        sock.sendall(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params or {}}).encode())
        buffer, decoder = '', json.JSONDecoder()
        while True:
            chunk = sock.recv(1 << 16)
            if not chunk:
                raise OSError('connection closed')
            buffer += chunk.decode('utf-8', 'replace')
            while buffer.strip():
                try:
                    obj, end = decoder.raw_decode(buffer.lstrip())
                except ValueError:
                    break
                buffer = buffer.lstrip()[end:]
                if obj.get('id') == 1:
                    return obj
    finally:
        sock.close()


def _rpc_up():
    try:
        return 'result' in rpc('JSONRPC.Ping', timeout=2)
    except OSError:
        return False


def _running():
    return subprocess.run(['pgrep', '-f', 'kodi.exe'], stdout=subprocess.DEVNULL).returncode == 0


def _wait(ready, seconds, what):
    deadline = time.monotonic() + seconds
    while time.monotonic() < deadline:
        if ready():
            return
        time.sleep(0.5)
    raise SystemExit('timeout: ' + what)


def _winpath(path):
    return 'Z:' + path.replace('/', '\\')


def cmd_prep(args):
    if _running():
        raise SystemExit('Kodi in the bottle is running: `stop` first')
    advanced = os.path.join(PROFILE, 'userdata', 'advancedsettings.xml')
    with open(advanced, 'w') as handle:
        handle.write('<advancedsettings><jsonrpc><tcpport>{}</tcpport></jsonrpc></advancedsettings>\n'.format(RPC_PORT))
    folder = os.path.join(PROFILE, 'addons', HELPER_ID)
    os.makedirs(folder, exist_ok=True)
    with open(os.path.join(folder, 'addon.xml'), 'w', encoding='utf-8') as handle:
        handle.write('<?xml version="1.0" encoding="UTF-8"?>\n<addon id="{}" name="Harness" version="1.0.0" '
                     'provider-name="test"><requires><import addon="xbmc.python" version="3.0.0"/></requires>'
                     '<extension point="xbmc.python.script" library="default.py"/>'
                     '<extension point="xbmc.addon.metadata"><platform>all</platform></extension></addon>\n'
                     .format(HELPER_ID))
    with open(os.path.join(folder, 'default.py'), 'w', encoding='utf-8') as handle:
        handle.write('import sys, xbmc, xbmcaddon\nif len(sys.argv) > 2 and sys.argv[1] == "builtin":\n'
                     '    xbmc.executebuiltin(sys.argv[2])\n'
                     'elif len(sys.argv) > 3 and sys.argv[1] == "setting":   # a non-secret setting (account_server)\n'
                     '    xbmcaddon.Addon("plugin.video.milionar").setSetting(sys.argv[2], sys.argv[3])\n')
    os.makedirs(SHOTS, exist_ok=True)
    print('prepared: JSON-RPC {} and {}'.format(RPC_PORT, HELPER_ID))


def cmd_start(args):
    if _running():
        raise SystemExit('Kodi in the bottle is already running')
    offset = os.path.getsize(LOG) if os.path.exists(LOG) else 0
    subprocess.Popen([WHISKY, 'run', BOTTLE_NAME, KODI_EXE], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                     start_new_session=True)
    _wait(_rpc_up, 120, 'JSON-RPC of the bottle Kodi on {}'.format(RPC_PORT))
    _state(log_offset=0)              # Kodi rotates kodi.log at start
    rpc('Addons.SetAddonEnabled', {'addonid': HELPER_ID, 'enabled': True})
    rpc('Settings.SetSettingValue', {'setting': 'debug.screenshotpath', 'value': _winpath(SHOTS) + '\\'})
    print('bottle Kodi up (previous log offset {})'.format(offset))


def cmd_stop(args):
    if _rpc_up():
        try:
            rpc('Application.Quit', timeout=5)
        except OSError:
            pass
    deadline = time.monotonic() + 40
    while _running() and time.monotonic() < deadline:
        time.sleep(0.5)
    if _running():
        subprocess.run(['pkill', '-f', 'kodi.exe'])
        print('killed (did not quit in 40 s)')
    else:
        print('quit')


def cmd_restore(args):
    cmd_unserve(args)
    if _running():
        raise SystemExit('Kodi in the bottle is running: `stop` first')
    if not os.path.isdir(os.path.join(BACKUP, 'userdata')):
        raise SystemExit('missing backup ' + BACKUP)
    shutil.rmtree(PROFILE)
    subprocess.run(['cp', '-c', '-R', '-p', BACKUP, PROFILE], check=True)
    subprocess.run(['chmod', '-R', 'u+w', PROFILE], check=True)
    _state(log_offset=0)
    print('restored ' + PROFILE)


def cmd_serve(args):
    """The workspace addon as our repository on 127.0.0.1:REPO_PORT, the bottle's repository.milionar pointed there
    (until `restore`): the household's way of installing (Doplňky -> Milionář Repository -> Instalovat), unpublished code."""
    import hashlib
    import xml.etree.ElementTree as ET
    import zipfile
    if _running():
        raise SystemExit('Kodi in the bottle is running: `stop` first (it reads the repository at start)')
    cmd_unserve(args)
    repo = os.path.join(HOME, 'repo')
    shutil.rmtree(repo, ignore_errors=True)
    os.makedirs(os.path.join(repo, ADDON_ID))
    built = subprocess.run(['sh', os.path.join(WORKSPACE, 'scripts', 'build_zip.sh'), os.path.join(repo, ADDON_ID)],
                           check=True, stdout=subprocess.PIPE, text=True).stdout.strip().splitlines()[-1]
    with zipfile.ZipFile(built) as archive:
        plugin_xml = archive.read(ADDON_ID + '/addon.xml').decode('utf-8')
        for name in archive.namelist():                    # the addon's art, which Kodi reads from the datadir
            if name.startswith(ADDON_ID + '/resources/media/brand/') or name in (ADDON_ID + '/icon.png',
                                                                                 ADDON_ID + '/fanart.jpg'):
                archive.extract(name, repo)
    url = 'http://127.0.0.1:{}/'.format(REPO_PORT)
    repo_xml_path = os.path.join(PROFILE, 'addons', 'repository.milionar', 'addon.xml')
    tree = ET.parse(repo_xml_path)
    folder = tree.getroot().find(".//extension[@point='xbmc.addon.repository']/dir")
    folder.find('info').text = url + 'addons.xml'
    folder.find('checksum').text = url + 'addons.xml.md5'
    folder.find('datadir').text = url
    tree.write(repo_xml_path, encoding='UTF-8', xml_declaration=True)
    strip = lambda text: re.sub(r'^\s*<\?xml[^>]*\?>\s*', '', text).strip()
    with open(repo_xml_path, encoding='utf-8') as handle:
        repo_xml = handle.read()
    addons = '<?xml version="1.0" encoding="UTF-8"?>\n<addons>\n{}\n{}\n</addons>\n'.format(strip(plugin_xml),
                                                                                            strip(repo_xml))
    with open(os.path.join(repo, 'addons.xml'), 'w', encoding='utf-8') as handle:
        handle.write(addons)
    with open(os.path.join(repo, 'addons.xml.md5'), 'w') as handle:
        handle.write(hashlib.md5(addons.encode('utf-8')).hexdigest())
    server = subprocess.Popen([sys.executable, '-m', 'http.server', str(REPO_PORT), '--bind', '127.0.0.1',
                               '--directory', repo], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                              start_new_session=True)
    _state(server=server.pid)
    print('serving {} as repository.milionar on {}'.format(os.path.basename(built), url))


def cmd_unserve(args):
    pid = _state().get('server')
    if pid:
        try:
            os.kill(pid, 15)
        except OSError:
            pass
        _state(server=None)


def cmd_rpc(args):
    print(json.dumps(rpc(args.method, json.loads(args.params) if args.params else None), ensure_ascii=False, indent=1))


def cmd_info(args):
    print(json.dumps(rpc('XBMC.GetInfoLabels', {'labels': args.labels})['result'], ensure_ascii=False, indent=1))


def cmd_keys(args):
    for key in args.keys:
        if key.startswith('text:'):
            rpc('Input.SendText', {'text': key[5:], 'done': False})
        else:
            rpc('Input.' + key)
        time.sleep(args.gap)


def builtin(command):
    answer = rpc('Addons.ExecuteAddon', {'addonid': HELPER_ID, 'params': ['builtin', command], 'wait': False})
    if 'error' in answer:
        raise SystemExit(json.dumps(answer['error']))


def cmd_setting(args):
    answer = rpc('Addons.ExecuteAddon', {'addonid': HELPER_ID, 'params': ['setting', args.id, args.value], 'wait': False})
    if 'error' in answer:
        raise SystemExit(json.dumps(answer['error']))


def cmd_click(args):
    builtin('SendClick({})'.format(args.id))


def cmd_builtin(args):
    builtin(args.command)


def cmd_shot(args):
    os.makedirs(SHOTS, exist_ok=True)
    for name in os.listdir(SHOTS):
        if name.startswith('screenshot'):
            os.remove(os.path.join(SHOTS, name))
    rpc('Input.ExecuteAction', {'action': 'screenshot'})
    deadline = time.monotonic() + 15
    while time.monotonic() < deadline:
        found = [name for name in os.listdir(SHOTS) if name.startswith('screenshot')]
        if found:
            source, target = os.path.join(SHOTS, found[0]), os.path.join(SHOTS, args.name + '.png')
            size = -1                     # Kodi under Wine writes the PNG slowly: wait until it stops growing
            while size != os.path.getsize(source) or size == 0:
                size = os.path.getsize(source)
                time.sleep(0.6)
            subprocess.run(['sips', '-Z', '1920', source, '--out', target], check=True, stdout=subprocess.DEVNULL)
            os.remove(source)
            print(target)
            return
        time.sleep(0.2)
    raise SystemExit('no screenshot')


def cmd_log(args):
    state = _state()
    with open(LOG, 'rb') as handle:
        data = handle.read()
    offset = 0 if args.all or state.get('log_offset', 0) > len(data) else state.get('log_offset', 0)
    text = data[offset:].decode('utf-8', 'replace')
    _state(log_offset=len(data))
    for line in text.splitlines():
        if not args.grep or re.search(args.grep, line, re.I):
            print(line)


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest='cmd', required=True)
    for name in ('prep', 'start', 'stop', 'restore', 'serve', 'unserve'):
        sub.add_parser(name)
    p = sub.add_parser('rpc'); p.add_argument('method'); p.add_argument('params', nargs='?')
    p = sub.add_parser('info'); p.add_argument('labels', nargs='+')
    p = sub.add_parser('keys'); p.add_argument('keys', nargs='+'); p.add_argument('--gap', type=float, default=0.4)
    p = sub.add_parser('click'); p.add_argument('id')
    p = sub.add_parser('setting'); p.add_argument('id'); p.add_argument('value')
    p = sub.add_parser('builtin'); p.add_argument('command')
    p = sub.add_parser('shot'); p.add_argument('name')
    p = sub.add_parser('log'); p.add_argument('--all', action='store_true'); p.add_argument('--grep')
    args = parser.parse_args()
    globals()['cmd_' + args.cmd](args)


if __name__ == '__main__':
    main()
