#!/usr/bin/env python3
"""
Merge analyzed data with generated responses into app-compatible format
"""

import json
from pathlib import Path
from datetime import datetime

# Files
ANALYZED_FILE = Path.home() / "Documents" / "instagram_dm_leads_analyzed.json"
RESPONSES_FILE = Path.home() / "Documents" / "instagram_dm_responses.json"
OUTPUT_FILE = Path.home() / "Documents" / "instagram_dm_analysis.json"

def main():
    print("Merging data for app...")

    # Load analyzed data
    with open(ANALYZED_FILE) as f:
        analyzed = json.load(f)

    # Load responses
    responses_map = {}
    if RESPONSES_FILE.exists():
        with open(RESPONSES_FILE) as f:
            responses_data = json.load(f)
            for r in responses_data.get("responses", []):
                username = r.get("username", "")
                responses_map[username.lower()] = r.get("suggestedResponse", "")

    print(f"Loaded {len(responses_map)} responses")

    # Transform conversations to app format
    conversations = []
    for conv in analyzed.get("conversations", []):
        analysis = conv.get("analysis", {})
        username = conv.get("participantUsername", "")

        # Get response for this user
        response = responses_map.get(username.lower(), "")

        # Convert to app format
        app_conv = {
            "id": conv.get("id", ""),
            "participantUsername": username,
            "participantDisplayName": conv.get("participantDisplayName", username),
            "profileURL": conv.get("profileURL", f"https://instagram.com/{username}"),
            "lastMessagePreview": conv.get("lastMessagePreview", ""),
            "lastMessageTime": conv.get("lastMessageTime", ""),
            "unreadCount": conv.get("unreadCount", 0),
            "isVerified": conv.get("isVerified", False),
            "threadURL": conv.get("threadURL", ""),
            "messages": conv.get("messages", []),
            "extractedAt": conv.get("extractedAt", datetime.now().isoformat()),
            "analysis": {
                "sentiment": analysis.get("sentiment", "neutral"),
                "intents": [analysis.get("intent", "personal")] if analysis.get("intent") else [],
                "leadScore": analysis.get("leadScore", 0),
                "summary": analysis.get("summary", ""),
                "suggestedResponse": response if response else None,
                "topics": [],
                "urgency": analysis.get("urgency", "low"),
                "analyzedAt": datetime.now().isoformat()
            } if analysis else None
        }
        conversations.append(app_conv)

    # Create app-compatible export
    output = {
        "exportedAt": datetime.now().isoformat(),
        "totalConversations": len(conversations),
        "leadsCount": sum(1 for c in conversations if (c.get("analysis") or {}).get("leadScore", 0) >= 60),
        "conversations": conversations
    }

    # Save
    with open(OUTPUT_FILE, "w") as f:
        json.dump(output, f, indent=2, ensure_ascii=False)

    print(f"Saved {len(conversations)} conversations to {OUTPUT_FILE}")

    # Stats
    with_response = sum(1 for c in conversations if (c.get("analysis") or {}).get("suggestedResponse"))
    hot = sum(1 for c in conversations if (c.get("analysis") or {}).get("leadScore", 0) >= 60)
    warm = sum(1 for c in conversations if 40 <= (c.get("analysis") or {}).get("leadScore", 0) < 60)

    print(f"\nStats:")
    print(f"  Hot leads (>=60): {hot}")
    print(f"  Warm leads (40-59): {warm}")
    print(f"  With responses: {with_response}")

if __name__ == "__main__":
    main()
