from __future__ import annotations

import shlex
from pathlib import Path

from konstant import cli
from konstant.config import ServiceConfig
from konstant.darwin import service as darwin_service
from konstant.linux import service as linux_service
import konstant.service as service_dispatch


def _service(tmp_path: Path, name: str = "demo") -> ServiceConfig:
    cwd = tmp_path / "app space"
    cwd.mkdir(parents=True, exist_ok=True)
    return ServiceConfig(name=name, script="worker.py", cwd=str(cwd))


def test_linux_unit_execstart_uses_konstant_manager(tmp_path: Path) -> None:
    svc = _service(tmp_path)
    cfg_path = tmp_path / "cfg dir" / "konstant.toml"
    cfg_path.parent.mkdir(parents=True, exist_ok=True)
    cfg_path.write_text("", encoding="utf-8")

    unit = linux_service._build_unit(svc, cfg_path)
    exec_line = next(line for line in unit.splitlines() if line.startswith("ExecStart="))

    assert " -m konstant.cli start demo --fg --config " in exec_line
    assert shlex.quote(str(cfg_path.resolve())) in exec_line


def test_darwin_plist_program_args_use_konstant_manager(tmp_path: Path) -> None:
    svc = _service(tmp_path)
    cfg_path = tmp_path / "cfg.toml"
    cfg_path.write_text("", encoding="utf-8")

    plist = darwin_service._build_plist(svc, cfg_path)
    args = plist["ProgramArguments"]

    assert args[1:7] == ["-m", "konstant.cli", "start", "demo", "--fg", "--config"]
    assert args[7] == str(cfg_path.resolve())


def test_darwin_install_creates_logs_dir(tmp_path: Path, monkeypatch) -> None:
    svc = _service(tmp_path)
    agents_dir = tmp_path / "Library" / "LaunchAgents"
    monkeypatch.setattr(darwin_service, "_AGENTS_DIR", agents_dir)

    def _fake_run(*args, **kwargs):
        return None

    monkeypatch.setattr(darwin_service.subprocess, "run", _fake_run)
    darwin_service.install_service(svc)

    assert (svc.resolved_cwd / "logs").exists()
    assert (agents_dir / f"{darwin_service._label('demo')}.plist").exists()


def test_cli_install_passes_config_path(tmp_path: Path, monkeypatch) -> None:
    cfg_path = tmp_path / "konstant.toml"
    cfg_path.write_text('[services.demo]\nscript = "worker.py"\n', encoding="utf-8")

    calls: list[Path | None] = []

    def _fake_install_service(config, user=None, password=None, config_path=None):
        calls.append(config_path)

    monkeypatch.setattr(service_dispatch, "install_service", _fake_install_service)
    monkeypatch.setattr(service_dispatch, "_platform_label", lambda: "test platform")
    monkeypatch.setattr(cli.console, "print", lambda *args, **kwargs: None)

    cli.install(name="demo", config=cfg_path)
    assert calls == [cfg_path]
