"""Saved MUD destinations and engine-thread connection requests."""
from pathlib import Path
import json
import os
import re
import shutil
import tempfile
import uuid
from lyntin import event, exported

ROOT = Path(__file__).resolve().parents[1]
CONNECTIONS_FILE = ROOT / 'config' / 'muds.json'
# MultiMonde in telnet over TLS (stunnel on the server, certificate for this host).
MULTIMONDE_HOST, MULTIMONDE_PORT, MULTIMONDE_TLS_PORT = 'houseparadise.freeboxos.fr', 2500, 2501
DEFAULT_MUD = {'id': 'multimonde', 'name': 'MultiMonde',
               'host': MULTIMONDE_HOST, 'port': MULTIMONDE_TLS_PORT, 'autoconnect': True, 'tls': True}
# Done once per installation, recorded in muds.json: a player who unticks
# the box afterwards keeps plain telnet.
TLS_MIGRATION = 'multimonde_tls'


def validate_profile(profile):
    if not isinstance(profile, dict):
        raise ValueError('Définition de MUD invalide.')
    identifier = profile.get('id', uuid.uuid4().hex)
    if not isinstance(identifier, str) or not re.fullmatch(r'[a-zA-Z0-9_-]{1,64}', identifier):
        raise ValueError('Identifiant de connexion invalide.')
    name = profile.get('name', '')
    if not isinstance(name, str):
        raise ValueError('Nom du MUD invalide.')
    name = name.strip()
    if not name or len(name) > 80 or any(ord(c) < 32 for c in name):
        raise ValueError('Indiquez un nom de MUD de 1 à 80 caractères.')
    host = profile.get('host', '')
    if not isinstance(host, str):
        raise ValueError('Adresse de connexion invalide.')
    try:
        host = host.strip().encode('idna').decode('ascii').lower()
    except UnicodeError:
        raise ValueError('Adresse de connexion invalide.') from None
    if len(host) > 253 or not host or any(not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', label)
                                          for label in host.rstrip('.').split('.')):
        raise ValueError('Indiquez un nom de domaine ou une adresse IPv4, sans protocole ni port.')
    port = profile.get('port')
    if isinstance(port, str) and port.strip().isdigit():
        port = int(port.strip())
    if type(port) is not int or not 1 <= port <= 65535:
        raise ValueError('Le port doit être un entier de 1 à 65535.')
    automatic = profile.get('autoconnect', False)
    if type(automatic) is not bool:
        raise ValueError('Le choix de connexion automatique est invalide.')
    tls = profile.get('tls', False)
    if type(tls) is not bool:
        raise ValueError('Le choix de connexion chiffrée est invalide.')
    return {'id': identifier, 'name': name, 'host': host, 'port': port, 'autoconnect': automatic, 'tls': tls}


class MudRegistry:
    def __init__(self, path=None, load=True):
        self.path = Path(path) if path is not None else CONNECTIONS_FILE
        self._profiles = []
        self._migrations = []
        if load:
            self.reload()

    @staticmethod
    def _validated(profiles):
        if not isinstance(profiles, list) or len(profiles) > 100:
            raise ValueError('La liste doit contenir au maximum 100 MUDs.')
        if any(not isinstance(row, dict) or 'id' not in row for row in profiles):
            raise ValueError('Une connexion enregistrée n’a pas d’identifiant.')
        result = [validate_profile(row) for row in profiles]
        if len({row['id'] for row in result}) != len(result):
            raise ValueError('Plusieurs connexions ont le même identifiant.')
        if len({row['name'].casefold() for row in result}) != len(result):
            raise ValueError('Ce nom est déjà utilisé par un autre MUD.')
        return result

    def reload(self):
        try:
            data = json.loads(self.path.read_text(encoding='utf-8'))
        except FileNotFoundError:
            self._profiles = [dict(DEFAULT_MUD)]
            self._migrations = [TLS_MIGRATION]
            return
        except (ValueError, UnicodeError) as exc:
            raise ValueError('Le fichier des connexions est illisible : %s' % self.path) from exc
        if not isinstance(data, dict) or type(data.get('version')) is not int or data.get('version') != 1:
            raise ValueError('Format du fichier des connexions inconnu.')
        self._profiles = self._validated(data.get('muds'))
        migrations = data.get('migrations', [])
        self._migrations = [m for m in migrations if isinstance(m, str)] if isinstance(migrations, list) else []

    def migrate_multimonde_tls(self):
        """Switch an untouched plain MultiMonde entry to TLS, once per installation.

        Returns the number of entries changed. A player who unticks the box
        later keeps plain telnet: the migration is recorded and never redone."""
        if TLS_MIGRATION in self._migrations:
            return 0
        rows, changed = self.all(), 0
        for row in rows:
            if (row['host'].rstrip('.') == MULTIMONDE_HOST and row['port'] == MULTIMONDE_PORT
                    and not row['tls']):
                row.update(port=MULTIMONDE_TLS_PORT, tls=True)
                changed += 1
        self._migrations.append(TLS_MIGRATION)
        self.save(rows)
        return changed

    def all(self):
        return [dict(row) for row in self._profiles]

    def save(self, profiles):
        validated = self._validated(profiles)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        temporary = None
        try:
            fd, temporary = tempfile.mkstemp(prefix='.muds-', dir=self.path.parent)
            with os.fdopen(fd, 'w', encoding='utf-8') as output:
                data = {'version': 1, 'muds': validated}
                if self._migrations:
                    data['migrations'] = sorted(set(self._migrations))
                json.dump(data, output, ensure_ascii=False, indent=2)
                output.write('\n')
                output.flush()
                os.fsync(output.fileno())
            if self.path.is_file():
                shutil.copy2(self.path, self.path.with_suffix('.json.bak'))
            os.replace(temporary, self.path)
            self._profiles = validated
        finally:
            if temporary is not None:
                Path(temporary).unlink(missing_ok=True)

    def upsert(self, profile):
        profile = validate_profile(profile)
        rows = self.all()
        for index, row in enumerate(rows):
            if row['id'] == profile['id']:
                rows[index] = profile
                break
        else:
            rows.append(profile)
        self.save(rows)
        return dict(profile)

    def remove(self, identifier):
        self.save([row for row in self.all() if row['id'] != identifier])


class ConnectMudEvent(event.Event):
    def __init__(self, profile, new_session=True, minimum_number=1):
        self.profile = validate_profile(profile)
        self.new_session = new_session
        if type(minimum_number) is not int or minimum_number < 1:
            raise ValueError("Numéro de session invalide.")
        self.minimum_number = minimum_number

    def execute(self):
        from lyntin.modules.tintincmds import session_cmd
        engine = exported.myengine
        profile = self.profile
        base = re.sub(r'[^\w-]+', '_', profile['name'], flags=re.UNICODE).strip('_') or 'MUD'
        first_name = base + '_S1'
        first = engine.getSession(first_name)
        if (not self.new_session and first is not None
                and getattr(first, '_mud_profile_id', None) == profile['id']
                and first.isConnected()
                and (first._host, first._port, bool(getattr(first, '_tls', False)))
                == (profile['host'], profile['port'], profile['tls'])):
            engine.changeSession(first_name)
            return
        number = self.minimum_number
        while engine.getSession(base + '_S' + str(number)) is not None:
            number += 1
        name = base + '_S' + str(number)
        session_cmd(engine.getSession('common'), {'sessionname': name, 'host': profile['host'],
                    'port': profile['port'], 'filename': '', 'tls': profile['tls']}, '')
        created = engine.getSession(name)
        if (profile['tls'] and profile['host'].rstrip('.') == MULTIMONDE_HOST
                and profile['port'] == MULTIMONDE_TLS_PORT
                and (created is None or not created.isConnected())):
            # Encrypted port unreachable (blocked network, server not ready):
            # do not leave the player outside the game.
            exported.write_error('Connexion chiffrée à MultiMonde impossible : connexion en clair '
                                 'sur le port %d.' % MULTIMONDE_PORT)
            session_cmd(engine.getSession('common'), {'sessionname': name, 'host': profile['host'],
                        'port': MULTIMONDE_PORT, 'filename': '', 'tls': False}, '')
            created = engine.getSession(name)
        if created is not None:
            created._mud_profile_id = profile['id']
            created._mud_profile = dict(profile)



def queue_connection(profile, new_session=True, minimum_number=1):
    ConnectMudEvent(profile, new_session, minimum_number).enqueue()



def queue_current_mud(session):
    """Duplicate the current session's actual destination, even after profile edits."""
    if session is None or session.getName() == 'common':
        return False
    host, port = getattr(session, '_host', None), getattr(session, '_port', None)
    if not host or port is None:
        return False
    name = session.getName()
    suffix = re.fullmatch(r'(.+)_S([0-9]+)', name)
    base = suffix.group(1) if suffix else name
    number = int(suffix.group(2)) + 1 if suffix else 1
    saved = getattr(session, '_mud_profile', None)
    profile = dict(saved) if isinstance(saved, dict) else {}
    identifier = getattr(session, '_mud_profile_id', None)
    if isinstance(identifier, str):
        profile['id'] = identifier
    profile.update(name=base, host=host, port=port, autoconnect=False,
                   tls=bool(getattr(session, '_tls', False)))
    queue_connection(validate_profile(profile), new_session=True, minimum_number=number)
    return True


def autoconnect():
    try:
        registry = MudRegistry()
    except (OSError, ValueError) as exc:
        exported.write_error('Connexions automatiques non chargées : %s' % exc)
        return
    try:
        if registry.migrate_multimonde_tls():
            exported.write_message('MultiMonde passe en connexion chiffrée (TLS, port %d). Pour revenir '
                                   'au telnet simple, décochez « Connexion chiffrée » dans la fiche du MUD.'
                                   % MULTIMONDE_TLS_PORT)
    except (OSError, ValueError) as exc:
        exported.write_error('Passage de MultiMonde en connexion chiffrée non enregistré : %s' % exc)
    rows = registry.all()
    for row in rows:
        if row['autoconnect']:
            queue_connection(row, new_session=False)
