#!/usr/bin/env python3
"""Sentiment + theme analyzer (heuristic, no deps).
Usage: python3 sentiment_analyzer.py reviews.jsonl
Input: one JSON per line {"id","text"}
Output: per-item JSON + aggregate summary.
"""
import json, re, sys
from collections import Counter

POS = re.compile(r'\b(great|awesome|excellent|love|happy|amazing|good|best|fast|easy|helpful|perfect|recommend|thanks|thank|smooth|fantastic|wonderful|impressed)\b', re.I)
NEG = re.compile(r'\b(bad|terrible|awful|slow|broken|bug|issue|problem|worst|hate|angry|frustrat\w*|disappoint\w*|confus\w*|poor|waste|refund|fail\w*|error|annoy\w*|unusable|crash)\b', re.I)
EMOTIONS = {
 'anger': r'\b(angry|furious|hate|rage|annoyed|frustrated)\b',
 'joy': r'\b(happy|glad|pleased|love|excited|thrilled)\b',
 'disappointment': r'\b(disappointed|let down|unfortunate|regret)\b',
 'trust': r'\b(trust|reliable|dependable|consistent)\b',
 'urgency': r'\b(asap|urgent|immediately|right away|need.*now)\b',
}
TOPIC = re.compile(r'\b(billing|invoice|payment|shipping|delivery|support|customer service|ui|ux|app|website|login|password|performance|speed|quality|price|pricing|feature|update|refund|account|email|notification)\b', re.I)

def classify(text):
    p = len(POS.findall(text)); n = len(NEG.findall(text))
    if p > n: return 'positive'
    if n > p: return 'negative'
    return 'neutral'

def main(path):
    items=[json.loads(l) for l in open(path) if l.strip()]
    out=[]
    for it in items:
        t=it.get('text','')
        emo=[k for k,rx in EMOTIONS.items() if re.search(rx,t)]
        topics=sorted(set(TOPIC.findall(t.lower())))
        out.append({'id':it.get('id'),'sentiment':classify(t),'emotions':emo,'topics':topics,'text':t[:160]})
    agg={'total':len(items),
         'sentiment_breakdown':dict(Counter(o['sentiment'] for o in out)),
         'top_emotions':dict(Counter(e for o in out for e in o['emotions'])),
         'top_topics':dict(Counter(t for o in out for t in o['topics'])),
         'items':out}
    print(json.dumps(agg, indent=2))

if __name__=='__main__': main(sys.argv[1])
