"""
test_memory_v2.py - Tests for MemoryCore v2
"""

import sys
import os
import json
import tempfile
from pathlib import Path
from datetime import datetime, timezone, timedelta

PROJECT_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from memory_core import MemoryCore


def create_test_db():
    """Create a temporary test database"""
    tmpdir = tempfile.mkdtemp()
    return MemoryCore(db_path=tmpdir)


def test_test_records_excluded():
    """Test records with kind='test' should not appear in active context"""
    print("\n=== Test: test records excluded ===")
    core = create_test_db()
    
    test_record = core.save_memory(
        content="This is test data",
        kind="test",
        status="active"
    )
    
    active = core.retrieve_active_context()
    test_in_active = any(r['id'] == test_record['id'] for r in active)
    
    if not test_in_active:
        print("PASS: test kind correctly excluded")
        return True
    else:
        print("FAIL: test kind incorrectly included")
        return False


def test_archived_records_excluded():
    """Archived records should not appear in active context"""
    print("\n=== Test: archived records excluded ===")
    core = create_test_db()
    
    record = core.save_memory(
        content="Archived fact",
        kind="fact",
        status="active"
    )
    core.archive_memory(record['id'])
    
    active = core.retrieve_active_context()
    archived_in_active = any(r['id'] == record['id'] for r in active)
    
    if not archived_in_active:
        print("PASS: archived status correctly excluded")
        return True
    else:
        print("FAIL: archived record incorrectly included")
        return False


def test_superseded_records_excluded():
    """Superseded records should not appear in active context"""
    print("\n=== Test: superseded records excluded ===")
    core = create_test_db()
    
    old = core.save_memory(
        content="Use model A",
        kind="project_decision",
        status="active"
    )
    
    new = core.save_memory(
        content="Use model B",
        kind="project_decision",
        status="active",
        supersedes=old['id']
    )
    
    active = core.retrieve_active_context()
    
    old_record = core.get_memory(old['id'])
    new_record = core.get_memory(new['id'])
    
    old_in_active = any(r['id'] == old['id'] for r in active)
    new_in_active = any(r['id'] == new['id'] for r in active)
    
    if old_record['metadata']['status'] == "superseded" and not old_in_active and new_in_active:
        print("PASS: supersedes logic works correctly")
        return True
    else:
        print(f"FAIL: old status={old_record['metadata']['status']}, old_in_active={old_in_active}, new_in_active={new_in_active}")
        return False


def test_expired_records_excluded():
    """Expired records should not appear in active context"""
    print("\n=== Test: expired records excluded ===")
    core = create_test_db()
    
    expired_time = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
    record = core.save_memory(
        content="Expired fact",
        kind="fact",
        status="active",
        expires_at=expired_time
    )
    
    active = core.retrieve_active_context()
    expired_in_active = any(r['id'] == record['id'] for r in active)
    
    if not expired_in_active:
        print("PASS: expired records correctly excluded")
        return True
    else:
        print("FAIL: expired record incorrectly included")
        return False


def test_active_kinds_included():
    """Active kinds should be included"""
    print("\n=== Test: active kinds included ===")
    core = create_test_db()
    
    kinds = ["rule", "preference", "project_decision", "fact"]
    records = []
    
    for kind in kinds:
        record = core.save_memory(
            content=f"Test {kind}",
            kind=kind,
            status="active"
        )
        records.append(record)
    
    active = core.retrieve_active_context()
    active_ids = {r['id'] for r in active}
    all_included = all(r['id'] in active_ids for r in records)
    
    if all_included:
        print("PASS: all active kinds included")
        return True
    else:
        print("FAIL: some active kinds missing")
        return False


def test_export_import():
    """Export and import should work correctly"""
    print("\n=== Test: export/import ===")
    core = create_test_db()
    
    core.save_memory(content="Record 1", kind="fact")
    core.save_memory(content="Record 2", kind="rule")
    
    tmpfile = tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False)
    tmpfile.close()
    count = core.export_memory(tmpfile.name)
    
    core2 = create_test_db()
    imported = core2.import_memory(tmpfile.name)
    
    os.unlink(tmpfile.name)
    
    if count == 2 and imported == 2:
        print("PASS: export/import works correctly")
        return True
    else:
        print(f"FAIL: exported {count}, imported {imported}")
        return False


def test_delete_creates_backup():
    """Delete should create backup file"""
    print("\n=== Test: delete creates backup ===")
    core = create_test_db()
    
    record = core.save_memory(
        content="To be deleted",
        kind="fact"
    )
    
    deleted = core.delete_memory(record['id'])
    backup_file = core.db_path / f"deleted_{record['id']}.json"
    backup_exists = backup_file.exists()
    
    if deleted and backup_exists:
        print("PASS: delete creates backup")
        return True
    else:
        print(f"FAIL: deleted={deleted}, backup_exists={backup_exists}")
        return False


def run_all_tests():
    """Run all tests"""
    print("=" * 60)
    print("MemoryCore v2 Tests")
    print(f"Project root: {PROJECT_ROOT}")
    print("=" * 60)
    
    tests = [
        test_test_records_excluded,
        test_archived_records_excluded,
        test_superseded_records_excluded,
        test_expired_records_excluded,
        test_active_kinds_included,
        test_export_import,
        test_delete_creates_backup,
    ]
    
    results = []
    for test in tests:
        try:
            result = test()
            results.append(result)
        except Exception as e:
            print(f"ERROR in {test.__name__}: {e}")
            import traceback
            traceback.print_exc()
            results.append(False)
    
    print("\n" + "=" * 60)
    print(f"Results: {sum(results)}/{len(results)} passed")
    print("=" * 60)
    
    return all(results)


if __name__ == '__main__':
    success = run_all_tests()
    sys.exit(0 if success else 1)
