from ai.local_ai_api import LocalAIApi
from .models import MindMapNode, MindMapConnection
import json

def generate_initial_mindmap(project):
    prompt = f"""
You are an expert business consultant. Create an initial mind map for a new project.
Project Title: {project.title}
Industry: {project.industry}
Goal: {project.goal}

Respond ONLY with a valid JSON object in the following format:
{{
  "nodes": [
    {{"id": "node_1", "title": "Main Goal", "summary": "Short description", "category": "Strategy"}},
    {{"id": "node_2", "title": "Feature X", "summary": "Short description", "category": "Product"}}
  ],
  "connections": [
    {{"source_id": "node_1", "target_id": "node_2", "how": "Defines what to build", "why": "Feature X is critical to achieve the Main Goal"}}
  ]
}}
Create 6-10 interconnected nodes exploring key business areas like Target Audience, Core Features, Marketing Strategy, Revenue Streams, etc. Ensure the IDs in connections match the nodes.
"""
    response = LocalAIApi.create_response({
        "input": [
            {"role": "system", "content": "You are a helpful business strategy AI. You must respond in valid JSON matching the exact requested format."},
            {"role": "user", "content": prompt}
        ],
        "text": {"format": {"type": "json_object"}}
    })

    if response.get("success"):
        data = LocalAIApi.decode_json_from_response(response)
        if not data:
            return False
            
        # Parse and save to DB
        node_map = {}
        for n in data.get("nodes", []):
            node = MindMapNode.objects.create(
                project=project,
                title=n.get("title", "Untitled"),
                summary=n.get("summary", ""),
                category=n.get("category", "General")
            )
            node_map[n.get("id")] = node
            
        for c in data.get("connections", []):
            source_id = c.get("source_id")
            target_id = c.get("target_id")
            if source_id in node_map and target_id in node_map:
                MindMapConnection.objects.create(
                    project=project,
                    source=node_map[source_id],
                    target=node_map[target_id],
                    how=c.get("how", ""),
                    why=c.get("why", "")
                )
        return True
    return False
