"""CLI tool for session-start hook injection.

Same algorithm as memory_timeline MCP tool — reads directly from SQLite.
Also loads Memory Bank (activeContext + progress) for full context injection.

Usage:
    python -m neo_cortex.timeline_cli --data-dir /path/to/data
    python -m neo_cortex.timeline_cli --data-dir /path/to/data --n 15 --mb /path/to/memory_bank
"""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path


def _log(msg: str) -> None:
    """Diagnostic log to stderr (captured by hook script into log file)."""
    print(f"[timeline_cli] {msg}", file=sys.stderr)


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description="Cortex session-start context injection")
    parser.add_argument("--data-dir", help="Cortex data directory (has cortex_db/, memory_index.db)")
    parser.add_argument("--n", type=int, default=10, help="Number of recent memories")
    parser.add_argument("--project", default=None, help="Filter by project")
    parser.add_argument("--mb", default=None, help="Memory Bank directory path")
    parser.add_argument("--mb-max", type=int, default=2000, help="Max chars per MB file")
    args = parser.parse_args(argv)

    _log(f"started, args={args}")

    # Discover data dir
    data_dir = args.data_dir or os.environ.get("CORTEX_DATA_DIR")
    if not data_dir:
        # Convention: check common locations
        for candidate in [
            os.path.join(os.getcwd(), ".neo", "cortex", "data"),
            os.path.expanduser("~/neo-ram"),
        ]:
            if os.path.isdir(os.path.join(candidate, "cortex_db")):
                data_dir = candidate
                break

    if not data_dir:
        _log("no data dir found — exiting")
        return

    _log(f"data_dir={data_dir}")

    # Discover MB path
    mb_path = args.mb
    if not mb_path:
        # Convention: memory_bank/ next to cortex_db/
        candidate = os.path.join(data_dir, "memory_bank")
        if os.path.isdir(candidate):
            mb_path = candidate

    _log(f"mb_path={mb_path}")

    # Configure paths (same as embedded mode)
    from neo_cortex.subscriber import configure_paths
    configure_paths(data_dir)
    from neo_cortex import config

    db_path = config.MEMORY_INDEX_DB_PATH
    if not Path(db_path).exists():
        _log(f"index db not found at {db_path} — exiting")
        return

    from neo_cortex.memory_index import MemoryIndex

    index = MemoryIndex(db_path)
    _log(f"index opened, count={index.count()}")

    # --- Output ---
    print("§MBEL:5.0")
    print()

    # Stats
    total = index.count()
    print("# Cortex{stats}")
    print(f"@memories::{total}")
    print()

    # Timeline (same algorithm as MCP memory_timeline → index.timeline)
    memories = index.timeline(n=args.n, project=args.project)
    if memories:
        print(f"# Cortex{{recentTimeline}} (last {len(memories)})")
        for m in memories:
            print(f"> {m.title} [{m.project}] #{m.topic} energy={m.energy:.1f}")
        print()

    # Memory Bank
    if mb_path:
        for fname in ["activeContext.md", "progress.md"]:
            fpath = os.path.join(mb_path, fname)
            if not os.path.exists(fpath):
                continue
            content = Path(fpath).read_text().strip()
            if len(content) > args.mb_max:
                content = content[: args.mb_max] + "\n[...truncated]"
            print(f"# MB::{fname}")
            print(content)
            print()

    # Hierarchy reminder
    print("# MemoryHierarchy")
    print("!primary::cortex{memory_query per qualsiasi cosa dovresti sapere}")
    print("!legacy::~/memory_bank/{solo milestone, non fonte primaria}")
    print("!rule::domanda->cortex first->poi rispondi")
    print()


if __name__ == "__main__":
    main()
