"""Session hooks for Claude Code integration."""

import json
import os
import sys
from datetime import datetime
from pathlib import Path

# Session marker to avoid duplicate prompts
SESSION_MARKER_DIR = Path("/tmp/meld-sessions")


def get_session_marker_path() -> Path:
    """Get the path for the session marker file.

    Uses CLAUDE_SESSION_ID if available, otherwise falls back to
    a date-based marker that resets daily.
    """
    SESSION_MARKER_DIR.mkdir(exist_ok=True)

    # Try to get Claude session ID from environment
    session_id = os.environ.get("CLAUDE_SESSION_ID")

    if session_id:
        return SESSION_MARKER_DIR / f"session-{session_id}"

    # Fallback: use date + parent process ID
    # This ensures we only prompt once per Claude Code session
    ppid = os.getppid()
    today = datetime.now().strftime("%Y%m%d")
    return SESSION_MARKER_DIR / f"session-{ppid}-{today}"


def check_session():
    """Check if this is a new session and emit meld_hello reminder.

    This is called by Claude Code's UserPromptSubmit hook.
    Only outputs on the first prompt of each session.
    """
    marker_path = get_session_marker_path()

    if marker_path.exists():
        # Already reminded this session
        return

    # Mark session as having been reminded
    marker_path.touch()

    # Check if user is logged in
    creds_file = Path.home() / ".meld" / "credentials.json"
    if not creds_file.exists():
        print(
            json.dumps({
                "type": "assistant",
                "content": (
                    "[Meld] Not logged in. Run `meld login` in your terminal "
                    "to connect your personal memory."
                ),
            })
        )
        return

    # Emit reminder to call meld_hello
    print(
        json.dumps({
            "type": "assistant",
            "content": (
                "[Meld Memory] Session start detected.\n\n"
                "IMPORTANT: Call meld_hello() to check user state and whether "
                "a check-in is recommended.\n\n"
                "This returns:\n"
                "- user_state: Current user context level\n"
                "- recommended_action: What to do (onboard/checkin/ready)\n"
                "- greeting: Personalized greeting to use\n"
                "- checkin_info: Whether a check-in is suggested\n\n"
                "If recommended_action is 'checkin', offer to start a check-in."
            ),
        })
    )


if __name__ == "__main__":
    check_session()

