#!/usr/bin/env python3
from __future__ import annotations

import os
import shlex
import shutil
import subprocess
import sys

from dxcli_metadata import current_release_metadata
from dxcli_sessions import (
    INTERNAL_RUN_COMMAND,
    MANAGED_GLOBAL_ID_ENV,
    MANAGED_LAUNCH_MODE_ENV,
    LAUNCH_MODE_SHELL,
    SessionStore,
    dispatch_management_command,
    query_tmux_statuses,
)
from dxcli_terminal_filter import run_with_terminal_filter

PROGRAM_COMMAND_ALIASES = {
    "dxs": "s",
    "dxsa": "sa",
    "dxsd": "sd",
    "dxsda": "sda",
    "dxa": "a",
    "dxaa": "aa",
}


def apply_program_alias(argv: list[str]) -> list[str]:
    invoked_name = os.getenv("DXCLI_INVOKED_NAME") or os.path.basename(sys.argv[0])
    command = PROGRAM_COMMAND_ALIASES.get(invoked_name)
    if command is None:
        return argv
    return [command] + list(argv)


def resolve_codex_command(forwarded_args: list[str]) -> list[str]:
    override = os.getenv("DXCLI_CODEX_BIN")
    if override:
        prefix = shlex.split(override)
    else:
        binary = shutil.which("codex") or "/usr/bin/codex"
        prefix = [binary] if binary else []
    if not prefix or (not shutil.which(prefix[0]) and not os.path.exists(prefix[0])):
        raise FileNotFoundError("Could not find codex. Set DXCLI_CODEX_BIN if needed.")
    return prefix + forwarded_args


def main(argv: list[str] | None = None) -> int:
    raw_args = list(sys.argv[1:] if argv is None else argv)
    forwarded_args = raw_args if raw_args and raw_args[0] == INTERNAL_RUN_COMMAND else apply_program_alias(raw_args)
    if forwarded_args == ["version"]:
        print(current_release_metadata()["version"])
        return 0

    force_passthrough = bool(forwarded_args and forwarded_args[0] == "--")
    if force_passthrough:
        forwarded_args = forwarded_args[1:]

    session_run_mode = bool(forwarded_args and forwarded_args[0] == INTERNAL_RUN_COMMAND)
    if session_run_mode:
        forwarded_args = forwarded_args[1:]
    elif not force_passthrough:
        managed = dispatch_management_command(
            forwarded_args,
            script_path=os.path.realpath(__file__),
            python_bin=sys.executable,
        )
        if managed is not None:
            return managed

    if session_run_mode:
        try:
            launch_mode = os.getenv(MANAGED_LAUNCH_MODE_ENV, "").strip().lower()
            if launch_mode == LAUNCH_MODE_SHELL:
                return run_with_terminal_filter(resolve_shell_command())
            command = resolve_codex_command(forwarded_args)
            return run_with_terminal_filter(command)
        except FileNotFoundError as exc:
            print(f"dxcli: {exc}", file=sys.stderr)
            return 127
        finally:
            _cleanup_managed_session()

    try:
        command = resolve_codex_command(forwarded_args)
    except FileNotFoundError as exc:
        print(f"dxcli: {exc}", file=sys.stderr)
        return 127

    return subprocess.call(command)


def resolve_shell_command() -> list[str]:
    shell = os.getenv("SHELL", "").strip() or "/bin/bash"
    if not os.path.exists(shell):
        shell = shutil.which("bash") or shutil.which("sh") or "/bin/sh"
    command = [shell]
    shell_name = os.path.basename(shell)
    if shell_name in {"bash", "zsh", "sh", "dash", "ksh"}:
        command.append("-l")
    return command


def _cleanup_managed_session() -> None:
    global_id = os.getenv(MANAGED_GLOBAL_ID_ENV, "").strip()
    if not global_id:
        return
    session_name = f"dxg{global_id}"
    try:
        store = SessionStore()
        record = store.get_by_global_id(global_id)
        if record is not None:
            session_name = str(record.get("session_name") or session_name)
        statuses = query_tmux_statuses()
        if statuses and session_name in statuses:
            return
        store.remove(global_id)
    except ValueError:
        pass


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