from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
import numpy as np
from rag_chunker import DEFAULT_OUTPUT_PATH, load_chunks
from rag_embed import DEFAULT_EMBEDDINGS_PATH, DEFAULT_INDEX_PATH, load_local_sentence_transformer, tokenizer
DEFAULT_THRESHOLD = 0.3
STOPWORDS = {'what', 'is', 'the', 'of', 'and', 'or', 'to', 'in', 'for', 'does', 'do', 'did', 'are', 'was', 'were', 'an'}

def content_terms(question: str) -> list[str]:
    terms = tokenizer(question)
    if len(terms) > 2:
        filtered = [term for term in terms if term not in STOPWORDS]
        if filtered:
            return filtered
    return terms

def build_query_vector_tfidf(terms: list[str], index_payload: dict[str, Any]) -> np.ndarray:
    tfidf = index_payload.get('tfidf')
    if not tfidf:
        raise RuntimeError('TF-IDF metadata missing from index.')
    vocabulary = {term: index for index, term in enumerate(tfidf['vocabulary'])}
    idf = np.asarray(tfidf['idf'], dtype=np.float32)
    counts: dict[str, int] = {}
    for token in terms:
        counts[token] = counts.get(token, 0) + 1
    vector = np.zeros(len(vocabulary), dtype=np.float32)
    if counts:
        max_tf = max(counts.values())
        for term, tf in counts.items():
            index = vocabulary.get(term)
            if index is None:
                continue
            vector[index] = tf / max_tf * idf[index]
        norm = np.linalg.norm(vector)
        if norm:
            vector /= norm
    return vector

def build_query_vector_st(question: str) -> np.ndarray:
    model, model_name, reason = load_local_sentence_transformer()
    if model is None:
        raise RuntimeError(reason or 'local sentence-transformers model unavailable')
    embedding = model.encode([question], convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=False)[0]
    return embedding.astype(np.float32)

def load_index(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding='utf-8'))

def format_result(rank: int, chunk: dict[str, Any], score: float) -> str:
    metadata = chunk['metadata']
    status = metadata.get('substrate_status_tags') or []
    status_text = ', '.join(status) if status else 'none'
    return '\n'.join([f'[{rank}] similarity={score:.4f}', f"Citation: {metadata['source_path']} :: {metadata['source_section']}", f"Layer tag: {metadata['layer_tag']}", f'Status tags: {status_text}', 'Chunk:', chunk['text']])

def rerank_with_overlap(base_scores: np.ndarray, terms: list[str], chunks: list[dict[str, Any]]) -> np.ndarray:
    if not terms:
        return base_scores
    term_set = set(terms)
    boosted = base_scores.astype(np.float32).copy()
    single_term_query = len(term_set) == 1
    for index, chunk in enumerate(chunks):
        title_tokens = set(tokenizer(chunk['metadata']['source_section']))
        text_tokens = set(tokenizer(chunk['text']))
        title_matches = len(term_set & title_tokens)
        text_matches = len(term_set & text_tokens)
        if single_term_query:
            boosted[index] += 0.1 * min(1, title_matches) + 0.1 * min(1, text_matches)
            continue
        boosted[index] += 0.05 * text_matches + 0.03 * title_matches
        if text_matches >= 2:
            boosted[index] += 0.08
        if title_matches >= 2:
            boosted[index] += 0.04
    return boosted
