"""Runtime paths for pip-installed ACP stack."""

from __future__ import annotations

import importlib.metadata
import os
import shutil
import subprocess
from pathlib import Path

from importlib.resources import as_file, files


def package_version() -> str:
    try:
        return importlib.metadata.version("acp-ai")
    except importlib.metadata.PackageNotFoundError:
        return "0.0.0.dev"


def acp_home() -> Path:
    return Path(os.environ.get("ACP_HOME", Path.home() / ".acp"))


def jwt_dir() -> Path:
    return acp_home() / "jwt"


def runtime_dir() -> Path:
    """Materialized compose bundle (writable copy outside site-packages)."""
    dest = acp_home() / "runtime" / package_version()
    dest.mkdir(parents=True, exist_ok=True)
    marker = dest / ".bundle_ok"
    if marker.exists():
        return dest
    bundle = files("acp").joinpath("bundle")
    with as_file(bundle) as src:
        src_path = Path(src)
        if not src_path.is_dir():
            raise RuntimeError("ACP bundle missing; reinstall acp-ai")
        for item in src_path.iterdir():
            target = dest / item.name
            if target.exists():
                if target.is_dir():
                    shutil.rmtree(target)
                else:
                    target.unlink()
            if item.is_dir():
                shutil.copytree(item, target)
            else:
                shutil.copy2(item, target)
    marker.touch()
    return dest


def ensure_jwt_keys() -> Path:
    """Create RS256 dev keypair under ~/.acp/jwt if missing."""
    d = jwt_dir()
    d.mkdir(parents=True, exist_ok=True)
    priv = d / "private.pem"
    pub = d / "public.pem"
    if priv.exists() and pub.exists():
        return d
    if not shutil.which("openssl"):
        raise RuntimeError("openssl not found; install OpenSSL to generate dev JWT keys")
    subprocess.run(
        ["openssl", "genrsa", "-out", str(priv), "2048"],
        check=True,
        capture_output=True,
    )
    subprocess.run(
        ["openssl", "rsa", "-in", str(priv), "-pubout", "-out", str(pub)],
        check=True,
        capture_output=True,
    )
    try:
        priv.chmod(0o600)
    except OSError:
        pass
    return d


def compose_env() -> dict[str, str]:
    from acp.policies import ensure_policies_ready

    env = os.environ.copy()
    env["ACP_JWT_DIR"] = str(ensure_jwt_keys())
    env["ACP_POLICIES_DIR"] = str(ensure_policies_ready())
    return env


def compose_file() -> Path:
    return runtime_dir() / "docker-compose.yml"
