import math
import random
import re
from collections import Counter, defaultdict

import evaluate
import gensim
import nltk
import numpy as np
import spacy
import torch
from gensim.models import Word2Vec
from nltk.corpus import wordnet as wn
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk.wsd import lesk
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from torch.utils.data import DataLoader, Dataset
from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    pipeline,
)

# Download required NLTK assets
for res in ["punkt", "punkt_tab", "averaged_perceptron_tagger", "averaged_perceptron_tagger_eng", "wordnet", "omw-1.4"]:
    try:
        nltk.download(res, quiet=True)
    except Exception:
        pass


# ==============================================================================
# (a) PREPROCESSING + BIGRAM LM
# ==============================================================================
print("\n" + "=" * 50 + "\n--- TASK (a): Preprocessing + Bigram LM ---\n" + "=" * 50)

SAMPLE_TEXT = (
    "Check this out at https://example.com/item! I didn't think it'd work :) "
    "but the display's quality is stunning. Don't buy the cheap version :("
)

# 1. Normalization & Tokenization
CONTRACTIONS = {
    r"\bdidn't\b": "did not",
    r"\bdon't\b": "do not",
    r"\bit'd\b": "it would",
    r"\bdisplay's\b": "display is",
}

def clean_and_tokenize(text):
    text = text.lower()
    text = re.sub(r"https?://\S+|www\.\S+", "", text)
    for pattern, repl in CONTRACTIONS.items():
        text = re.sub(pattern, repl, text)
    text = text.replace(":)", "<happy>").replace(":(", "<sad>")
    # Retain standard words, tags (<happy>, <sad>), and punctuation
    tokens = re.findall(r"<[^>]+>|\b\w+\b|[^\w\s]", text)
    return tokens

tokens = clean_and_tokenize(SAMPLE_TEXT)
print(f"Tokens: {tokens[:12]}...")

# 2. Porter Stemming vs WordNet Lemmatization
stemmer = PorterStemmer()
lemmatizer = WordNetLemmatizer()
sample_words = ["running", "display's", "stunning", "better", "worked"]
for w in sample_words:
    print(f"Word: {w:<10} | Stem: {stemmer.stem(w):<10} | Lemma: {lemmatizer.lemmatize(w, pos='v')}")

# 3. Bigram LM with Add-1 (Laplace) Smoothing
corpus = [
    clean_and_tokenize("the display is stunning and clear"),
    clean_and_tokenize("the screen is bright but the battery is bad"),
    clean_and_tokenize("i do not like the display quality <sad>"),
    clean_and_tokenize("the design is clean and good <happy>"),
]

class BigramLM:
    def __init__(self, tokenized_sentences):
        self.unigrams = Counter()
        self.bigrams = Counter()
        self.vocab = set()

        for sent in tokenized_sentences:
            padded = ["<s>"] + sent + ["</s>"]
            for w in padded:
                self.unigrams[w] += 1
                self.vocab.add(w)
            for w1, w2 in zip(padded[:-1], padded[1:]):
                self.bigrams[(w1, w2)] += 1

        self.V = len(self.vocab)

    def probability(self, w1, w2):
        # Laplace smoothing: (C(w1, w2) + 1) / (C(w1) + |V|)
        num = self.bigrams[(w1, w2)] + 1
        denom = self.unigrams[w1] + self.V
        return num / denom

    def sentence_probability(self, sent):
        padded = ["<s>"] + sent + ["</s>"]
        prob = 1.0
        for w1, w2 in zip(padded[:-1], padded[1:]):
            prob *= self.probability(w1, w2)
        return prob

    def perplexity(self, sent):
        padded = ["<s>"] + sent + ["</s>"]
        N = len(padded) - 1
        log_prob_sum = 0.0
        for w1, w2 in zip(padded[:-1], padded[1:]):
            log_prob_sum += math.log(self.probability(w1, w2))
        return math.exp(-log_prob_sum / N)

    def sample(self, max_len=15, seed=42):
        random.seed(seed)
        word_list = list(self.vocab - {"<s>"})
        curr_word = "<s>"
        generated = []

        for _ in range(max_len):
            probs = [self.probability(curr_word, w) for w in word_list]
            total_p = sum(probs)
            probs = [p / total_p for p in probs]
            curr_word = random.choices(word_list, weights=probs, k=1)[0]
            if curr_word == "</s>":
                break
            generated.append(curr_word)
        return " ".join(generated)

lm = BigramLM(corpus)
test_sent = clean_and_tokenize("the display is clear")
print(f"P('the display is clear'): {lm.sentence_probability(test_sent):.8e}")
print(f"Perplexity: {lm.perplexity(test_sent):.4f}")
print(f"Sampled generation (seed=42): {lm.sample(seed=42)}")


# ==============================================================================
# (b) POS + PARSING
# ==============================================================================
print("\n" + "=" * 50 + "\n--- TASK (b): POS + Parsing ---\n" + "=" * 50)

# 1. NLTK POS Tagging & Open vs Closed Class Classification
OPEN_TAGS = {"NN", "NNS", "NNP", "NNPS", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ", "JJ", "JJR", "JJS", "RB", "RBR", "RBS"}
CLOSED_TAGS = {"DT", "IN", "PRP", "PRP$", "CC", "MD", "TO", "WDT", "WP", "WP$", "WRB"}

test_pos_sent = "The technician inspected the laptop with the magnifier ."
tagged = nltk.pos_tag(test_pos_sent.split())

open_words = [w for w, tag in tagged if tag in OPEN_TAGS]
closed_words = [w for w, tag in tagged if tag in CLOSED_TAGS]
print(f"Tagged: {tagged}")
print(f"Open-class words:   {open_words}")
print(f"Closed-class words: {closed_words}")

# 2. CFG + ChartParser (PP-attachment Ambiguity: 2 Parse Trees)
cfg_grammar = nltk.CFG.fromstring("""
    S -> NP VP
    PP -> P NP
    NP -> Det N | NP PP
    VP -> V NP | VP PP
    Det -> 'The' | 'the'
    N -> 'technician' | 'laptop' | 'magnifier'
    V -> 'inspected'
    P -> 'with'
""")

chart_parser = nltk.ChartParser(cfg_grammar)
parse_tokens = "The technician inspected the laptop with the magnifier".split()
trees = list(chart_parser.parse(parse_tokens))
print(f"\nGenerated {len(trees)} trees for PP-attachment sentence:")
for i, t in enumerate(trees, 1):
    print(f"Tree {i}:\n{t}")

# 3. spaCy Aspect-Opinion Extraction (amod and nsubj + acomp)
nlp = spacy.load("en_core_web_sm")
doc = nlp("The bright screen is impressive, and the keyboard feels great.")

aspect_opinions = []
for token in doc:
    # amod: Adjective modifier modifying a noun aspect (e.g., 'bright screen')
    if token.dep_ == "amod" and token.head.pos_ in ("NOUN", "PROPN"):
        aspect_opinions.append((token.head.text, token.text, "amod"))
    # nsubj + acomp: Predicative adjective linked via copula/verb (e.g., 'screen is impressive')
    if token.dep_ == "nsubj" and token.pos_ in ("NOUN", "PROPN"):
        verb = token.head
        for child in verb.children:
            if child.dep_ in ("acomp", "attr") and child.pos_ == "ADJ":
                aspect_opinions.append((token.text, child.text, f"{token.dep_}+{child.dep_}"))

print(f"\nAspect-Opinion Pairs: {aspect_opinions}")


# ==============================================================================
# (c) SEMANTICS
# ==============================================================================
print("\n" + "=" * 50 + "\n--- TASK (c): Semantics ---\n" + "=" * 50)

# 1. WordNet: Synsets, Wu-Palmer, Lesk WSD
syn1 = wn.synset("laptop.n.01")
syn2 = wn.synset("computer.n.01")
print(f"Synset 1: {syn1.name()} | Def: {syn1.definition()}")
print(f"Synset 2: {syn2.name()} | Def: {syn2.definition()}")
print(f"Wu-Palmer Similarity: {syn1.wup_similarity(syn2):.4f}")

lesk_sent = "I deposited all my money in the bank vault"
disambiguated = lesk(nltk.word_tokenize(lesk_sent), "bank", pos="n")
print(f"Lesk Disambiguated Sense for 'bank': {disambiguated.name()} -> {disambiguated.definition()}")

# 2. TF-IDF + Cosine Similarity Top-k Retrieval
docs = [
    "High performance laptop with clear display and long battery",
    "Affordable smartphone with bright screen and dual camera",
    "Running shoes for outdoor marathon training and sports",
    "Premium noise cancelling headphones with deep bass",
]
query = ["laptop with battery life"]
vectorizer = TfidfVectorizer()
doc_tfidf = vectorizer.fit_transform(docs)
q_tfidf = vectorizer.transform(query)
cos_sims = cosine_similarity(q_tfidf, doc_tfidf).flatten()
top_indices = cos_sims.argsort()[::-1][:2]
print(f"\nTop-2 Retrieval for query '{query[0]}':")
for idx in top_indices:
    print(f"  Score: {cos_sims[idx]:.4f} | Doc: {docs[idx]}")

# 3. Positive Pointwise Mutual Information (PPMI, window +-2)
toy_tokens = ["the", "battery", "is", "good", "and", "the", "battery", "charges", "fast"]
vocab_ppmi = sorted(list(set(toy_tokens)))
w2i = {w: i for i, w in enumerate(vocab_ppmi)}
V_size = len(vocab_ppmi)
cooc = np.zeros((V_size, V_size))
w_counts = Counter(toy_tokens)
window = 2

for i, w in enumerate(toy_tokens):
    left = max(0, i - window)
    right = min(len(toy_tokens), i + window + 1)
    for j in range(left, right):
        if i != j:
            cooc[w2i[w]][w2i[toy_tokens[j]]] += 1

total_cooc = np.sum(cooc)
ppmi_matrix = np.zeros((V_size, V_size))
for u in range(V_size):
    for v in range(V_size):
        if cooc[u, v] > 0:
            p_uv = cooc[u, v] / total_cooc
            p_u = sum(cooc[u, :]) / total_cooc
            p_v = sum(cooc[:, v]) / total_cooc
            pmi = math.log2(p_uv / (p_u * p_v))
            ppmi_matrix[u, v] = max(0.0, pmi)

u_idx, v_idx = w2i["battery"], w2i["good"]
print(f"\nPPMI('battery', 'good'): {ppmi_matrix[u_idx, v_idx]:.4f}")

# 4. Word2Vec Skip-Gram (Reproducible)
tokenized_w2v_corpus = [d.lower().split() for d in docs]
w2v_model = Word2Vec(
    sentences=tokenized_w2v_corpus,
    vector_size=20,
    window=2,
    sg=1,       # Skip-gram
    seed=42,
    workers=1,  # Single-threaded execution guarantees deterministic output
    min_count=1
)
print(f"Word2Vec embedding shape for 'laptop': {w2v_model.wv['laptop'].shape}")


# ==============================================================================
# (d) COREFERENCE
# ==============================================================================
print("\n" + "=" * 50 + "\n--- TASK (d): Coreference ---\n" + "=" * 50)

coref_text = (
    "Mr. John bought a laptop from the market. "
    "He inspected the laptop thoroughly. "
    "Mrs. Smith arrived later, and she praised John."
)

cdoc = nlp(coref_text)

# 1. Mention Extraction
mentions = []
for ent in cdoc.ents:
    mentions.append((ent.start_char, ent.end_char, ent.text, ent.root, "ENT"))
for chunk in cdoc.noun_chunks:
    if not any(m[0] == chunk.start_char and m[1] == chunk.end_char for m in mentions):
        mentions.append((chunk.start_char, chunk.end_char, chunk.text, chunk.root, "NP"))
for tok in cdoc:
    if tok.pos_ == "PRON":
        mentions.append((tok.idx, tok.idx + len(tok.text), tok.text, tok, "PRON"))

mentions = sorted(mentions, key=lambda x: x[0])

# 2. Rule-Based Pairwise Scoring & Chain Resolution
GENDER_MAP = {
    "john": "M", "mr.": "M", "he": "M", "him": "M", "his": "M",
    "smith": "F", "mrs.": "F", "she": "F", "her": "F", "hers": "F",
    "laptop": "NEUT", "market": "NEUT", "it": "NEUT"
}

def infer_gender(text):
    text_lower = text.lower()
    for k, v in GENDER_MAP.items():
        if k in text_lower:
            return v
    return "UNKNOWN"

def score_mention_pair(antecedent, anaphor):
    _, _, ante_text, ante_root, _ = antecedent
    _, _, ana_text, ana_root, _ = anaphor

    # Distance penalty
    sent_dist = abs(ana_root.sent.start - ante_root.sent.start)
    score = -0.5 * sent_dist

    # Exact head match
    if ante_root.lemma_.lower() == ana_root.lemma_.lower():
        score += 3.0

    # Gender agreement check
    g_ante = infer_gender(ante_text)
    g_ana = infer_gender(ana_text)
    if g_ante != "UNKNOWN" and g_ana != "UNKNOWN":
        if g_ante == g_ana:
            score += 2.0
        else:
            return -999.0  # Veto

    return score

# Build chains
chains = []
for i, ana in enumerate(mentions):
    best_candidate = None
    best_score = 0.5  # Positive acceptance threshold
    for j in range(i):
        ante = mentions[j]
        s = score_mention_pair(ante, ana)
        if s > best_score:
            best_score = s
            best_candidate = j

    if best_candidate is not None:
        placed = False
        for chain in chains:
            if best_candidate in chain:
                chain.append(i)
                placed = True
                break
        if not placed:
            chains.append([best_candidate, i])

print("Resolved Coreference Chains:")
for c_idx, chain in enumerate(chains, 1):
    chain_texts = [mentions[idx][2] for idx in chain]
    print(f" Chain {c_idx}: {' -> '.join(chain_texts)}")


# ==============================================================================
# (e) BERT PIPELINES & 9-SAMPLE FINE-TUNING
# ==============================================================================
print("\n" + "=" * 50 + "\n--- TASK (e): BERT Pipelines & Fine-Tuning ---\n" + "=" * 50)

# 1. Off-the-shelf Pipelines
unmasker = pipeline("fill-mask", model="bert-base-uncased")
mask_res = unmasker("The laptop has an amazing [MASK] quality.")
print(f"Fill-Mask Top Prediction: {mask_res[0]['token_str']} (Score: {mask_res[0]['score']:.4f})")

classifier_pipe = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
pipe_res = classifier_pipe("The screen brightness is superb!")
print(f"Sentiment Pipeline: {pipe_res[0]}")

# 2. 9-Sample Fine-Tuning Setup
train_texts = [
    "This laptop is exceptionally good",        # 1 (pos)
    "Absolutely terrible purchase, broken",      # 0 (neg)
    "Great battery life and clear screen",       # 1 (pos)
    "Poor performance and laggy interface",      # 0 (neg)
    "Love the keyboard and the speed",           # 1 (pos)
    "Do not buy, absolute waste of money",       # 0 (neg)
    "Extremely satisfied with the build",        # 1 (pos)
    "The charger failed within two days",        # 0 (neg)
    "Flawless product, highly recommend it",     # 1 (pos)
]
train_labels = [1, 0, 1, 0, 1, 0, 1, 0, 1]

eval_texts = [
    "Wonderful hardware, very pleased",          # 1
    "Defective unit, completely useless",        # 0
]
eval_labels = [1, 0]

MODEL_NAME = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=2)

class MicroDataset(Dataset):
    def __init__(self, texts, labels):
        self.encodings = tokenizer(texts, padding=True, truncation=True, max_length=32, return_tensors="pt")
        self.labels = torch.tensor(labels, dtype=torch.long)

    def __getitem__(self, idx):
        item = {k: v[idx] for k, v in self.encodings.items()}
        item["labels"] = self.labels[idx]
        return item

    def __len__(self):
        return len(self.labels)

train_loader = DataLoader(MicroDataset(train_texts, train_labels), batch_size=3, shuffle=True)
eval_loader = DataLoader(MicroDataset(eval_texts, eval_labels), batch_size=2)

# Training loop
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

model.train()
for epoch in range(3):
    total_loss = 0
    for batch in train_loader:
        optimizer.zero_grad()
        input_ids = batch["input_ids"].to(device)
        attention_mask = batch["attention_mask"].to(device)
        labels = batch["labels"].to(device)

        outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
        loss = outputs.loss
        loss.backward()
        optimizer.step()
        total_loss += loss.item()
    print(f"Epoch {epoch+1}/3 Loss: {total_loss / len(train_loader):.4f}")

# Evaluation (Accuracy & F1)
model.eval()
acc_metric = evaluate.load("accuracy")
f1_metric = evaluate.load("f1")

all_preds, all_refs = [], []
with torch.no_grad():
    for batch in eval_loader:
        input_ids = batch["input_ids"].to(device)
        attention_mask = batch["attention_mask"].to(device)
        logits = model(input_ids=input_ids, attention_mask=attention_mask).logits
        preds = torch.argmax(logits, dim=-1)
        all_preds.extend(preds.cpu().numpy())
        all_refs.extend(batch["labels"].cpu().numpy())

print(f"\nEvaluation Accuracy: {acc_metric.compute(predictions=all_preds, references=all_refs)['accuracy']:.4f}")
print(f"Evaluation F1-Score: {f1_metric.compute(predictions=all_preds, references=all_refs)['f1']:.4f}")

# Inference on unseen text
new_text = "The system is fast and quiet."
inputs = tokenizer(new_text, return_tensors="pt").to(device)
with torch.no_grad():
    pred_idx = torch.argmax(model(**inputs).logits, dim=-1).item()
label_map = {0: "NEGATIVE", 1: "POSITIVE"}
print(f"Inference on '{new_text}': {label_map[pred_idx]}")