#!/usr/bin/env python3
import sys

from grnexus import NeuralNetwork
from lib.grnexus_layers import DenseLayer, DropoutLayer
from lib.grnexus_activations import ReLU
from lib.grnexus_normalization import Softmax

print("=" * 60)
print("GRNexus - Sentiment Analysis Demo")
print("Simple Bag-of-Words approach")
print("=" * 60)

# Training data - English
train_texts = [
    "I love this product, it's amazing!",
    "This is the best thing ever!",
    "Absolutely wonderful experience!",
    "Great quality and fast shipping!",
    "I'm very happy with my purchase!",
    "Terrible product, waste of money",
    "Very disappointed, poor quality",
    "Worst purchase ever, don't buy",
    "Horrible experience, never again",
    "Complete garbage, total ripoff"
]

train_labels = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]  # 1=Positive, 0=Negative

# Simple Bag of Words Vectorizer
class SimpleVectorizer:
    def __init__(self, max_features=100):
        self.max_features = max_features
        self.vocab = {}
    
    def fit(self, texts):
        word_count = {}
        for text in texts:
            for word in self.tokenize(text):
                word_count[word] = word_count.get(word, 0) + 1
        
        sorted_words = sorted(word_count.items(), key=lambda x: -x[1])[:self.max_features]
        self.vocab = {word: idx for idx, (word, _) in enumerate(sorted_words)}
    
    def transform(self, texts):
        return [self.text_to_vector(text) for text in texts]
    
    def tokenize(self, text):
        import re
        return re.sub(r'[^a-z\s]', '', text.lower()).split()
    
    def text_to_vector(self, text):
        vector = [0.0] * len(self.vocab)
        for word in self.tokenize(text):
            if word in self.vocab:
                vector[self.vocab[word]] += 1.0
        # Normalize
        total = sum(vector)
        if total > 0:
            vector = [v / total for v in vector]
        return vector

# Create vectorizer and fit
print("\n1. Creating vocabulary...")
vectorizer = SimpleVectorizer(max_features=50)
vectorizer.fit(train_texts)
print(f"   Vocabulary size: {len(vectorizer.vocab)}")

# Transform texts
print("\n2. Vectorizing texts...")
x_train = vectorizer.transform(train_texts)
y_train = [[0.0, 1.0] if label == 1 else [1.0, 0.0] for label in train_labels]

# Create model
print("\n3. Creating neural network...")
model = NeuralNetwork(
    loss='cross_entropy',
    optimizer='sgd',
    learning_rate=0.1,
    name='sentiment_classifier'
)

input_dim = len(vectorizer.vocab)
model.add(DenseLayer(units=32, input_dim=input_dim, activation=ReLU()))
model.add(DropoutLayer(rate=0.3))
model.add(DenseLayer(units=16, input_dim=32, activation=ReLU()))
model.add(DenseLayer(units=2, input_dim=16, activation=Softmax()))

# Train
print("\n4. Training model...")
model.train(x_train, y_train, epochs=100, batch_size=2, verbose=False)

# Save model
model.save('sentiment_model.nexus')
print("   Model saved!")

# Test predictions
print("\n5. Testing predictions:")
print("-" * 60)

test_texts = [
    "This is absolutely fantastic!",
    "Terrible waste of time",
    "I love it so much!",
    "Very bad quality"
]

for text in test_texts:
    vector = vectorizer.transform([text])[0]
    pred = model.predict([vector])[0]
    sentiment = "POSITIVE" if pred[1] > pred[0] else "NEGATIVE"
    confidence = round(max(pred) * 100, 1)
    
    print(f"\nText: \"{text}\"")
    print(f"Sentiment: {sentiment} ({confidence}%)")

print("\n" + "=" * 60)
print("✅ Demo complete!")
print("=" * 60)
