#!/usr/bin/env python3
"""Engram Memory — simple one-command interface.

Usage:
    mem save "Simon Kim is the CEO of Hashed"
    mem find "CEO"
    mem who "Simon Kim"
    mem all
    mem status
"""

import sys
from pathlib import Path

# Add project to path
sys.path.insert(0, str(Path(__file__).parent))

from engram.config import EngramConfig
from engram.engine import MemoryEngine

DB = Path.home() / ".engram"


def get_engine():
    return MemoryEngine(EngramConfig(base_dir=DB))


def main():
    if len(sys.argv) < 2:
        print("""
  Engram Memory

  mem save "정보"          저장
  mem find "검색어"        검색
  mem who  "이름"          엔티티 조회
  mem all                  전체 목록
  mem status               상태 확인
  mem remember "이름" "사실"  수동 기억 추가
  mem forget "이름"         엔티티 삭제
        """)
        return

    cmd = sys.argv[1]
    engine = get_engine()

    try:
        if cmd == "save" and len(sys.argv) >= 3:
            text = " ".join(sys.argv[2:])
            result = engine.store(text)
            created = [e.name for e in result.entities_created]
            updated = [e.name for e in result.entities_updated]
            if created:
                print(f"  New: {', '.join(created)}")
            if updated:
                print(f"  Updated: {', '.join(updated)}")
            if result.facts_added:
                print(f"  Learned {len(result.facts_added)} fact(s)")
            if not created and not updated and not result.facts_added:
                print("  No entities or facts found in text.")

        elif cmd == "find" and len(sys.argv) >= 3:
            query = " ".join(sys.argv[2:])
            result = engine.search(query)
            if not result.hits:
                print(f"  Nothing found for '{query}'")
            else:
                for h in result.hits:
                    print(f"  {h.entity.name} ({h.entity.entity_type})")
                    if h.entity.summary:
                        print(f"    {h.entity.summary}")
                    for f in h.facts[:3]:
                        print(f"    - {f.raw_text}")

        elif cmd == "who" and len(sys.argv) >= 3:
            name = " ".join(sys.argv[2:])
            entity = engine.get_entity(name)
            if not entity:
                print(f"  '{name}' not found.")
            else:
                print(f"  {entity.name} [{entity.entity_type}]")
                if entity.summary:
                    print(f"  {entity.summary}")
                if entity.state.role:
                    print(f"  Role: {entity.state.role}")
                if entity.state.affiliation:
                    print(f"  At: {entity.state.affiliation}")
                facts = engine.get_facts(name)
                if facts:
                    print(f"  Facts ({len(facts)}):")
                    for f in facts:
                        print(f"    - {f.raw_text}")

        elif cmd == "all":
            entities = engine.list_entities(limit=50)
            if not entities:
                print("  No memories yet.")
            else:
                print(f"  {len(entities)} entities:")
                for e in entities:
                    line = f"    {e.name} ({e.entity_type})"
                    if e.summary:
                        line += f" — {e.summary[:60]}"
                    print(line)

        elif cmd == "status":
            h = engine.health_check()
            print(f"  Entities: {h['entity_count']}")
            print(f"  Facts: {h['fact_count']}")
            print(f"  Conflicts: {h['pending_conflicts']}")
            print(f"  Status: {h['status']}")

        elif cmd == "remember" and len(sys.argv) >= 4:
            name = sys.argv[2]
            fact = " ".join(sys.argv[3:])
            # Create entity if not exists
            if not engine.get_entity(name):
                engine.create_entity(name)
            result = engine.add_fact(name, fact)
            print(f"  Remembered: {result.action.value} ({result.confidence:.0%})")

        elif cmd == "forget" and len(sys.argv) >= 3:
            name = " ".join(sys.argv[2:])
            entity = engine.get_entity(name)
            if entity:
                engine.storage.delete_entity(entity.id)
                print(f"  Forgot {name}")
            else:
                print(f"  '{name}' not found")

        else:
            print(f"  Unknown command: {cmd}")
            print("  Try: mem save/find/who/all/status/remember/forget")

    finally:
        engine.close()


if __name__ == "__main__":
    main()
