#!/usr/bin/env python3
"""
Research KG Sync - Sync research files to Luzia's research KG

Called by: luzia research-sync
"""

import sys
sys.path.insert(0, '/home/admin/mcp-servers/hybrid-memory-mcp/tools')

from research_to_kg import LuziaResearchExtractor


def sync_research(reprocess: bool = False):
    """Sync all research files to Luzia research KG."""
    extractor = LuziaResearchExtractor()

    if reprocess:
        extractor.index = {"processed": {}}
        extractor.save_index()
        print("Index cleared. Reprocessing all files...")

    results = extractor.process_directory()
    processed = [r for r in results if r.get('status') == 'processed']
    skipped = [r for r in results if r.get('status') == 'skipped']

    print(f"\n📚 Research KG Sync Complete")
    print(f"   New files indexed: {len(processed)}")
    print(f"   Already indexed: {len(skipped)}")

    total_findings = sum(r.get('findings_added', 0) for r in processed)
    total_nodes = sum(r.get('nodes_added', 0) for r in processed)
    if total_findings > 0:
        print(f"   Findings added: {total_findings}")
        print(f"   Nodes added: {total_nodes}")

    extractor.show_stats()


def show_stats():
    """Show research KG statistics."""
    extractor = LuziaResearchExtractor()
    extractor.show_stats()


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--reprocess", action="store_true", help="Reprocess all files")
    parser.add_argument("--stats", action="store_true", help="Show stats only")
    args = parser.parse_args()

    if args.stats:
        show_stats()
    else:
        sync_research(reprocess=args.reprocess)
