#!/usr/bin/env python3
# summary: Install, select and remove language versions for your account.
"""Usage: starchaser languages status | install|use|remove LANGUAGE VERSION

Versions are managed by mise, in your home folder. System languages and project files are kept.
Use latest or a version number. Install keeps the current default; use installs and selects a default.
"""
import fcntl
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path

LANGUAGES = [('python', 'Python'), ('node', 'Node.js'), ('go', 'Go'), ('rust', 'Rust'),
             ('ruby', 'Ruby'), ('java', 'Java'), ('php', 'PHP'), ('elixir', 'Elixir'),
             ('erlang', 'Erlang'), ('bun', 'Bun'), ('deno', 'Deno'), ('zig', 'Zig'), ('dotnet', '.NET')]
LOCK_DIR = Path(os.environ.get('XDG_STATE_HOME') or Path.home() / '.local/state') / 'starchaser'
VERSION = re.compile(r'[A-Za-z0-9][A-Za-z0-9._+-]{0,79}\Z')


def mise(args):
    # Start at home so a project in the calling directory cannot run hooks or change the requested default.
    result = subprocess.run(['mise', *args], cwd=Path.home(), capture_output=True, text=True,
                            env={**os.environ, 'MISE_YES': '1', 'MISE_COLOR': '0'})
    if result.returncode:
        raise OSError("The language change couldn't finish. Check your internet connection, then try again.")
    return result.stdout


def version_key(version):
    # Compare numeric components as numbers, so 22 is newer than 9.
    return [(1, int(part)) if part.isdigit() else (0, part) for part in re.split(r'(\d+)', version)]


def status():
    installed = bool(shutil.which('mise'))
    versions = json.loads(mise(['ls', '--installed', '--json'])) if installed else {}
    if not isinstance(versions, dict):
        raise ValueError("The installed language list couldn't be read.")
    rows = []
    for tool, name in LANGUAGES:
        entries = [v for v in versions.get(tool, []) if isinstance(v, dict)]
        rows.append({'id': tool, 'name': name, 'versions': [
            {'version': str(v['version']), 'active': bool(v.get('active'))}
            for v in sorted(entries, key=lambda entry: version_key(str(entry.get('version', '')))) if isinstance(v, dict) and VERSION.fullmatch(str(v.get('version', '')))]})
    return {'installed': installed, 'languages': rows}


def change(action, tool, version):
    if action not in ('install', 'use', 'remove') or tool not in dict(LANGUAGES) or not VERSION.fullmatch(version):
        raise ValueError('Choose a listed language and a version number, or latest.')
    if action == 'remove' and version == 'latest':
        raise ValueError('Choose the installed version to remove.')
    LOCK_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
    with (LOCK_DIR / 'languages.lock').open('a') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise OSError('Another language change is running. Wait for it to finish.') from None
        name = dict(LANGUAGES)[tool]
        target = tool + '@' + version
        if action == 'use':
            # Elixir needs Erlang, but choosing Elixir must never change another language's default,
            # including when the Elixir download fails. Erlang is managed through its own row.
            if tool == 'elixir':
                versions = json.loads(mise(['ls', '--installed', '--json']))
                if not any(v.get('active') for v in versions.get('erlang', [])):
                    raise ValueError('Install and use Erlang in its language row first, then choose Elixir.')
            try:
                mise(['use', '--global', '--pin', target])
            except OSError:
                raise OSError(f'{name} {version} couldn\'t be installed. Check the version number and your internet connection, then try again.') from None
            if version == 'latest':
                entries = json.loads(mise(['ls', '--installed', '--json'])).get(tool, [])
                version = next((str(v['version']) for v in entries if v.get('active')), version)
            return f'{name} {version} is your default. New terminals use it.'
        elif action == 'remove':
            entries = json.loads(mise(['ls', '--installed', '--json'])).get(tool, [])
            was_default = any(v.get('active') and v.get('version') == version for v in entries)
            remaining = [str(v['version']) for v in entries if v.get('version') != version and VERSION.fullmatch(str(v.get('version', '')))]
            # Remove only an exact default request, retaining all other versions and all project requests.
            mise(['unuse', '--global', '--no-prune', target])
            mise(['uninstall', target])
            message = f'{name} {version} was removed.'
            if was_default and remaining:
                newest = max(remaining, key=version_key)
                mise(['use', '--global', '--pin', tool + '@' + newest])
                message += f' {name} {newest} is your default. New terminals use it.'
            return message
        else:
            try:
                mise(['install', target])
            except OSError:
                raise OSError(f'{name} {version} couldn\'t be installed. Check the version number and your internet connection, then try again.') from None
            return f'{name} {version} was installed.'


def main(args):
    if args in (['--help'], ['-h'], ['help']):
        print(__doc__)
        return 0
    if args != ['status'] and (len(args) != 3 or args[0] not in ('install', 'use', 'remove')):
        print(__doc__, file=sys.stderr)
        return 2
    try:
        if args == ['status']:
            print(json.dumps(status()))
        else:
            message = change(*args)
            print(json.dumps({'ok': True, 'message': message}))
        return 0
    except (OSError, ValueError) as error:
        print(json.dumps({'ok': False, 'errors': str(error)}))
        print(str(error), file=sys.stderr)
        return 1


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
