"""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():
        # Output in Claude Code's UserPromptSubmit hook format
        print(json.dumps({
            "hookSpecificOutput": {
                "hookEventName": "UserPromptSubmit",
                "additionalContext": (
                    "[Meld] Not logged in. Run `meld login` in your terminal "
                    "to connect your personal memory."
                )
            }
        }))
        return

    # Emit reminder to call meld_hello in Claude Code's expected format
    # The hook is minimal - just tells Claude to check user state
    # Claude should then behave based on the response:
    # - new_user: Do onboarding (conversational, ask questions)
    # - has_content: Brief greeting, get to work (user came to code, not chat)
    print(json.dumps({
        "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": (
                "[Meld] Call meld_hello() silently to check user state.\n\n"
                "Based on the response:\n"
                "- If state is 'new_user': Offer a quick intro to learn about them\n"
                "- If state is 'has_content': Just greet briefly and help with their request\n"
                "  (Don't push check-ins - they came here to code, not chat)\n"
                "- Only offer check-in if they explicitly ask or it's been 3+ days"
            )
        }
    }))


if __name__ == "__main__":
    check_session()

