import http.client
import os
import re
from .backend import ensure_vis_server, is_vis_running, render_png, render_png_bytes, send_phg


def _vis_exe_path() -> str:
    current_directory = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(current_directory, "vis", "vis.exe")


def HTTPPOST(ip, phg):
    if ip not in ("127.0.0.1", "localhost"):
        raise ValueError("Only local VIS server is supported.")
    headers = {
        "Connection": "keep-alive",
        "Content-Type": "text/plain",
    }
    conn = http.client.HTTPConnection(f"{ip}:5088")
    conn.request("POST", "/phg", phg, headers)
    conn.getresponse()
    conn.close()


def vis(phg):
    send_phg(phg)


def HTTPPOST_IMG(ip, phg, filename="shot.png"):
    if ip not in ("127.0.0.1", "localhost"):
        raise ValueError("Only local VIS server is supported.")
    headers = {
        "Connection": "keep-alive",
        "Content-Type": "text/plain",
    }
    text = phg.decode("utf-8") if isinstance(phg, bytes) else str(phg)
    if "|||" not in text:
        request_body = f"{text}|||file={filename}"
    else:
        code, params = text.split("|||", 1)
        params = params.strip()
        if "file=" in params:
            params = re.sub(r"file=\\S+", f"file={filename}", params)
        else:
            params = f"{params} file={filename}".strip()
        request_body = f"{code}|||{params}"
    conn = http.client.HTTPConnection(f"{ip}:5088")
    conn.request("POST", "/phg_img", request_body, headers)
    conn.getresponse()
    conn.close()


def image(
    phg,
    filename="shot.png",
    width=800,
    height=600,
    view=3,
    timeout=30.0,
    **camera_kwargs,
):
    return render_png(
        phg,
        filename=filename,
        width=width,
        height=height,
        view=view,
        timeout=timeout,
        **camera_kwargs,
    )


__all__ = [
    "is_vis_running",
    "render_png",
    "render_png_bytes",
    "HTTPPOST",
    "HTTPPOST_IMG",
    "vis",
    "image",
]
