# Naive Bayes for sentiment classification (Assignment 4)
from collections import Counter
import numpy as np


def train_nb(documents, labels, alpha=1.0):
    """Estimate the Naive Bayes model from training documents.

    alpha is the smoothing constant (add-alpha smoothing, alpha=1 is Laplace).
    Returns a dictionary with everything needed to classify new documents.
    """
    classes = sorted(set(labels))
    doc_counts = Counter(labels)

    # how often each word appears in the documents of each class
    word_counts = {c: Counter() for c in classes}
    for doc, label in zip(documents, labels):
        word_counts[label].update(doc)

    # vocabulary = every word seen in the training set
    vocab = set()
    for c in classes:
        vocab.update(word_counts[c])
    V = len(vocab)

    n_docs = len(labels)
    log_prior = {}
    log_prob = {}
    for c in classes:
        log_prior[c] = np.log(doc_counts[c] / n_docs)
        total_words = sum(word_counts[c].values())
        denom = total_words + alpha * V
        log_prob[c] = {w: np.log((word_counts[c][w] + alpha) / denom)
                       for w in vocab}

    return {'classes': classes, 'vocab': vocab,
            'log_prior': log_prior, 'log_prob': log_prob}


def score_doc_label(document, label, model):
    """log P(label) + sum of log P(word | label) over the words in the document.
    Words that were not in the training vocabulary are skipped."""
    score = model['log_prior'][label]
    for w in document:
        if w in model['vocab']:
            score += model['log_prob'][label][w]
    return score


def classify_nb(document, model):
    """Return the label with the highest score."""
    best_label = None
    best_score = None
    for c in model['classes']:
        s = score_doc_label(document, c, model)
        if best_score is None or s > best_score:
            best_label = c
            best_score = s
    return best_label


def classify_documents(docs, model):
    return [classify_nb(d, model) for d in docs]


def accuracy(true_labels, guessed_labels):
    correct = sum(1 for t, g in zip(true_labels, guessed_labels) if t == g)
    return correct / len(true_labels)
