"""Install the separate TasksAI agent connection using Python 3.11 or newer."""

import argparse
import hashlib
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import urllib.request
import venv

WHEEL_URL = "https://tasksai-agent-commerce-live-10437713249.us-central1.run.app/downloads/tasksai_agent_skills-0.3.0-py3-none-any.whl"
WHEEL_SHA256 = "e992a8f043840e8c5ea7199d31baffc69d44d9eaf5b6e9d2746e83035e8bff3d"
VERSION = "0.3.0"


def main():
    parser = argparse.ArgumentParser(description=__doc__, add_help=False)
    parser.add_argument("--install-dir", type=Path)
    args, connection_args = parser.parse_known_args()
    if sys.version_info < (3, 11):
        raise SystemExit("Install Python 3.11 or newer, then run this installer again.")
    if args.install_dir:
        root = args.install_dir.expanduser().absolute()
    elif os.name == "nt":
        root = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / "AppData/Local"))) / "TasksAI/AgentSkills"
    else:
        root = Path.home() / ".local/share/tasksai-agent-skills"
    root.mkdir(parents=True, exist_ok=True, mode=0o700)
    environment = root / VERSION
    if environment.is_symlink():
        raise SystemExit("Choose an installation directory owned by you, without a linked runtime directory.")
    python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
    print("Preparing the separate TasksAI agent connection", file=sys.stderr)
    if not python.is_file():
        venv.EnvBuilder(with_pip=True).create(environment)
    with tempfile.TemporaryDirectory(prefix="tasksai-agent-download-") as temporary:
        wheel = Path(temporary) / WHEEL_URL.rsplit("/", 1)[1]
        with urllib.request.urlopen(WHEEL_URL, timeout=60) as response:
            data = response.read(2_000_001)
        if len(data) > 2_000_000 or hashlib.sha256(data).hexdigest() != WHEEL_SHA256:
            raise SystemExit("The connector download failed its integrity check. Run the installer again after checking the download.")
        wheel.write_bytes(data)
        subprocess.run([str(python), "-m", "pip", "install", "--disable-pip-version-check", str(wheel)],
                       check=True, stdout=sys.stderr, stderr=sys.stderr)
    subprocess.run([str(python), "-m", "realtortasksai_connector", "--version"], check=True, stdout=sys.stderr)
    command = connection_args or ["setup"]
    result = subprocess.run([str(python), "-m", "realtortasksai_connector", *command])
    raise SystemExit(result.returncode)


if __name__ == "__main__":
    try:
        main()
    except (OSError, subprocess.CalledProcessError) as error:
        raise SystemExit(f"TasksAI installation needs attention. {error}")
