#!/usr/bin/env python3
"""Install the Ruen public beta on Linux; run without sudo."""
import argparse
import contextlib
import fcntl
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import shutil
import sys
import tempfile
import time
import uuid

sys.dont_write_bytecode = True

BUNDLE = Path(__file__).resolve().parent
sys.path.insert(0, str(BUNDLE / 'Tools'))
import ruen_dependencies as deps
import ruen_migrate as migration
CONFIG = Path.home() / '.config/ruen-ui/install.json'
SAVES = ('RuenUI', 'GunSilencerForever', 'Leatrix_Plus', 'Leatrix_Maps', 'Spoken', 'Spoken_Quests')


def no_links(path):
    deps.no_links(path)
    if path.is_dir():
        for child in path.rglob('*'):
            if child.is_symlink(): raise ValueError('Linked content cannot be replaced: ' + str(child))


def game_path(value):
    root = Path(value).expanduser().absolute()
    no_links(root)
    if root.name != '_forever_': root = root / '_forever_'
    if not (root / 'Wow.exe').is_file(): raise ValueError('Choose the Forever folder containing Wow.exe.')
    return root


def closed(root):
    for path in Path('/proc').glob('[0-9]*/cmdline'):
        try:
            args = path.read_bytes().decode(errors='replace').split('\0')[:2]
            if any(x.replace('\\', '/').rsplit('/', 1)[-1].lower() in {'wow.exe', 'wowclassic.exe', 'wow-64.exe'} for x in args):
                raise RuntimeError('Close WoW before installing or restoring. Hardware evaluation can run while playing.')
        except OSError: pass


@contextlib.contextmanager
def locked(path):
    deps.no_links(path)
    with path.open('a') as lock:
        try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError: raise RuntimeError('Another Ruen installer is using this folder: ' + str(path.parent))
        yield


def verify(bundle):
    manifest = json.loads((bundle / 'manifest.json').read_text())
    if manifest.get('format') != 1: raise ValueError('Unsupported package manifest')
    expected = set()
    for entry in manifest['files']:
        rel = deps.safe_relative(entry['path']); path = bundle / rel; deps.no_links(path)
        if rel.as_posix() in expected: raise ValueError('Duplicate package entry')
        expected.add(rel.as_posix())
        if not path.is_file() or deps.digest(path) != entry['sha256']:
            raise ValueError('Package integrity check failed: ' + str(rel))
    actual = {p.relative_to(bundle).as_posix() for p in bundle.rglob('*') if p.is_file() and p != bundle / 'manifest.json'}
    if actual != expected: raise ValueError('Package file list differs from its manifest; extract a fresh ZIP.')
    if not deps.compatible(bundle / 'RuenUI'): raise ValueError('Ruen is not marked compatible with Forever.')


def copy(src, dst):
    dst.parent.mkdir(parents=True, exist_ok=True)
    if src.is_dir(): shutil.copytree(src, dst)
    else: shutil.copy2(src, dst)


def remove(path):
    if path.is_dir(): shutil.rmtree(path)
    elif path.exists(): path.unlink()


def save_paths(root):
    yield 'WTF/Config.wtf'
    accounts = root / 'WTF/Account'
    if not accounts.exists(): return
    for account in accounts.iterdir():
        if not account.is_dir() or account.name == 'SavedVariables': continue
        for name in ['config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-account.txt']:
            yield (account / name).relative_to(root).as_posix()
        for addon in SAVES:
            yield (account / 'SavedVariables' / (addon + '.lua')).relative_to(root).as_posix()
        for realm in account.iterdir():
            if not realm.is_dir() or realm.name == 'SavedVariables': continue
            for character in realm.iterdir():
                if not character.is_dir() or character.name == 'SavedVariables': continue
                for rel in ['config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-character.txt', 'SavedVariables/RuenUI.lua']:
                    yield (character / rel).relative_to(root).as_posix()


def allowed_restore(rel, managed):
    path = deps.safe_relative(rel)
    if path.parts[:2] == ('Interface', 'AddOns'):
        return len(path.parts) == 3 and path.name in managed
    if rel == 'WTF/Config.wtf': return True
    if path.parts[:2] != ('WTF', 'Account'): return False
    if len(path.parts) in (4, 6) and path.name in {'AddOns.txt', 'config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-account.txt', 'edit-mode-cache-character.txt'}: return True
    return len(path.parts) in (5, 7) and path.parts[-2] == 'SavedVariables' and path.name in {x + suffix for x in (*SAVES, migration.LEGACY_ADDON) for suffix in ('.lua', '.lua.bak')}


def restore(root, backup):
    backup = backup.absolute(); no_links(backup)
    receipt = json.loads((backup / 'receipt.json').read_text())
    if receipt.get('format') != 2 or receipt['gameRoot'] != str(root) or backup.parent != root / 'Ruen-UI-Backups':
        raise ValueError('Use a public-beta backup belonging to this installation.')
    known = {'RuenUI', migration.LEGACY_ADDON}
    for p in deps.selected(BUNDLE, 'enru'): known.update(p['folders'])
    managed = set(receipt['managed'])
    if not managed <= known: raise ValueError('Unknown addon in backup receipt')
    seen = set()
    for entry in receipt['entries']:
        rel = entry['path']
        if rel in seen or not allowed_restore(rel, managed): raise ValueError('Unsafe backup target: ' + rel)
        seen.add(rel); no_links(root / rel); no_links(backup / 'original' / rel)
        if entry['existed'] and not (backup / 'original' / rel).exists(): raise ValueError('Incomplete backup: ' + rel)
    retained = backup / ('before-restore-' + uuid.uuid4().hex)
    for entry in receipt['entries']:
        closed(root); rel = entry['path']; target = root / rel
        if target.exists():
            dest = retained / rel; dest.parent.mkdir(parents=True, exist_ok=True); shutil.move(str(target), dest)
        if entry['existed']: copy(backup / 'original' / rel, target)
    print('Pre-install files restored; later files retained in:', retained)


def install(root, args):
    cache = Path(args.cache).expanduser().absolute(); deps.no_links(cache); cache.mkdir(parents=True, exist_ok=True)
    with locked(cache / '.install.lock'), tempfile.TemporaryDirectory(prefix='stage-', dir=cache) as temporary:
        print('Ruen beta applies ESDF controls and a native-frame layout. /ruen restore undoes its preferences.', flush=True)
        sources, enabled = deps.prepare(BUNDLE, root, Path(temporary), args.voice_packs, cache)
        closed(root)
        # Keep machine-specific reports and a previously requested language on upgrades.
        staged_ruen = Path(temporary) / 'RuenUI'
        copy(sources['RuenUI'], staged_ruen)
        for name in ('HardwareProfile.lua', 'LanguageDefaults.lua'):
            old = root / 'Interface/AddOns/RuenUI' / name
            if old.is_file(): shutil.copy2(old, staged_ruen / name)
        sources['RuenUI'] = staged_ruen
        entries = {rel: {'path': rel, 'backupOnly': True} for rel in save_paths(root)}
        for name, source in sources.items(): entries['Interface/AddOns/' + name] = {'path': 'Interface/AddOns/' + name, 'source': str(source)}
        accounts = root / 'WTF/Account'
        enable_files = list(accounts.rglob('AddOns.txt')) if accounts.exists() else []
        # Fresh characters use WoW's default-enabled behavior for newly installed addons.
        for path in enable_files:
            no_links(path)
            kept = [line for line in path.read_text().splitlines() if line.split(':', 1)[0].strip() not in (*enabled, migration.LEGACY_ADDON)]
            rel = path.relative_to(root).as_posix()
            entries[rel] = {'path': rel, 'text': '\n'.join(kept + [n + ': enabled' for n in enabled]) + '\n'}
        for rel, text in migration.plan(root, include_addons=False): entries[rel] = {'path': rel, 'text': text}
        legacy = 'Interface/AddOns/' + migration.LEGACY_ADDON
        if (root / legacy).exists(): entries[legacy] = {'path': legacy, 'text': None}
        for entry in entries.values(): no_links(root / entry['path'])
        changes = [e for e in entries.values() if not e.get('backupOnly')]
        def matches(e):
            target = root / e['path']
            if 'source' in e:
                source = Path(e['source'])
                if not target.is_dir(): return False
                a = {p.relative_to(source): deps.digest(p) for p in source.rglob('*') if p.is_file()}
                b = {p.relative_to(target): deps.digest(p) for p in target.rglob('*') if p.is_file()}
                return a == b
            if e['text'] is None: return not target.exists()
            return target.is_file() and target.read_text() == e['text']
        if args.language == 'auto' and all(matches(e) for e in changes):
            print('This package is already installed. No files or backups added.'); return
        needed = sum(p.stat().st_size for e in entries.values() for p in
                     ([root / e['path']] if (root / e['path']).is_file() else (root / e['path']).rglob('*')) if p.is_file())
        needed += sum(p.stat().st_size for source in sources.values() for p in source.rglob('*') if p.is_file())
        if shutil.disk_usage(root).free < needed + 128 * 1024**2:
            raise OSError('Not enough game-drive space for installation and rollback backup.')
        backup = root / 'Ruen-UI-Backups' / (time.strftime('%Y%m%d-%H%M%S') + '-' + uuid.uuid4().hex[:8])
        deps.no_links(backup); backup.mkdir(parents=True)
        receipt = {'format': 2, 'gameRoot': str(root), 'managed': list(sources), 'status': 'prepared', 'entries': []}
        for entry in entries.values():
            target = root / entry['path']; entry['existed'] = target.exists()
            receipt['entries'].append({'path': entry['path'], 'existed': entry['existed']})
            if target.exists(): copy(target, backup / 'original' / entry['path'])
        receipt_path = backup / 'receipt.json'; receipt_path.write_text(json.dumps(receipt, indent=2))
        changed = []
        try:
            for entry in entries.values():
                if entry.get('backupOnly'): continue
                closed(root); target = root / entry['path']; changed.append(entry); remove(target)
                if 'source' in entry: copy(Path(entry['source']), target)
                elif entry['text'] is not None:
                    target.parent.mkdir(parents=True, exist_ok=True); target.write_text(entry['text'], encoding='utf-8')
            if args.language != 'auto':
                locale = 'ruRU' if args.language == 'ru' else 'enUS'
                (root / 'Interface/AddOns/RuenUI/LanguageDefaults.lua').write_text('local _, P = ...\nP.installLanguage = "' + locale + '"\nP.installLanguageRequest = "public-' + uuid.uuid4().hex + '"\n')
            receipt['status'] = 'installed'; receipt_path.write_text(json.dumps(receipt, indent=2))
        except Exception:
            for entry in reversed(changed):
                target = root / entry['path']; remove(target)
                if entry['existed']: copy(backup / 'original' / entry['path'], target)
            receipt['status'] = 'rolled_back'; receipt_path.write_text(json.dumps(receipt, indent=2)); raise
    try:
        CONFIG.parent.mkdir(parents=True, exist_ok=True); CONFIG.write_text(json.dumps({'gameRoot': str(root)}))
    except OSError as error: print('Installed, but could not remember the game path:', error)
    print('Ruen installed. Backup:', backup)
    print('Launch WoW. /ruen help shows controls; /ruen guns off restores nearby gunfire.')
    print('For English/Russian game text and speech, install both languages through Battle.net.')


def main():
    spec = importlib.util.spec_from_file_location('hardware', BUNDLE / 'Tools/ruen_hardware.py')
    hardware = importlib.util.module_from_spec(spec); spec.loader.exec_module(hardware)
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--wow'); parser.add_argument('--voice-packs', choices=('none', 'en', 'enru'), default='en')
    parser.add_argument('--cache', default=str(Path.home() / '.cache/ruen-ui/downloads'))
    parser.add_argument('--language', choices=('auto', 'en', 'ru'), default='auto')
    parser.add_argument('--restore', type=Path); parser.add_argument('--non-interactive', action='store_true')
    parser.add_argument('--optimize', nargs='?', const=60, type=hardware.fps_target, metavar='FPS')
    parser.add_argument('--seconds', type=int, default=600); args = parser.parse_args()
    value = args.wow
    if not value and CONFIG.is_file(): value = json.loads(CONFIG.read_text())['gameRoot']
    if not value:
        candidates = []
        for base, pattern in [(Path('/opt/games'), '*/*/compatdata/pfx/drive_c/Program Files*/World of Warcraft/_forever_/Wow.exe'), (Path.home() / '.wine', 'drive_c/Program Files*/World of Warcraft/_forever_/Wow.exe'), (Path.home() / '.local/share/Steam/steamapps/compatdata', '*/pfx/drive_c/Program Files*/World of Warcraft/_forever_/Wow.exe'), (Path.home() / 'Games', '**/_forever_/Wow.exe')]:
            if base.exists(): candidates.extend(base.glob(pattern))
        found = list(dict.fromkeys(str(p.parent) for p in candidates))
        if len(found) == 1: value = found[0]
        elif args.non_interactive: parser.error('Supply --wow; no unique Forever installation was found.')
        else: value = input('Paste the Forever folder containing Wow.exe: ')
    root = game_path(value)
    if args.optimize is not None:
        if not 1 <= args.seconds <= 1800: parser.error('--seconds must be 1–1800')
        result = hardware.evaluate(args.seconds); hardware.write_report(root, result, True, args.optimize)
        print(result['evidence']); print('Type /reload to import the hardware report.'); return
    closed(root)
    with locked(root / '.ruen-install.lock'):
        if args.restore: restore(root, args.restore)
        else: verify(BUNDLE); install(root, args)


if __name__ == '__main__':
    try: main()
    except Exception as error:
        print('Setup stopped:', error, file=sys.stderr); sys.exit(1)
