#!/usr/bin/env python3
"""Install Clay from inside one extracted release archive."""

from pathlib import Path
import json
import os
import subprocess
import sys


def install_requirement(manifest: dict) -> str:
    """Select the Clay distribution extra represented by this archive."""
    flavor = manifest.get("flavor")
    if flavor == "core":
        return "clay"
    if flavor == "ui":
        return "clay[ui]"
    raise ValueError(f"unsupported release flavor: {flavor!r}")


def launcher_script(console_script: Path) -> str:
    """Build the launcher that runs one absolute console-script path.

    The launcher is normally reached through the ``~/.local/bin/clay`` symlink.
    A POSIX shell sets ``$0`` to the path the script was invoked as rather than
    to the file that path resolves to, so a directory derived from ``$0`` names
    the symlink's directory and not the release. The launcher therefore records
    the console script's absolute path, which is stable because release
    directories are version-named and are never moved after installation.
    """
    target = str(console_script)
    if not console_script.is_absolute():
        raise ValueError(f"launcher target must be absolute: {target}")
    if set('"\\$`\n') & set(target):
        raise ValueError(f"launcher target is not safely quotable: {target}")
    return f'#!/bin/sh\nexec "{target}" "$@"\n'


def main() -> int:
    root = Path(__file__).resolve().parent
    manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
    expected_version = str(manifest["version"])
    requirement = install_requirement(manifest)
    runtime = root / "python" / "bin" / "python3"
    venv = root / "venv"
    if not runtime.is_file():
        print(f"clay install: bundled Python is missing: {runtime}", file=sys.stderr)
        return 1
    subprocess.run([str(runtime), "-m", "venv", str(venv)], check=True)
    python = venv / "bin" / "python"
    subprocess.run([
        str(python), "-m", "pip", "install",
        "--no-index", "--find-links", str(root / "wheels"), requirement,
    ], check=True)
    clay = venv / "bin" / "clay"
    reported = subprocess.run(
        [str(clay), "--version"],
        check=True,
        text=True,
        stdout=subprocess.PIPE,
    ).stdout.strip()
    expected_output = f"clay {expected_version}"
    if reported != expected_output:
        print(
            f"clay install: expected {expected_output!r}, got {reported!r}",
            file=sys.stderr,
        )
        return 1
    launcher = root / "clay"
    launcher.write_text(launcher_script(clay), encoding="utf-8")
    os.chmod(launcher, 0o755)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
