#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Knowledge Graph CLI: Thin entry point for graph operations (Phase 7).

This module provides a simple CLI interface. All heavy lifting is delegated to:
  - knowledge_graph_build.py (graph construction, causal parsing)
  - knowledge_graph_query.py (search, path finding, stats)

Usage:
  python knowledge_graph.py --build              Build graph from brain files
  python knowledge_graph.py --stats              Show graph statistics
  python knowledge_graph.py --causes "query"     What causes this?
  python knowledge_graph.py --prevents "query"   What prevents this?
  python knowledge_graph.py --related "query"    Find related knowledge
  python knowledge_graph.py --chain "from" "to"  Find causal path
  python knowledge_graph.py --hubs               Most connected nodes
"""

import io
import json
import os
import sys
from pathlib import Path

if os.name == 'nt' and __name__ == '__main__':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')


# Import build operations
from pulse.graph.knowledge_graph_build import build_graph, incremental_update

# Import query operations
from pulse.graph.knowledge_graph_query import (
    query_causes, query_prevents, query_related,
    query_chain, get_hub_nodes, get_graph_stats,
)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Knowledge Graph CLI")
        print()
        print("  python knowledge_graph.py --build              Build graph from brain files")
        print("  python knowledge_graph.py --stats              Show graph statistics")
        print('  python knowledge_graph.py --causes "query"     What causes this?')
        print('  python knowledge_graph.py --prevents "query"   What prevents this?')
        print('  python knowledge_graph.py --related "query"    Find related knowledge')
        print('  python knowledge_graph.py --chain "from" "to"  Find causal path')
        print('  python knowledge_graph.py --hubs               Most connected nodes')
        sys.exit(0)

    if "--build" in sys.argv:
        build_graph(verbose=True)

    elif "--stats" in sys.argv:
        stats = get_graph_stats()
        print(f"Knowledge Graph: {stats['total_nodes']} nodes, {stats['total_edges']} edges")
        print(f"Built: {stats['built_at']}")
        print(f"Node types: {json.dumps(stats['node_types'], indent=2)}")
        print(f"Edge types: {json.dumps(stats['edge_types'], indent=2)}")

    elif "--causes" in sys.argv:
        idx = sys.argv.index("--causes")
        query = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""
        results = query_causes(query)
        print(f"What causes '{query}':")
        for r in results:
            print(f"  [{r['type']}] {r['text'][:80]} (conf={r['confidence']})")

    elif "--prevents" in sys.argv:
        idx = sys.argv.index("--prevents")
        query = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""
        results = query_prevents(query)
        print(f"What prevents '{query}':")
        for r in results:
            print(f"  [{r['type']}] {r['text'][:80]} (conf={r['confidence']})")

    elif "--related" in sys.argv:
        idx = sys.argv.index("--related")
        query = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""
        results = query_related(query)
        print(f"Related to '{query}':")
        for r in results:
            print(f"  [{r['type']}] ({r['relationship']}) {r['text'][:80]}")

    elif "--chain" in sys.argv:
        idx = sys.argv.index("--chain")
        from_text = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""
        to_text = sys.argv[idx + 2] if idx + 2 < len(sys.argv) else ""
        chain = query_chain(from_text, to_text)
        if chain:
            print(f"Causal chain: {from_text} -> {to_text}")
            for i, step in enumerate(chain):
                prefix = "  " + ("-> " if i > 0 else "   ")
                print(f"{prefix}[{step['type']}] {step['node'][:80]}")
        else:
            print(f"No causal path found between '{from_text}' and '{to_text}'")

    elif "--hubs" in sys.argv:
        hubs = get_hub_nodes()
        print("Most connected knowledge (hub nodes):")
        for h in hubs:
            print(f"  [{h['type']}] {h['text'][:60]} ({h['connections']} connections)")
