"""Managed MUD music cache; background downloads, never executes server text."""
from pathlib import Path, PurePosixPath
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit, unquote
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.error import HTTPError
import hashlib
import json
import logging
import os
import tempfile
import threading
import time

SOURCE = 'https://jeuxvideopouraveugles.fr/partage/musics/'
CACHE = Path(__file__).resolve().parents[1] / 'music' / 'multimonde'
AUDIO = {'.mp3', '.ogg', '.wav', '.flac'}
MAX_FILE = 100 * 1024 * 1024
MAX_INDEX = 1024 * 1024
MAX_FILES = 512
MAX_TOTAL = 1024 * 1024 * 1024

class Cancelled(Exception):
    pass

class Links(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links = []
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            value = dict(attrs).get('href')
            if value:
                self.links.append(value)

class RestrictedRedirect(HTTPRedirectHandler):
    def __init__(self, validate):
        super().__init__()
        self.validate = validate
    def redirect_request(self, req, fp, code, msg, headers, url):
        self.validate(url)
        return super().redirect_request(req, fp, code, msg, headers, url)

class MusicLibrarySync:
    def __init__(self, root=CACHE, allowed_source=SOURCE):
        self.root = Path(root)
        self.source = allowed_source.rstrip('/') + '/'
        self._lock = threading.RLock()
        self._thread = None
        self._restart = False
        self._cancel = threading.Event()
        self._status = {'state': 'inactive', 'downloaded': 0, 'unchanged': 0, 'removed': 0}

    def track_for_room(self, zone, room, override=None, building=None):
        """Choose room, explicit room mapping, building, then zone music."""
        zone, room = zone.casefold(), room.casefold()
        building = building.casefold() if building else None
        if not self.root.is_dir() or self.root.is_symlink():
            return None
        matches = []
        if override is not None:
            try:
                if self._path(override).is_file():
                    matches.append((1, 0, override))
            except (ValueError, OSError):
                pass
        for path in self.root.iterdir():
            if path.suffix.lower() not in AUDIO or not path.is_file():
                continue
            try:
                self._path(path.name)
            except ValueError:
                continue
            stem = path.stem.casefold()
            if stem == zone:
                matches.append((3, 0, path.name))
                continue
            # Match complete identifiers before the optional memo suffix.
            # Double separators also support identifiers containing underscores.
            for priority, target in ((0, room), (2, building)):
                if not target:
                    continue
                for style, separator in enumerate(('__', '_')):
                    prefix = zone + separator + target
                    if stem == prefix or (priority == 0 and stem.startswith(prefix + separator)):
                        matches.append((priority, style, path.name))
        return min(matches, key=lambda x: (x[0], x[1], x[2].casefold(), x[2]))[2] if matches else None

    def status(self):
        with self._lock:
            return dict(self._status)

    def _update(self, **values):
        with self._lock:
            self._status.update(values)

    def start(self, source=SOURCE):
        if source.rstrip('/') + '/' != self.source:
            raise ValueError('Source musicale non autorisée.')
        with self._lock:
            if self._thread and self._thread.is_alive():
                if self._cancel.is_set():
                    self._restart = True
                return
            self._cancel = threading.Event()
            self._status = {'state': 'synchronisation', 'downloaded': 0, 'unchanged': 0, 'removed': 0}
            self._thread = threading.Thread(target=self._background, args=(self._cancel,),
                                            name='NTLyntinMusicSync', daemon=True)
            self._thread.start()

    def cancel(self):
        with self._lock:
            self._restart = False
            self._cancel.set()

    def shutdown(self):
        self.cancel()
        thread = self._thread
        if thread and thread is not threading.current_thread():
            thread.join(timeout=3)

    def _check(self, cancel, deadline):
        if cancel.is_set():
            raise Cancelled()
        if time.monotonic() > deadline:
            raise TimeoutError('Synchronisation musicale trop longue.')

    def _validate(self, url):
        base, value = urlsplit(self.source), urlsplit(url)
        if (value.scheme, value.netloc) != (base.scheme, base.netloc) or value.query or value.fragment:
            raise ValueError('Lien hors de la bibliothèque musicale.')
        path, prefix = unquote(value.path), unquote(base.path)
        if not path.startswith(prefix):
            raise ValueError('Lien hors du dossier musical.')
        relative = path[len(prefix):].rstrip('/')
        if relative:
            self._relative(relative)
        return relative

    @staticmethod
    def _relative(name):
        parts = name.split('/')
        reserved = {'CON', 'PRN', 'AUX', 'NUL', *(f'COM{i}' for i in range(10)), *(f'LPT{i}' for i in range(10))}
        if not name or any(not x or x in ('.', '..') or x.startswith('.') or x.endswith((' ', '.'))
                           or any(c in x for c in '\\:<>"|?*') or any(ord(c) < 32 for c in x)
                           or x.split('.')[0].upper() in reserved for x in parts):
            raise ValueError('Nom musical non valide.')
        return PurePosixPath(name)

    def _path(self, name):
        relative = self._relative(name)
        path = self.root.joinpath(*relative.parts)
        if not path.resolve().is_relative_to(self.root.resolve()) or self.root.is_symlink():
            raise ValueError('Chemin musical non valide.')
        return path

    def _catalog(self, opener, cancel, deadline):
        pending = [(self.source, 0)]
        visited, result = set(), {}
        while pending:
            url, depth = pending.pop()
            if url in visited:
                continue
            if depth > 8:
                raise ValueError('Trop de sous-dossiers musicaux.')
            visited.add(url)
            if len(visited) > MAX_FILES:
                raise ValueError('Bibliothèque musicale trop grande.')
            self._check(cancel, deadline)
            with opener.open(Request(url, headers={'User-Agent': 'NTLyntin64/1.0'}), timeout=2) as response:
                self._validate(response.url)
                body = response.read(MAX_INDEX + 1)
            if len(body) > MAX_INDEX:
                raise ValueError('Index musical trop grand.')
            parser = Links()
            parser.feed(body.decode('utf-8', errors='replace'))
            for link in parser.links:
                value = urljoin(url, link)
                try:
                    relative = self._validate(value)
                except ValueError:
                    continue
                if not relative:
                    continue
                if urlsplit(value).path.endswith('/'):
                    pending.append((value, depth + 1))
                elif PurePosixPath(relative).suffix.lower() in AUDIO:
                    result[relative] = value
                    if len(result) > MAX_FILES:
                        raise ValueError('Trop de fichiers musicaux.')
        if len({x.casefold() for x in result}) != len(result):
            raise ValueError('Noms musicaux ambigus sous Windows.')
        return result

    @staticmethod
    def _digest(path):
        with path.open('rb') as source:
            return hashlib.file_digest(source, 'sha256').hexdigest()

    def _save_json(self, path, data):
        fd, temporary = tempfile.mkstemp(prefix='.index-', dir=self.root)
        try:
            with os.fdopen(fd, 'w', encoding='utf-8') as output:
                json.dump(data, output, ensure_ascii=False, indent=2)
                output.flush()
                os.fsync(output.fileno())
            os.replace(temporary, path)
        finally:
            Path(temporary).unlink(missing_ok=True)

    def _background(self, cancel):
        try:
            self.synchronize(cancel)
        except Cancelled:
            self._update(state='annulée')
        except Exception as exc:
            logging.exception('Music library synchronization failed')
            self._update(state='erreur', error=str(exc))
        finally:
            with self._lock:
                restart = self._restart
                self._restart = False
                self._thread = None
                if restart:
                    self.start(self.source)

    def synchronize(self, cancel=None):
        cancel = cancel or threading.Event()
        deadline = time.monotonic() + 600
        self.root.mkdir(parents=True, exist_ok=True)
        if self.root.is_symlink():
            raise ValueError('Le dossier de cache ne doit pas être un lien.')
        index = self.root / '.index.json'
        try:
            previous = json.loads(index.read_text(encoding='utf-8'))
            if not isinstance(previous, dict) or previous.get('source') != self.source or not isinstance(previous.get('files'), dict):
                previous = {}
        except (FileNotFoundError, ValueError, TypeError):
            previous = {}
        old = previous.get('files', {})
        opener = build_opener(RestrictedRedirect(self._validate))
        catalog = self._catalog(opener, cancel, deadline)
        current, total = {}, 0
        stats = {'state': 'synchronisation', 'downloaded': 0, 'unchanged': 0, 'removed': 0}
        for name, url in sorted(catalog.items()):
            self._check(cancel, deadline)
            path = self._path(name)
            info = old.get(name, {})
            if not isinstance(info, dict):
                info = {}
            valid = path.is_file() and path.stat().st_size == info.get('size') and self._digest(path) == info.get('sha256')
            headers = {'User-Agent': 'NTLyntin64/1.0'}
            if valid:
                if info.get('etag'):
                    headers['If-None-Match'] = info['etag']
                elif info.get('modified'):
                    headers['If-Modified-Since'] = info['modified']
            try:
                response = opener.open(Request(url, headers=headers), timeout=2)
            except HTTPError as exc:
                if exc.code == 304 and valid:
                    exc.close()
                    current[name] = info
                    stats['unchanged'] += 1
                    self._update(**stats)
                    continue
                raise
            temporary = None
            try:
                with response:
                    self._validate(response.url)
                    if response.headers.get_content_type() == 'text/html':
                        raise ValueError('Une musique renvoie une page HTML.')
                    length = response.headers.get('Content-Length')
                    length = int(length) if length is not None else None
                    if length is not None and not 0 < length <= MAX_FILE:
                        raise ValueError('Taille musicale non valide.')
                    path.parent.mkdir(parents=True, exist_ok=True)
                    fd, temporary = tempfile.mkstemp(prefix='.download-', dir=path.parent)
                    size, digest = 0, hashlib.sha256()
                    with os.fdopen(fd, 'wb') as output:
                        while True:
                            self._check(cancel, deadline)
                            chunk = response.read(65536)
                            if not chunk:
                                break
                            size += len(chunk)
                            total += len(chunk)
                            if size > MAX_FILE or total > MAX_TOTAL:
                                raise ValueError('Limite de téléchargement musical dépassée.')
                            output.write(chunk)
                            digest.update(chunk)
                        output.flush()
                        os.fsync(output.fileno())
                    self._check(cancel, deadline)
                    if size == 0 or length is not None and size != length:
                        raise ValueError('Téléchargement musical incomplet.')
                    info = {'size': size, 'sha256': digest.hexdigest(), 'etag': response.headers.get('ETag'),
                            'modified': response.headers.get('Last-Modified')}
                    os.replace(temporary, path)
                    temporary = None
                    current[name] = info
                    stats['downloaded'] += 1
                    self._update(**stats)
            finally:
                if temporary:
                    Path(temporary).unlink(missing_ok=True)
        self._check(cancel, deadline)
        for name, info in old.items():
            if name not in catalog and isinstance(info, dict):
                path = self._path(name)
                if path.is_file() and self._digest(path) == info.get('sha256'):
                    path.unlink()
                    stats['removed'] += 1
        self._save_json(index, {'source': self.source, 'files': current})
        stats['state'] = 'à jour'
        self._update(**stats)
        return stats
