"""Instala la orden aon para el usuario actual con Python 3 y OpenSSH."""
import argparse
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile

DEFAULT_HOST = "anastasiia.l@Anastasiias-MacBook-Pro.local"

def private_host():
    cli = shutil.which("tailscale") or "/Applications/Tailscale.app/Contents/MacOS/Tailscale"
    if not Path(cli).is_file():
        return DEFAULT_HOST
    try:
        result = subprocess.run([cli, "status", "--json"], capture_output=True, timeout=4, check=True)
        status = json.loads(result.stdout)
    except (OSError, ValueError, subprocess.SubprocessError):
        return DEFAULT_HOST
    user, hostname = DEFAULT_HOST.split("@")
    slug = lambda name: "".join(c for c in name.lower() if c.isascii() and c.isalnum())
    target = slug(hostname.split(".")[0])
    names = {p["DNSName"].rstrip(".") for p in (status.get("Peer") or {}).values()
             if p.get("DNSName") and target in (slug(p.get("HostName","")), slug(p["DNSName"].split(".")[0]))}
    if status.get("BackendState") == "Running" and len(names) == 1:
        return user + "@" + names.pop()
    return DEFAULT_HOST

def write(path, content, mode):
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle:
        handle.write(content)
        os.fchmod(handle.fileno(), mode)
    os.replace(handle.name, path)

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--servidor", action="store_true", help="usar Ollama en este Mac")
    parser.add_argument("--host", help="destino o alias SSH del Mac")
    args = parser.parse_args()
    args.host = args.host or (DEFAULT_HOST if args.servidor else private_host())
    if not args.host or args.host.startswith("-") or any(c.isspace() for c in args.host):
        parser.error("Indica un destino SSH válido.")
    user = Path.home()
    source = Path(__file__).resolve().with_name("aon.py")
    if args.servidor:
        if not source.is_file():
            parser.error("Ejecuta la instalación desde aon-front en el Mac servidor.")
        options = "--local"
    else:
        copy = subprocess.check_output(["ssh", "--", args.host, "cat ~/aon-model/aon-front/aon.py"])
        compile(copy, "aon.py", "exec")
        source = user / ".local/share/aon/aon.py"
        write(source, copy, 0o600)
        options = "--host " + shlex.quote(args.host)
    executable = user / ".local/bin/aon"
    marker = "# AON terminal"
    if executable.exists() and marker not in executable.read_text(errors="replace")[:100]:
        parser.error("Ya existe otro programa en ~/.local/bin/aon.")
    script = "#!/bin/sh\n" + marker + "\nexec python3 " + shlex.quote(str(source)) + " " + options + ' "$@"\n'
    if args.servidor:
        admin = shlex.quote(str(source.parent.parent / "aon-backend" / "web" / "usuarios.py"))
        actions = 'if [ "${1:-}" = clave ]; then shift; exec python3 ' + admin + ' --copiar "$@"; fi\n'
        actions += 'if [ "${1:-}" = usuario ]; then shift; exec python3 ' + admin + ' "$@"; fi\n'
    else:
        actions = 'if [ "${1:-}" = ssh ]; then exec ssh -- ' + shlex.quote(args.host) + '; fi\n'
    script = script.replace(marker + "\n", marker + "\n" + actions, 1)
    write(executable, script.encode(), 0o755)
    shell = Path(os.environ.get("SHELL", "/bin/zsh")).name
    profiles = [user / ".zshenv"] if shell == "zsh" else [user / ".profile", user / ".bashrc"]
    for profile in profiles:
        old = profile.read_text() if profile.exists() else ""
        if marker not in old and str(executable.parent) not in os.environ.get("PATH", "").split(":"):
            with profile.open("a") as out:
                out.write('\n' + marker + '\nexport PATH="$HOME/.local/bin:$PATH"\n')
    print("Abre otra terminal, entra en tu proyecto y escribe aon.")

if __name__ == "__main__":
    main()
