"""Trace — universal agent context tracking.

Tracks what codebase an AI agent is working in. Any tool can read
~/.trace/active_project to know the current project context.

Usage:
    from trace_pkg import active_project, set_active_project

    # Read current project
    project = active_project()  # Path or None

    # Set current project (usually done by the hook)
    set_active_project("/path/to/project")
"""
from __future__ import annotations

from pathlib import Path

__version__ = "0.1.0"

TRACE_DIR = Path.home() / ".trace"
ACTIVE_PROJECT_FILE = TRACE_DIR / "active_project"


def active_project() -> Path | None:
    """Read the currently active project path."""
    try:
        text = ACTIVE_PROJECT_FILE.read_text().strip()
        if text:
            p = Path(text)
            if p.is_dir():
                return p
    except (OSError, ValueError):
        pass
    return None


def set_active_project(path: str | Path) -> None:
    """Set the active project path."""
    TRACE_DIR.mkdir(parents=True, exist_ok=True)
    ACTIVE_PROJECT_FILE.write_text(str(Path(path).resolve()) + "\n")


def cli() -> None:
    """CLI entry point."""
    import sys

    if len(sys.argv) > 1 and sys.argv[1] == "set":
        if len(sys.argv) < 3:
            print("Usage: trace set <path>", file=sys.stderr)
            sys.exit(1)
        set_active_project(sys.argv[2])
        print(f"Active project: {Path(sys.argv[2]).resolve()}")
    else:
        project = active_project()
        if project:
            print(project)
        else:
            print("No active project", file=sys.stderr)
            sys.exit(1)
