from __future__ import annotations

from pathlib import Path

from prompt_auto_lab.api.models import User
from prompt_auto_lab.core.user_store import (
    UserRecord,
    create_user_record,
    ensure_user_record,
    get_user_dir as core_get_user_dir,
    get_user_record,
    get_user_session_dir as core_get_user_session_dir,
    get_user_sessions_file as core_get_user_sessions_file,
    login_user_record,
)


def _to_api_user(record: UserRecord) -> User:
    return User(
        id=record.id,
        created_at=record.created_at,
        last_login=record.last_login,
    )


def get_user(user_id: str) -> User | None:
    """Get user by ID. Returns None if not found."""
    record = get_user_record(user_id)
    if record is None:
        return None
    return _to_api_user(record)


def create_user(user_id: str) -> User:
    """Create a new user. Raises ValueError if user already exists."""
    return _to_api_user(create_user_record(user_id))


def login_user(user_id: str) -> User:
    """Login user - creates if not exists, updates last_login if exists."""
    return _to_api_user(login_user_record(user_id))


def ensure_user(user_id: str) -> User:
    """Ensure user exists, create if not. For CLI usage."""
    return _to_api_user(ensure_user_record(user_id))


def get_user_dir(user_id: str) -> Path:
    """Get the user's data directory."""
    return core_get_user_dir(user_id)


def get_user_sessions_file(user_id: str) -> Path:
    """Get path to user's sessions.json file."""
    return core_get_user_sessions_file(user_id)


def get_user_session_dir(user_id: str, session_id: str) -> Path:
    """Get the session directory for a user's session."""
    return core_get_user_session_dir(user_id, session_id)
