#!/usr/bin/env python3

import json
import os
import signal
import subprocess
import sys
import time
import urllib.request

CONFIG = "/usr/local/etc/modelctl/models.json"
LLAMA = "/home/theroot/llama.cpp/build/bin/llama-server"
PID_FILE = "/tmp/modelctl.pid"


def load_config():
    with open(CONFIG, "r", encoding="utf-8") as f:
        return json.load(f)


def get_models():
    return load_config()["models"]


def get_pid():
    try:
        with open(PID_FILE, "r", encoding="utf-8") as f:
            return int(f.read().strip())
    except (FileNotFoundError, ValueError):
        return None


def write_pid(pid):
    with open(PID_FILE, "w", encoding="utf-8") as f:
        f.write(str(pid))


def clear_pid():
    try:
        os.unlink(PID_FILE)
    except FileNotFoundError:
        pass


def process_alive(pid):
    try:
        os.kill(pid, 0)
        return True
    except OSError:
        return False


def stop_server():
    pid = get_pid()

    if not pid or not process_alive(pid):
        clear_pid()
        return

    print(f"Останавливаю llama-server PID {pid}...")

    try:
        os.kill(pid, signal.SIGTERM)
    except ProcessLookupError:
        clear_pid()
        return

    for _ in range(30):
        if not process_alive(pid):
            clear_pid()
            return
        time.sleep(1)

    if process_alive(pid):
        print("Не остановился, SIGKILL...")
        try:
            os.kill(pid, signal.SIGKILL)
        except ProcessLookupError:
            pass

    clear_pid()


def get_loaded_model(port):
    try:
        with urllib.request.urlopen(
            f"http://127.0.0.1:{port}/v1/models",
            timeout=3,
        ) as response:
            data = json.loads(response.read())

        items = data.get("data", [])

        if items:
            return items[0].get("id")

    except Exception:
        pass

    return None


def wait_ready(port, expected):
    print(f"Жду {expected} на порту {port}...")

    for _ in range(300):
        if get_loaded_model(port) == expected:
            print(f"READY: port {port}")
            return True

        time.sleep(1)

    print("ERROR: модель не поднялась")
    return False


def find_model(profile):
    for name, info in get_models().items():
        if info.get("profile") == profile:
            return name, info

    return None, None


def start_model(profile):
    name, info = find_model(profile)

    if info is None:
        print(f"Неизвестный профиль: {profile}")
        return 1

    command = [LLAMA] + info["args"]

    print(f"Запускаю {name}...")
    print(" ".join(command))

    log_dir = "/var/log/modelctl"
    os.makedirs(log_dir, exist_ok=True)

    log_path = os.path.join(
        log_dir,
        f"{name}.log",
    )

    log_file = open(
        log_path,
        "a",
        encoding="utf-8",
        buffering=1,
    )

    process = subprocess.Popen(
        command,
        stdout=log_file,
        stderr=subprocess.STDOUT,
        start_new_session=True,
    )

    write_pid(process.pid)

    if not wait_ready(info["port"], name):
        try:
            process.terminate()
        except ProcessLookupError:
            pass

        clear_pid()
        return 1

    return 0


def command_list(json_output=False):
    config = load_config()

    if json_output:
        print(
            json.dumps(
                config,
                ensure_ascii=False,
                indent=2,
            )
        )
        return

    for name, info in config["models"].items():
        print(
            f"{name} | "
            f"profile={info['profile']} | "
            f"port={info['port']} | "
            f"context={info['context']}"
        )


def status():
    pid = get_pid()

    if not pid or not process_alive(pid):
        clear_pid()
        print("llama-server: STOPPED")
        return 0

    print(f"llama-server: RUNNING (PID {pid})")

    for name, info in get_models().items():
        loaded = get_loaded_model(info["port"])

        if loaded:
            print(f"model: {loaded}")
            print(f"port: {info['port']}")
            break

    return 0


def main():
    if len(sys.argv) < 2:
        print("Использование:")
        print("  modelctl status")
        print("  modelctl stop")
        print("  modelctl list")
        print("  modelctl list --json")
        print("  modelctl load <profile>")
        return 1

    command = sys.argv[1]

    if command == "status":
        return status()

    if command == "stop":
        stop_server()
        print("llama-server: STOPPED")
        return 0

    if command == "list":
        command_list(
            len(sys.argv) > 2 and sys.argv[2] == "--json"
        )
        return 0

    if command == "load":
        if len(sys.argv) != 3:
            print("Использование: modelctl load <profile>")
            return 1

        profile = sys.argv[2]

        if find_model(profile)[1] is None:
            print(f"Неизвестный профиль: {profile}")
            return 1

        stop_server()
        return start_model(profile)

    print(f"Неизвестная команда: {command}")
    return 1


if __name__ == "__main__":
    sys.exit(main())
