"""Shared auth.json read/write utilities — ported from yt-mcp's sharedAuth.ts."""

from __future__ import annotations

import json
from pathlib import Path
from typing import TypedDict

from .config_helpers import ensure_shared_auth_dir


class SharedAuthData(TypedDict, total=False):
    """Shared authentication data structure."""
    type: str  # "jwt" | "pat"
    access_token: str
    refresh_token: str
    expires_at: int  # in milliseconds
    client_id: str
    pat: str


def read_shared_auth(auth_path: Path | str) -> SharedAuthData | None:
    """Read shared auth data from JSON file.
    
    Returns None if file doesn't exist or cannot be parsed.
    """
    auth_path = Path(auth_path)
    if not auth_path.exists():
        return None
    
    try:
        data = json.loads(auth_path.read_text("utf-8"))
        return data
    except (json.JSONDecodeError, OSError):
        return None


def write_shared_auth(auth_path: Path | str, data: SharedAuthData) -> None:
    """Write shared auth data to JSON file with 0o600 permissions.
    
    Uses atomic write (temp file + rename) for safety.
    """
    auth_path = Path(auth_path)
    ensure_shared_auth_dir(auth_path)
    
    # Atomic write via temp file
    temp_path = auth_path.with_suffix(".tmp")
    temp_path.write_text(json.dumps(data, indent=2), "utf-8")
    
    try:
        temp_path.chmod(0o600)
    except OSError:
        pass
    
    temp_path.replace(auth_path)
    
    try:
        auth_path.chmod(0o600)
    except OSError:
        # Why: chmod is best-effort on Windows and should not block auth persistence.
        pass
