#!/usr/bin/env python3
import json
import os
import pwd
import shutil
import subprocess
import sys
from pathlib import Path

USER_NAME = "claude"
HOME_DIR = Path("/home/claude")
ROOT_CLAUDE = Path("/root/.claude")
TARGET_CLAUDE = HOME_DIR / ".claude"
ROOT_CLAUDE_STATE = Path("/root/.claude.json")
ROOT_CLAUDE_STATE_BACKUP = Path("/root/.claude.json.backup")
PROMPTS_DIR = HOME_DIR / ".prompts"
SESSIONS_DIR = HOME_DIR / ".delegate-claude-code" / "sessions"
STUB = Path("/usr/local/bin/delegate-claude-code")
SCRIPT = Path("/home/workspace/Skills/claude-code-delegate/scripts/claude_delegate.py")
TMUX_TMP = HOME_DIR / ".tmux-tmp"


def run(cmd, check=True, capture=False):
    return subprocess.run(cmd, check=check, text=True, capture_output=capture)


def ensure_user():
    try:
        pwd.getpwnam(USER_NAME)
    except KeyError:
        run(["useradd", "-m", "-s", "/bin/bash", USER_NAME])


def copy_if_exists(src: Path, dst: Path):
    if src.exists():
        shutil.copy2(src, dst)


def main():
    ensure_user()
    TARGET_CLAUDE.mkdir(parents=True, exist_ok=True)
    PROMPTS_DIR.mkdir(parents=True, exist_ok=True)
    SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
    TMUX_TMP.mkdir(parents=True, exist_ok=True)

    creds = ROOT_CLAUDE / ".credentials.json"
    if not creds.exists():
        print("ERROR: missing /root/.claude/.credentials.json", file=sys.stderr)
        print("Ask the user to sign in to Claude manually in the Zo terminal, then rerun this setup.", file=sys.stderr)
        sys.exit(1)

    copy_if_exists(creds, TARGET_CLAUDE / ".credentials.json")
    copy_if_exists(ROOT_CLAUDE / "settings.json", TARGET_CLAUDE / "settings.json")
    copy_if_exists(ROOT_CLAUDE_STATE, HOME_DIR / ".claude.json")
    copy_if_exists(ROOT_CLAUDE_STATE_BACKUP, HOME_DIR / ".claude.json.backup")

    run(["chown", "-R", f"{USER_NAME}:{USER_NAME}", str(HOME_DIR)])
    run(["chown", "-R", f"{USER_NAME}:{USER_NAME}", str(TMUX_TMP)])
    run(["chmod", "700", str(TMUX_TMP)])

    stub = f"#!/usr/bin/env bash\nset -euo pipefail\nexec python3 {SCRIPT} dispatch \"$@\"\n"
    STUB.write_text(stub)
    os.chmod(STUB, 0o755)

    token_expired = False
    try:
        creds_data = json.loads((TARGET_CLAUDE / ".credentials.json").read_text())
        expires_at = creds_data.get("claudeAiOauth", {}).get("expiresAt", 0)
        import time
        if expires_at and time.time() * 1000 > expires_at:
            token_expired = True
    except Exception:
        pass

    status = subprocess.run(["runuser", "-u", USER_NAME, "--", "claude", "auth", "status"], capture_output=True, text=True)
    logged_in = '"loggedIn": true' in status.stdout and not token_expired

    result = {
        "user": USER_NAME,
        "home": str(HOME_DIR),
        "stub": str(STUB),
        "tmux_tmp": str(TMUX_TMP),
        "logged_in": logged_in,
        "token_expired": token_expired,
        "auth_status": status.stdout.strip(),
    }
    if token_expired:
        result["action_required"] = "Token expired. Run: claude auth login (in Zo terminal as root), then rerun setup."
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
