from __future__ import annotations
import argparse
import importlib.util
import json
import math
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import numpy as np
from rag_chunker import DEFAULT_OUTPUT_PATH, load_chunks
DEFAULT_EMBEDDINGS_PATH = Path('embeddings.npy')
DEFAULT_INDEX_PATH = Path('index.json')
MODEL_CANDIDATES = ['sentence-transformers/all-MiniLM-L6-v2', 'all-MiniLM-L6-v2', 'sentence-transformers/all-MiniLM-L12-v2', 'all-MiniLM-L12-v2', 'sentence-transformers/paraphrase-MiniLM-L3-v2', 'paraphrase-MiniLM-L3-v2', 'sentence-transformers/multi-qa-MiniLM-L6-cos-v1', 'multi-qa-MiniLM-L6-cos-v1']

def tokenizer(text: str) -> list[str]:
    import re
    return re.findall('[\\w]+(?:[./-][\\w]+)*', text.lower(), flags=re.UNICODE)

def l2_normalize(matrix: np.ndarray) -> np.ndarray:
    norms = np.linalg.norm(matrix, axis=1, keepdims=True)
    norms[norms == 0] = 1.0
    return matrix / norms

def build_tfidf_matrix(texts: list[str]) -> tuple[np.ndarray, dict[str, int], np.ndarray]:
    doc_counts: list[Counter[str]] = []
    doc_frequency: Counter[str] = Counter()
    for text in texts:
        counts = Counter(tokenizer(text))
        doc_counts.append(counts)
        doc_frequency.update(counts.keys())
    vocabulary = {term: index for index, term in enumerate(sorted(doc_frequency))}
    n_docs = len(texts)
    idf = np.zeros(len(vocabulary), dtype=np.float32)
    for term, index in vocabulary.items():
        idf[index] = math.log((1.0 + n_docs) / (1.0 + doc_frequency[term])) + 1.0
    matrix = np.zeros((n_docs, len(vocabulary)), dtype=np.float32)
    for row, counts in enumerate(doc_counts):
        if not counts:
            continue
        max_tf = max(counts.values())
        for term, tf in counts.items():
            col = vocabulary[term]
            matrix[row, col] = tf / max_tf * idf[col]
    matrix = l2_normalize(matrix)
    return (matrix, vocabulary, idf)

def sentence_transformers_available() -> bool:
    return importlib.util.find_spec('sentence_transformers') is not None

def load_local_sentence_transformer() -> tuple[Any | None, str | None, str | None]:
    if not sentence_transformers_available():
        return (None, None, 'package not installed')
    from sentence_transformers import SentenceTransformer
    errors: list[str] = []
    for candidate in MODEL_CANDIDATES:
        try:
            model = SentenceTransformer(candidate, local_files_only=True)
            return (model, candidate, None)
        except Exception as exc:
            errors.append(f'{candidate}: {exc}')
    reason = 'no local sentence-transformers model found'
    if errors:
        reason = f"{reason}; attempts: {' | '.join(errors)}"
    return (None, None, reason)

def embed_with_sentence_transformers(texts: list[str]) -> tuple[np.ndarray, str]:
    model, model_name, reason = load_local_sentence_transformer()
    if model is None or model_name is None:
        raise RuntimeError(reason or 'failed to load local sentence-transformers model')
    embeddings = model.encode(texts, convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=False)
    return (embeddings.astype(np.float32), model_name)

def build_index_payload(chunks: list[dict[str, Any]], embeddings_path: Path, chunks_path: Path, backend: str, model_name: str | None, notes: list[str], tfidf_vocabulary: dict[str, int] | None=None, tfidf_idf: np.ndarray | None=None) -> dict[str, Any]:
    payload: dict[str, Any] = {'created_at_utc': datetime.now(timezone.utc).isoformat(), 'backend': backend, 'model_name': model_name, 'chunks_path': str(chunks_path), 'embeddings_path': str(embeddings_path), 'vector_shape': None, 'chunk_ids': [chunk['id'] for chunk in chunks], 'rows': [{'row': row, 'id': chunk['id'], 'source_path': chunk['metadata']['source_path'], 'source_section': chunk['metadata']['source_section'], 'citation_target': chunk['metadata']['citation_target'], 'layer_tag': chunk['metadata']['layer_tag'], 'substrate_status_tags': chunk['metadata']['substrate_status_tags']} for row, chunk in enumerate(chunks)], 'notes': notes}
    if tfidf_vocabulary is not None and tfidf_idf is not None:
        ordered_vocab = [None] * len(tfidf_vocabulary)
        for term, index in tfidf_vocabulary.items():
            ordered_vocab[index] = term
        payload['tfidf'] = {'vocabulary': ordered_vocab, 'idf': [float(value) for value in tfidf_idf.tolist()], 'term_weighting': 'tf / max_tf * idf, L2-normalized'}
    return payload
