#!/usr/bin/env python3
"""
Sentiment & Feedback Tracker for Novyx Core
Monitors external mentions, feedback, and sentiment about Novyx

Usage:
    python tools/sentiment_tracker.py                    # Track all
    python tools/sentiment_tracker.py --source github    # GitHub issues only
    python tools/sentiment_tracker.py --ingest           # Save as artifacts

Integrates with Query Engine for semantic analysis
"""

import json
import sys
from datetime import datetime
from tools.util import calculate_hash_for_new_artifact
from pathlib import Path
from typing import Dict, List

# Add project root to path
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

try:
    from tools.query import semantic_search
    QUERY_AVAILABLE = True
except ImportError:
    print("⚠️  Query Engine not available. Limited functionality.")
    QUERY_AVAILABLE = False


def track_internal_feedback() -> List[Dict]:
    """
    Track feedback mentions in existing Knowledge Graph artifacts.
    Uses semantic search to find discussions about Novyx.
    """
    if not QUERY_AVAILABLE:
        return []
    
    queries = [
        "feedback on Novyx",
        "improvement suggestions",
        "feature requests",
        "bug reports",
        "user experience"
    ]
    
    feedback_items = []
    
    for query in queries:
        try:
            results = semantic_search(query=query, top_k=5, min_confidence=0.25)
            for result in results:
                feedback_items.append({
                    "query": query,
                    "artifact": result.get("id", "unknown"),
                    "content": result.get("content", "")[:200],
                    "confidence": result.get("confidence", 0.0),
                    "source": "knowledge_graph"
                })
        except Exception as e:
            print(f"⚠️  Query '{query}' failed: {e}")
    
    return feedback_items


def track_github_activity() -> List[Dict]:
    """
    Track GitHub activity (issues, PRs, discussions).
    Requires requests library and public repo.
    """
    try:
        import requests
    except ImportError:
        return []
    
    repo = "novyxlabs/novyx-core"
    api_base = "https://api.github.com"
    
    activity = []
    
    # Fetch recent issues
    try:
        url = f"{api_base}/repos/{repo}/issues"
        response = requests.get(url, params={"state": "all", "per_page": 10}, timeout=10)
        if response.status_code == 200:
            issues = response.json()
            for issue in issues:
                activity.append({
                    "type": "github_issue",
                    "title": issue.get("title"),
                    "body": issue.get("body", "")[:200],
                    "url": issue.get("html_url"),
                    "created_at": issue.get("created_at"),
                    "state": issue.get("state"),
                    "comments": issue.get("comments", 0),
                    "source": "github"
                })
    except Exception as e:
        print(f"⚠️  GitHub issues fetch failed: {e}")
    
    return activity


def analyze_sentiment(items: List[Dict]) -> Dict:
    """
    Simple sentiment analysis based on keywords.
    (Can be enhanced with ML models later)
    """
    positive_keywords = ["great", "excellent", "love", "amazing", "helpful", "useful", "awesome"]
    negative_keywords = ["bug", "issue", "problem", "error", "broken", "fail", "missing"]
    neutral_keywords = ["question", "how", "what", "when", "where", "suggestion"]
    
    sentiment = {
        "positive": 0,
        "negative": 0,
        "neutral": 0,
        "total": len(items)
    }
    
    for item in items:
        text = (item.get("content", "") + " " + item.get("body", "") + " " + item.get("title", "")).lower()
        
        pos_count = sum(1 for kw in positive_keywords if kw in text)
        neg_count = sum(1 for kw in negative_keywords if kw in text)
        neu_count = sum(1 for kw in neutral_keywords if kw in text)
        
        if pos_count > neg_count and pos_count > neu_count:
            sentiment["positive"] += 1
        elif neg_count > pos_count:
            sentiment["negative"] += 1
        else:
            sentiment["neutral"] += 1
    
    return sentiment


def categorize_feedback(items: List[Dict]) -> Dict:
    """Categorize feedback by type."""
    categories = {
        "feature_requests": [],
        "bug_reports": [],
        "questions": [],
        "improvements": [],
        "praise": []
    }
    
    for item in items:
        text = (item.get("content", "") + " " + item.get("body", "") + " " + item.get("title", "")).lower()
        
        if any(kw in text for kw in ["feature", "add", "would be great if"]):
            categories["feature_requests"].append(item)
        elif any(kw in text for kw in ["bug", "error", "broken", "crash"]):
            categories["bug_reports"].append(item)
        elif any(kw in text for kw in ["how", "what", "question", "help"]):
            categories["questions"].append(item)
        elif any(kw in text for kw in ["improve", "better", "enhance", "optimize"]):
            categories["improvements"].append(item)
        elif any(kw in text for kw in ["love", "great", "excellent", "amazing"]):
            categories["praise"].append(item)
    
    return categories


def ingest_as_artifact(feedback_items: List[Dict], sentiment: Dict, categories: Dict):
    """Ingest feedback as Novyx artifact."""
    FEEDBACK_DIR = Path(PROJECT_ROOT) / "memory" / "strategy" / "feedback"
    FEEDBACK_DIR.mkdir(parents=True, exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
    artifact_id = f"feedback_snapshot_{timestamp}"
    
    artifact = {
        "@context": "https://novyx.ai/schemas/v1",
        "@type": "FeedbackSnapshot",
        "uuid": artifact_id,
        "novyx:ingestedAt": datetime.now().isoformat(),
        "totalItems": len(feedback_items),
        "sentiment": sentiment,
        "categories": {
            "feature_requests": len(categories["feature_requests"]),
            "bug_reports": len(categories["bug_reports"]),
            "questions": len(categories["questions"]),
            "improvements": len(categories["improvements"]),
            "praise": len(categories["praise"])
        },
        "items": feedback_items[:20],  # Store top 20
        "sources": list(set(item.get("source", "unknown") for item in feedback_items))
    }
    
    # Generate integrity hash
    integrity_hash = calculate_hash_for_new_artifact(artifact)
    artifact["novyx:integrityHash"] = integrity_hash
    
    filepath = FEEDBACK_DIR / f"{artifact_id}.jsonld"
    with open(filepath, 'w') as f:
        json.dump(artifact, f, indent=2)
    
    print(f"\n📥 Feedback ingested: {filepath}")
    print(f"🔒 Integrity hash: {integrity_hash[:32]}...")
    
    return filepath


def display_report(items: List[Dict], sentiment: Dict, categories: Dict):
    """Display formatted feedback report."""
    print("\n" + "="*70)
    print("💬 NOVYX CORE FEEDBACK & SENTIMENT REPORT")
    print("="*70)
    
    print(f"\n📅 Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}")
    print(f"\n📊 Total Feedback Items: {len(items)}")
    
    if len(items) == 0:
        print("\n⚠️  No feedback found. Possible reasons:")
        print("   • Repository not public yet")
        print("   • No issues/discussions created")
        print("   • Query Engine has no relevant artifacts")
        print("\n💡 Run again after Phase 2 launch (GitHub stars campaign)")
        return
    
    # Sentiment breakdown
    print("\n😊 Sentiment Analysis:")
    print(f"   Positive:  {sentiment['positive']:2d} ({sentiment['positive']/sentiment['total']*100:.1f}%)")
    print(f"   Neutral:   {sentiment['neutral']:2d} ({sentiment['neutral']/sentiment['total']*100:.1f}%)")
    print(f"   Negative:  {sentiment['negative']:2d} ({sentiment['negative']/sentiment['total']*100:.1f}%)")
    
    # Category breakdown
    print("\n📂 Feedback Categories:")
    print(f"   ⭐ Praise:            {len(categories['praise'])}")
    print(f"   🎯 Feature Requests:  {len(categories['feature_requests'])}")
    print(f"   💡 Improvements:      {len(categories['improvements'])}")
    print(f"   ❓ Questions:         {len(categories['questions'])}")
    print(f"   🐛 Bug Reports:       {len(categories['bug_reports'])}")
    
    # Top feedback items
    if categories["feature_requests"]:
        print("\n🎯 Top Feature Requests:")
        for i, item in enumerate(categories["feature_requests"][:3], 1):
            print(f"   {i}. {item.get('title', item.get('query', 'Untitled'))}")
    
    if categories["bug_reports"]:
        print("\n🐛 Bug Reports:")
        for i, item in enumerate(categories["bug_reports"][:3], 1):
            print(f"   {i}. {item.get('title', 'Bug reported')}")
    
    # Sources
    sources = list(set(item.get("source", "unknown") for item in items))
    print(f"\n📡 Sources: {', '.join(sources)}")
    
    print("\n" + "="*70)


def main():
    """Main execution."""
    import sys
    
    mode = sys.argv[1] if len(sys.argv) > 1 else "track"
    
    print("🔍 Tracking feedback & sentiment...")
    
    # Collect feedback from multiple sources
    all_feedback = []
    
    # 1. Internal Knowledge Graph
    if QUERY_AVAILABLE:
        print("\n📚 Querying Knowledge Graph for feedback mentions...")
        kg_feedback = track_internal_feedback()
        all_feedback.extend(kg_feedback)
        print(f"   Found {len(kg_feedback)} relevant artifacts")
    
    # 2. GitHub activity
    print("\n🐙 Checking GitHub for issues/PRs...")
    github_feedback = track_github_activity()
    all_feedback.extend(github_feedback)
    print(f"   Found {len(github_feedback)} GitHub items")
    
    # Analyze sentiment and categorize
    sentiment = analyze_sentiment(all_feedback)
    categories = categorize_feedback(all_feedback)
    
    # Display report
    display_report(all_feedback, sentiment, categories)
    
    # Ingest if requested
    if mode == "--ingest" and len(all_feedback) > 0:
        ingest_as_artifact(all_feedback, sentiment, categories)
        print("\n✅ Feedback ingested as artifact!")
    elif mode == "--ingest":
        print("\n⚠️  No feedback to ingest. Skipping artifact creation.")
    else:
        print("\n💡 Tip: Run with --ingest to save feedback as artifact")


if __name__ == "__main__":
    main()
