import json
import os
from pathlib import Path
from datetime import datetime

GENESIS_ROOT = Path("E:/genesis-system")
ENTITIES_JSONL = GENESIS_ROOT / "KNOWLEDGE_GRAPH" / "entities.jsonl"
OUTPUT_JSON = GENESIS_ROOT / "memory" / "knowledge_graph.json"

# Mapping logic
TYPE_MAPPING = {
    "technology_enabler": "RESOURCE",
    "protocol": "PATTERN",
    "strategy_node": "DECISION",
    "integration": "INTEGRATION",
    "client": "CLIENT",
    "blocker": "BLOCKER",
    "solution": "SOLUTION",
    "lesson": "LESSON"
}

def migrate():
    print(f"🔄 Starting RLM Migration from {ENTITIES_JSONL}...")
    
    if not ENTITIES_JSONL.exists():
        print(f"❌ Source file {ENTITIES_JSONL} not found.")
        return

    entities = []
    
    with open(ENTITIES_JSONL, "r") as f:
        for line in f:
            if not line.strip(): continue
            try:
                data = json.loads(line)
                
                # Extract basic info
                name = data.get("id") or data.get("name")
                if not name: continue
                
                raw_type = data.get("type", "observation")
                entity_type = TYPE_MAPPING.get(raw_type.lower(), "PATTERN")
                
                # Build observations
                observations = []
                if data.get("title"): observations.append(f"Title: {data['title']}")
                if data.get("source"): observations.append(f"Source: {data['source']}")
                if data.get("relevance"): observations.append(f"Relevance: {data['relevance']}")
                if data.get("patent_synergy"): observations.append(f"Patent Synergy: {data['patent_synergy']}")
                if data.get("axiom_id"): observations.append(f"Axiom ID: {data['axiom_id']}")
                if data.get("description"): observations.append(f"Description: {data['description']}")
                
                entities.append({
                    "name": name,
                    "entityType": entity_type,
                    "observations": observations,
                    "createdAt": data.get("timestamp") or datetime.now().isoformat()
                })
            except Exception as e:
                print(f"⚠️ Error parsing line: {e}")

    # Initialize graph
    graph = {
        "entities": entities,
        "relations": []
    }
    
    # Simple relation inference (e.g., if entity has 'source' that matches another entity ID)
    # For now, keeping it simple as relations.jsonl might not exist or be sparsely used.
    
    OUTPUT_JSON.parent.mkdir(parents=True, exist_ok=True)
    with open(OUTPUT_JSON, "w") as f:
        json.dump(graph, f, indent=2)
        
    print(f"✅ Migration complete. {len(entities)} entities moved to {OUTPUT_JSON}")

if __name__ == "__main__":
    migrate()
