#!/usr/bin/env python3
"""A clean, temporary Kodi on Standa's TV for testing the first install (docs/plan/onboarding/000-plan.md).

Standa's own Kodi is never touched: Kodi for Android reads `/sdcard/xbmc_env.properties` at start, and its line
`xbmc.data=<folder>` makes Kodi use that folder for everything (kodi.wiki HOW-TO:Change data location for Android).
`up` stops Kodi, points it at an empty folder and starts it there: a clean Kodi, in Czech, with the published
repository. `down` stops it, deletes the file and the folder and starts Standa's Kodi again, and checks it.
Only on Standa's word in the current task (AGENTS.md, Standova TV).

JSON-RPC goes through `adb forward` (local 9192, never fresh_kodi.py's 9191) to the TV's port 9090 (the commands of fresh_kodi.py work the same: expect, click,
keys, info, rpc). The TMDb key is read from ~/.milionar-test/keys.json and sent into Kodi's open keyboard; it is never
printed and never stored on the TV.

Commands:
  up                  clean Kodi on the TV in Czech, with the published repository and the harness helper
  install             InstallAddon(plugin.video.milionar) from the repository, answer Kodi's Yes
  typekey             the TMDb key into Kodi's open keyboard, confirmed
  shot NAME           screenshot of the TV -> <scratch>/tv/NAME.png (1920x1080)
  log                 TV kodi.log lines since the last `log`
  try [--published]   for Standa to try (fresh_kodi.handover): up, install, the workspace's version unless
                      --published, the TMDb key entered in the guide, then hands off; `down` when he is done
  down                Standa's Kodi back: stop, delete the file and the folder, start, check
  expect/click/keys/info/rpc/builtin as in fresh_kodi.py
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import fresh_kodi as fk                      # noqa: E402  (its JSON-RPC commands, here forwarded to the TV)

# a port of its own: a command of fresh_kodi.py (9191) never reaches the TV, even while the clean Mac Kodi is down
fk.RPC_PORT = 9192

WORKSPACE = fk.WORKSPACE
ADB = ['adb', '-s', '127.0.0.1:15555']
PACKAGE = 'org.xbmc.kodi'
ENV_FILE = '/sdcard/xbmc_env.properties'
TEST = '/sdcard/milionar_fresh'              # the clean Kodi's data folder
OWN = '/sdcard/Android/data/org.xbmc.kodi/files/.kodi'
OUT = os.path.join(os.environ.get('MILIONAR_FRESH_ROOT') or tempfile.gettempdir(), 'tv')
STATE = os.path.join(OUT, 'state.json')


def adb(*args, check=True, capture=True):
    result = subprocess.run(ADB + list(args), check=check, stdout=subprocess.PIPE if capture else None,
                            stderr=subprocess.STDOUT, text=True)
    return result.stdout if capture else ''


def sh(command, check=True):
    return adb('shell', command, check=check)


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


def _stop():
    sh('am force-stop {}'.format(PACKAGE))
    time.sleep(2)


def _start():
    sh('am start -n {}/.Main'.format(PACKAGE))


def _home():
    """The clean Kodi's special://home (Kodi puts .kodi under the data folder, or uses it as it is)."""
    for folder in (TEST + '/.kodi', TEST):
        if 'userdata' in sh('ls {} 2>/dev/null'.format(folder), check=False):
            return folder
    return None


def _forward():
    adb('forward', 'tcp:{}'.format(fk.RPC_PORT), 'tcp:9090')


def _push_dir(local, remote):
    sh('mkdir -p {}'.format(remote))
    adb('push', local + '/.', remote)


def _staged_addons():
    """The published repository (as a user installs it) and the harness helper, as folders to push."""
    staging = tempfile.mkdtemp(prefix='milionar-tv-')
    repo = os.path.join(staging, 'addons', fk.REPO_ID)
    os.makedirs(repo)
    for name in ('addon.xml', 'icon.png'):
        with open(os.path.join(WORKSPACE, 'repository', fk.REPO_ID, name), 'rb') as source, \
                open(os.path.join(repo, name), 'wb') as target:
            target.write(source.read())
    profile, fk.PROFILE = fk.PROFILE, staging
    try:
        fk._helper()
    finally:
        fk.PROFILE = profile
    return os.path.join(staging, 'addons')


def cmd_up(args):
    if sh('ls {} 2>/dev/null'.format(ENV_FILE), check=False).strip():
        raise SystemExit('{} exists already: run `down` first'.format(ENV_FILE))
    try:
        _up()
    except BaseException:
        # never leave Standa's Kodi pointed at the test folder (the TV went to standby during `up` once)
        sh('rm -f {}'.format(ENV_FILE), check=False)
        sh('am force-stop {}'.format(PACKAGE), check=False)
        sh('am start -n {}/.Main'.format(PACKAGE), check=False)
        adb('forward', '--remove', 'tcp:{}'.format(fk.RPC_PORT), check=False)
        raise


def _up():
    _stop()
    sh('rm -rf {}'.format(TEST))
    sh('mkdir -p {}'.format(TEST))
    sh("echo 'xbmc.data={}' > {}".format(TEST, ENV_FILE))
    _start()                                         # first start: Kodi lays out its folders
    deadline = time.monotonic() + 120
    while time.monotonic() < deadline and not _home():
        time.sleep(1)
    home = _home()
    if not home:
        raise SystemExit('the clean Kodi did not create its folder: run `down`')
    time.sleep(6)
    _stop()
    addons = _staged_addons()                        # the addons go in while Kodi is down: it finds them at start
    for name in (fk.REPO_ID, fk.HELPER_ID):
        _push_dir(os.path.join(addons, name), '{}/addons/{}'.format(home, name))
    sh('cp -r {0}/addons/{1} {2}/addons/'.format(OWN, fk.CZECH, home))     # Czech from Standa's Kodi, read only
    _start()
    _forward()
    fk._wait(fk._rpc_up, 120, 'JSON-RPC of the clean Kodi on the TV')
    for addon in (fk.REPO_ID, fk.HELPER_ID, fk.CZECH):  # put there by hand: Kodi leaves them off
        fk.rpc('Addons.SetAddonEnabled', {'addonid': addon, 'enabled': True})
    fk.rpc('Settings.SetSettingValue', {'setting': 'locale.country', 'value': 'CZ'})
    fk.rpc('Settings.SetSettingValue', {'setting': 'locale.language', 'value': fk.CZECH})
    fk._wait(lambda: fk._info('System.Language') == 'Czech', 60, 'Kodi in Czech')
    _state(home=home, log_offset=0)
    print('clean Kodi on the TV: {}'.format(home))


def cmd_typekey(args):
    with open(fk.KEYS) as handle:
        key = json.load(handle).get('tmdb_api_key', '')
    if not key:
        raise SystemExit('no key in ' + fk.KEYS)
    for _ in range(50):
        if fk._info('System.CurrentWindow') and fk.rpc('XBMC.GetInfoBooleans', {
                'booleans': ['Window.IsActive(virtualkeyboard)']})['result'].get('Window.IsActive(virtualkeyboard)'):
            break
        time.sleep(0.2)
    fk.rpc('Input.SendText', {'text': key, 'done': True})
    print('key typed into Kodi\'s keyboard (value not shown)')


def cmd_shot(args):
    os.makedirs(OUT, exist_ok=True)
    raw = os.path.join(OUT, args.name + '.raw.png')
    with open(raw, 'wb') as handle:
        subprocess.run(ADB + ['exec-out', 'screencap', '-p'], check=True, stdout=handle)
    target = os.path.join(OUT, args.name + '.png')
    subprocess.run(['sips', '-z', '1080', '1920', raw, '--out', target], check=True, stdout=subprocess.DEVNULL)
    os.remove(raw)
    print(target)


def cmd_log(args):
    home = _state().get('home') or OWN
    lines = sh('cat {}/temp/kodi.log'.format(home), check=False).splitlines()
    offset = _state().get('log_offset', 0)
    _state(log_offset=len(lines))
    sys.stdout.write('\n'.join(lines[offset:]) + '\n')


def cmd_install(args):
    fk.cmd_install(args)


def after_install(args):
    """`try` without --published: the workspace's unpublished version over the installed one (its dependencies came with
    the published install, the TV cannot reach the Mac's repository); a restart of Kodi starts it."""
    if args.published:
        return
    build = tempfile.mkdtemp(prefix='milionar-tv-build-')
    try:
        package = subprocess.run(['sh', os.path.join(WORKSPACE, 'scripts', 'build_zip.sh'), build], check=True,
                                 stdout=subprocess.PIPE, text=True).stdout.strip().splitlines()[-1]
        with zipfile.ZipFile(package) as archive:
            archive.extractall(build)
        target = '{}/addons/{}'.format(_state()['home'], fk.ADDON_ID)
        _stop()
        sh('rm -rf {}'.format(target))
        _push_dir(os.path.join(build, fk.ADDON_ID), target)
    finally:
        shutil.rmtree(build, ignore_errors=True)
    _start()
    _forward()
    fk._wait(fk._rpc_up, 120, 'JSON-RPC of the clean Kodi on the TV')
    print('the workspace version on the TV')


def cmd_try(args):
    fk.handover(sys.modules[__name__], args)


def cmd_down(args):
    _stop()
    sh('rm -f {}'.format(ENV_FILE), check=False)
    sh('rm -rf {}'.format(TEST), check=False)
    adb('forward', '--remove', 'tcp:{}'.format(fk.RPC_PORT), check=False)
    _start()
    time.sleep(8)
    left = sh('ls {} {} 2>&1'.format(ENV_FILE, TEST), check=False)
    version = sh("grep -o 'version=\"[^\"]*\"' {}/addons/plugin.video.milionar/addon.xml | head -1".format(OWN),
                 check=False).strip()
    print('Standa\'s Kodi started; left behind: {}; his Milionář: {}'.format(
        'nothing' if 'No such file' in left else left.strip(), version))


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest='cmd', required=True)
    for name in ('up', 'install', 'typekey', 'log', 'down'):
        sub.add_parser(name)
    p = sub.add_parser('try')
    p.add_argument('--published', action='store_true', help='the published version instead of the workspace')
    p = sub.add_parser('shot')
    p.add_argument('name')
    p = sub.add_parser('expect')
    p.add_argument('label')
    p.add_argument('value')
    p.add_argument('--timeout', type=float, default=30)
    p = sub.add_parser('click')
    p.add_argument('id')
    p = sub.add_parser('keys')
    p.add_argument('keys', nargs='+')
    p.add_argument('--gap', type=float, default=0.6)
    p = sub.add_parser('info')
    p.add_argument('labels', nargs='+')
    p = sub.add_parser('rpc')
    p.add_argument('method')
    p.add_argument('params', nargs='?')
    p = sub.add_parser('builtin')
    p.add_argument('command')
    args = parser.parse_args()
    handler = globals().get('cmd_' + args.cmd) or getattr(fk, 'cmd_' + args.cmd)
    handler(args)


if __name__ == '__main__':
    main()
