#!/usr/bin/env python3
"""CLI for agent-handoff: session continuity toolkit for AI agents."""

import argparse
import json
import os
import sys

from . import __version__
from .core import init, snapshot, resume, push_to_memoryvault


def cmd_init(args):
    """Initialize handoff files."""
    result = init(args.directory, agent_name=args.name, force=args.force)
    if result["created"]:
        print(f"Created {len(result['created'])} file(s):")
        for f in result["created"]:
            print(f"  + {f}")
    if result["skipped"]:
        print(f"Skipped {len(result['skipped'])} existing file(s):")
        for f in result["skipped"]:
            print(f"  ~ {f} (use --force to overwrite)")
    if not result["created"] and result["skipped"]:
        print("\nAll files already exist. Use --force to overwrite.")


def cmd_snapshot(args):
    """Generate a session snapshot."""
    content = snapshot(args.directory, mode=args.mode)
    if args.stdout:
        print(content)
    else:
        print(f"Snapshot written to {os.path.join(args.directory, 'HANDOFF.md')}")
        print(f"  Lines: {len(content.splitlines())}")
        print(f"  Chars: {len(content)}")


def cmd_resume(args):
    """Generate a resume briefing."""
    briefing = resume(args.directory)
    if args.json:
        print(json.dumps({"briefing": briefing, "chars": len(briefing)}))
    else:
        print(briefing)


def cmd_push(args):
    """Push handoff state to MemoryVault."""
    api_key = args.api_key or os.environ.get("MEMORYVAULT_API_KEY")
    if not api_key:
        print("Error: Provide --api-key or set MEMORYVAULT_API_KEY", file=sys.stderr)
        sys.exit(1)

    result = push_to_memoryvault(args.directory, api_key, agent_name=args.name)
    if result.get("ok"):
        print(f"Pushed to MemoryVault: {result['key']}")
    else:
        print(f"Error: {result.get('error', 'unknown')}", file=sys.stderr)
        sys.exit(1)


def cmd_auto(args):
    """Auto-update: snapshot + optional push. Meant for cron/heartbeat."""
    content = snapshot(args.directory, mode=args.mode)
    print(f"Snapshot updated ({len(content)} chars)")

    api_key = args.api_key or os.environ.get("MEMORYVAULT_API_KEY")
    if api_key:
        result = push_to_memoryvault(args.directory, api_key, agent_name=args.name)
        if result.get("ok"):
            print(f"Pushed to MemoryVault: {result['key']}")
        else:
            print(f"Push failed: {result.get('error', 'unknown')}", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(
        prog="agent-handoff",
        description="Session continuity toolkit for AI agents. "
        "Maintain SOUL.md, MEMORY.md, and HANDOFF.md across sessions.",
    )
    parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")

    sub = parser.add_subparsers(dest="command", required=True)

    # init
    p_init = sub.add_parser("init", help="Initialize handoff files in a directory")
    p_init.add_argument("directory", nargs="?", default=".", help="Target directory (default: .)")
    p_init.add_argument("--name", default="agent", help="Agent name for SOUL.md")
    p_init.add_argument("--force", action="store_true", help="Overwrite existing files")
    p_init.set_defaults(func=cmd_init)

    # snapshot
    p_snap = sub.add_parser("snapshot", help="Generate session snapshot (writes HANDOFF.md)")
    p_snap.add_argument("directory", nargs="?", default=".", help="Target directory")
    p_snap.add_argument("--mode", default="build", help="Session mode label (build/engage/write)")
    p_snap.add_argument("--stdout", action="store_true", help="Also print to stdout")
    p_snap.set_defaults(func=cmd_snapshot)

    # resume
    p_resume = sub.add_parser("resume", help="Generate resume briefing for a new session")
    p_resume.add_argument("directory", nargs="?", default=".", help="Target directory")
    p_resume.add_argument("--json", action="store_true", help="Output as JSON")
    p_resume.set_defaults(func=cmd_resume)

    # push
    p_push = sub.add_parser("push", help="Push handoff state to MemoryVault")
    p_push.add_argument("directory", nargs="?", default=".", help="Target directory")
    p_push.add_argument("--name", default="agent", help="Agent name for MV key")
    p_push.add_argument("--api-key", help="MemoryVault API key (or set MEMORYVAULT_API_KEY)")
    p_push.set_defaults(func=cmd_push)

    # auto
    p_auto = sub.add_parser("auto", help="Auto-update: snapshot + optional push (for cron)")
    p_auto.add_argument("directory", nargs="?", default=".", help="Target directory")
    p_auto.add_argument("--name", default="agent", help="Agent name")
    p_auto.add_argument("--mode", default="auto", help="Session mode label")
    p_auto.add_argument("--api-key", help="MemoryVault API key for push (optional)")
    p_auto.set_defaults(func=cmd_auto)

    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
