#   Copyright (C) 2025 Stephen Fairchild (s-fairchild@users.sourceforge.net)
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program in the file entitled COPYING.
#   If not, see <http://www.gnu.org/licenses/>.


import re
import os
import ctypes
import logging
import time
import tempfile
import shlex
import secrets
from functools import wraps
from datetime import datetime
from subprocess import Popen
from binascii import unhexlify

from idjc import FGlobs
from idjc.streamspec import FormatControl


__all__ = ["append", "prepend", "mk_ping", "Backend", "IcecastServer",
           "Encoder", "Source", "RandomNoise"]


logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger("testing")


def append(extra_text):
    assert extra_text.endswith("\n")
    def inner(func):
        @wraps(func)
        def send(message):
            func(f"{message}{extra_text}")
        return send
    return inner


def prepend(extra_text):
    assert extra_text.endswith("\n")
    def inner(func):
        @wraps(func)
        def send(message):
            func(f"{extra_text}{message}")
        return send
    return inner


def mk_ping(send, receive):
    start_time = datetime.now()
    def ping():
        try:
            send("ACTN=ping\n")
        except BrokenPipeError:
            logger.error("ping failed\n")
            raise
        else:
            reply = receive()
            if reply != "pong":
                logger.critical(f"ping failed: {reply=}\n")
                exit(5)
            logger.info(f"{datetime.now() - start_time} PING")
    return ping


class Backend:
    def __init__(self, streams, tmpdirname):
        self._streams = streams
        self._closer = None
        self._tmpdirname = tmpdirname

    def __enter__(self):
        os.environ["num_encoders"] = str(self._streams)
        os.environ["num_streamers"] = str(self._streams)
        os.environ["app_name"] = "idjc testing mode"
        os.environ["client_id"] = secrets.token_hex(16)
        os.environ["ui2be"] = os.path.join(self._tmpdirname, "ui2be")
        os.environ["be2ui"] = os.path.join(self._tmpdirname, "be2ui")

        backend = ctypes.CDLL(FGlobs.backend)

        int_r = ctypes.c_int()
        int_w = ctypes.c_int()
        if not backend.init_backend(ctypes.byref(int_r), ctypes.byref(int_w)):
            logger.critical("call to init_backend failed")
            exit(5)

        logger.debug(f"file descriptors for read/write are {int_r.value}, {int_w.value}")

        try:
            reader = os.fdopen(int_r.value, "r")
            writer = os.fdopen(int_w.value, "w")
        except OSError:
            logger.critical("failed to create streams for back-end i/o")
            exit(5)

        logger.info("awaiting reply")

        try:
            line = reader.readline()
        except IOError as e:
            logger.critical(e)
            exit(5)

        if line != "idjc back-end ready\n":
            logger.critical(f"bad reply from back-end: {line}")
            exit(5)

        logger.debug(f"back-end replied correctly with: {line}")

        @append("end\n")
        def send(message):
            assert re.fullmatch(r"^(mx\n|sc\n)(([^=\n]+?=[^\n]*\n)*?)+(end\n)$",
                                message)
            logger.debug(message.rstrip().replace("\n", "|"))
            writer.write(message)
            writer.flush()

        def closer():
            try:
                reader.close()
                writer.close()
            except BrokenPipeError:
                pass

        self._closer = closer

        return prepend("mx\n")(send), prepend("sc\n")(send), \
               lambda: reader.readline().rstrip()

    def __exit__(self, *_):
        if self._closer is not None:
            self._closer()


class IcecastServer():
    def __init__(self, port):
        self._proc = None
        self._port = port
        self._config_xml = b"""
                <icecast>
                    <limits>
                        <sources>2</sources>
                    </limits>
                    <authentication>
                        <source-password>changeme</source-password>
                        <relay-password>changeme</relay-password>
                        <admin-user>admin</admin-user>
                        <admin-password>changeme</admin-password>
                    </authentication>
                    <directory>
                        <yp-url-timeout>15</yp-url-timeout>
                        <yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
                    </directory>
                    <hostname>localhost</hostname>
                    <listen-socket>
                        <port>%d</port>
                    </listen-socket>
                    <fileserve>1</fileserve>
                    <paths>
                        <logdir>/tmp</logdir>
                        <webroot>/usr/share/icecast/web</webroot>
                        <adminroot>/usr/share/icecast/admin</adminroot>
                        <alias source="/" destination="/status.xsl"/>
                    </paths>
                    <logging>
                        <accesslog>access.log</accesslog>
                        <errorlog>error.log</errorlog>
                        <loglevel>1</loglevel>
                    </logging>
                    <http-headers>
                        <header name="Access-Control-Allow-Origin" value="*" />
                    </http-headers>
                </icecast>""" % port

    def __enter__(self):
        with tempfile.NamedTemporaryFile(delete=False) as cfg:
            cfg.write(self._config_xml)

        logger.info(f"start local icecast server on port {self._port}")

        def ic_launch(filename):
            try:
                return Popen(shlex.split(f"{filename} -c {cfg.name}"))
            except Exception:
                return None

        # Account for icecast2 executable name variations across distros.
        proc = ic_launch("icecast2") or ic_launch("icecast")
        if proc is None:
            logger.critical("icecast launch failed")
            exit(5)

        logger.debug(f"icecast process has pid of {proc.pid}")
        time.sleep(3)  # Give icecast some time to initialise.

        if proc.poll() is not None:
            logger.critical(f"icecast exited with code {proc.poll()}")
            exit(5)
        logger.debug("icecast is running")
        self._proc = proc

    def __exit__(self, *_):
        self._proc.kill()
        logger.info("kill signal sent to icecast server")


class Encoder:
    def __init__(self, send, receive, random, streams):
        self._tabs = [FormatControl(prepend(f"tab_id={i}\n")(send), receive)
                      for i in range(streams)]
        self._random = random

    def __enter__(self):
        for tab in self._tabs:
            if self._random:
                tab.select_random()
            else:
                tab.select_default()
            tab.start_encoder_rc()
        logger.info("start command issued to encoders")

    def __exit__(self, *_):
        for tab in self._tabs:
            tab.stop_encoder_rc()
            tab._clear_selection()
        logger.info("stop command issued to encoders")


class Source:
    def __init__(self, send, receive, port, streams):
        self._send = send
        self._receive = receive

        def params(i):
            return "\n".join((
                    f"stream_source={i}",
                    "server_type=Icecast 2",
                    "host=127.0.0.1",
                    f"{port=}",
                    f"mount=/listen{i}",
                    "login=source",
                    "password=changeme",
                    "useragent=",
                    "dj_name=IMTesting",
                    "listen_url=www.example.com",
                    "description=Test Stream",
                    "genre=Silence or test noise",
                    "irc=",
                    "aim=",
                    "icq=",
                    "tls=Disabled",
                    "ca_directory=",
                    "ca_file=",
                    "client_cert=",
                    "make_public=False",
                    "command=server_connect\n"))

        self._param_list = [params(i) for i in range(streams)]

    def __enter__(self):
        for i, each in enumerate(self._param_list):
            self._send(each)
            reply = self._receive()
            if reply.endswith("failed"):
                logger.error(f"server connection failure on tab {i}")
            elif reply.endswith("succeeded"):
                logger.info(f"connection made on tab {i}")
            else:
                logger.warn(f"unexpected reply: {reply=}")

    def __exit__(self, *_):
        for i in range(len(self._param_list)):
            self._send(f"stream_source={i}\ncommand=server_disconnect\n")
            self._receive()


class RandomNoise:
    def __init__(self, send, receive):
        self._send = send
        self._receive = receive

    def __enter__(self):
        self._send("command=random_noise_on\n")
        self._receive()

    def __exit__(self, *_):
        self._send("command=random_noise_off\n")
        self._receive()


def mk_jack_ports_list(send, receive):
    def jack_ports_list(filter_=""):
        send(f"ACTN=jackportread\nJFIL={filter_}\nJPRT=\n")
        reply = receive()

        if not reply.startswith("jackports="):
            raise ValueError(f"reply does not start with jackports= \"{reply}\"")

        return [str(unhexlify(x.lstrip("@-")), "ascii") for x in reply[10:].split()]
    return jack_ports_list


