# 1. Install required libraries (run once in your terminal)
# pip install gensim scikit-learn numpy

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Optional: download a small pre-trained embedding model (25 dimensions, fast)
import gensim.downloader as api
print("Downloading small GloVe model (25d) - this happens once...")
embedding_model = api.load("glove-twitter-25")  # ~ 50 MB download

# If you have no internet, you can skip the download and use random embeddings:
# from gensim.test.utils import datapath, get_tmpfile
# from gensim.models import KeyedVectors
# embedding_model = KeyedVectors(25)  # empty, would need custom vectors

# 2. Helper: convert sentence to average embedding (simple weighting)
def sentence_embedding(sentence, model, weight_probabilities=None):
    """
    sentence: string
    model: gensim KeyedVectors
    weight_probabilities: optional list of floats same length as words
    Returns a fixed-length vector (average of word vectors).
    """
    words = sentence.lower().split()
    vectors = []
    for i, w in enumerate(words):
        if w in model:
            vec = model[w]
            # if probabilities given, scale vector by that weight
            if weight_probabilities and i < len(weight_probabilities):
                vec = vec * weight_probabilities[i]
            vectors.append(vec)
    if not vectors:
        return np.zeros(model.vector_size)
    return np.mean(vectors, axis=0)

# 3. Create a tiny dataset
sentences = [
    "hello how are you",
    "hey good morning",
    "what time is it",
    "can you tell me the current hour",
    "light the torch",
    "turn on the flashlight"
]
# Labels: 0 = greeting, 1 = time question, 2 = command
labels = [0, 0, 1, 1, 2, 2]

# Convert sentences to embedding vectors (using simple average)
X = np.array([sentence_embedding(s, embedding_model) for s in sentences])
y = np.array(labels)

# 4. Train a prediction model (logistic regression)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
clf = LogisticRegression(max_iter=1000)
clf.fit(X_train, y_train)

# 5. Test predictions
y_pred = clf.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}")

# 6. Example of "intelligent but hardcoded parser" using prediction
def parse_with_prediction(user_input):
    # Hardcoded step 1: compute embedding (with potential probability weighting)
    # Here, we naively give each word equal weight (1.0)
    emb = sentence_embedding(user_input, embedding_model)
    # Hardcoded step 2: predict class
    pred_class = clf.predict([emb])[0]
    # Hardcoded step 3: act based on prediction
    if pred_class == 0:
        return "🤖 Parser: Greeting detected – responding with 'Hello!'"
    elif pred_class == 1:
        return "🕒 Parser: Time question – answering 'It's 12:34' (hardcoded reply)"
    else:
        return "🔥 Parser: Command detected – executing light/flashlight action"

# Demo
test_inputs = [
    "hi there nice to see you",
    "what's the current time",
    "please ignite the candle"
]
for inp in test_inputs:
    print(f"User: '{inp}'")
    print(parse_with_prediction(inp))
    print()