#!/usr/bin/env python3
from __future__ import annotations

import argparse
from pathlib import Path

import torch
from transformers import LogitsProcessorList
from transformers import AutoModelForCausalLM, AutoProcessor

from hotword.hotword_trie import build_trie_from_hotwords, parse_hotwords


PROMPT = "Please transcribe this audio."


def build_conversation(audio_path: Path) -> list[dict]:
    return [
        {
            "role": "user",
            "content": [
                {"type": "audio", "path": str(audio_path)},
                {"type": "text", "text": PROMPT},
            ],
        }
    ]


def make_hotword_processor(tokenizer, hotwords: str, *, topk: int, start_boost: float, continuation_boost: float):
    words = parse_hotwords(hotwords)
    if not words:
        return None
    special_ids = set(int(value) for value in tokenizer.all_special_ids if value is not None)

    def encode(text: str) -> list[int]:
        return tokenizer.encode(text, add_special_tokens=False)

    def id_to_token(token_id: int) -> str:
        return str(tokenizer.convert_ids_to_tokens(int(token_id)))

    trie, _ = build_trie_from_hotwords(
        words,
        encode=encode,
        id_to_token=id_to_token,
        special_ids=special_ids,
        start_boost=start_boost,
        continuation_boost=continuation_boost,
    )
    if not trie:
        return None

    def processor(input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
        vocab_size = int(scores.shape[-1])
        allowed_rows = None
        if int(topk) > 0:
            top_idx = torch.topk(scores.float(), k=min(int(topk), vocab_size), dim=-1).indices
            allowed_rows = [set(int(x) for x in row.tolist()) for row in top_idx]
        for batch_i in range(int(scores.shape[0])):
            boosts = trie.boosts_for_generated(input_ids[batch_i].tolist())
            allowed = allowed_rows[batch_i] if allowed_rows is not None else None
            for token_id, boost in boosts.items():
                if 0 <= int(token_id) < vocab_size and (allowed is None or int(token_id) in allowed):
                    scores[batch_i, int(token_id)] += float(boost)
        return scores

    return processor


def main() -> None:
    parser = argparse.ArgumentParser(description="Transcribe one audio file with optional hotword boosting.")
    parser.add_argument("audio", type=Path)
    parser.add_argument("--model", default=".")
    parser.add_argument("--hotwords", required=True, help="Comma-separated hotwords.")
    parser.add_argument("--hotword_topk", type=int, default=50)
    parser.add_argument("--hotword_start_boost", type=float, default=6.0)
    parser.add_argument("--hotword_continuation_boost", type=float, default=8.0)
    parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
    parser.add_argument("--max_new_tokens", type=int, default=128)
    args = parser.parse_args()

    device = torch.device(args.device)
    dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
    processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True)
    model = AutoModelForCausalLM.from_pretrained(
        args.model,
        trust_remote_code=True,
        torch_dtype=dtype,
        attn_implementation="eager",
    ).to(device)
    model.eval()

    batch = processor.apply_chat_template(
        build_conversation(args.audio),
        return_tensors="pt",
        sampling_rate=16000,
        audio_padding="longest",
        add_generation_prompt=True,
        audio_max_length=30 * 16000,
        text_kwargs={"padding": "longest", "truncation": True, "max_length": 1000},
    )
    batch = {key: value.to(device) if hasattr(value, "to") else value for key, value in dict(batch).items()}
    logits_processor = make_hotword_processor(
        processor.tokenizer,
        args.hotwords,
        topk=args.hotword_topk,
        start_boost=args.hotword_start_boost,
        continuation_boost=args.hotword_continuation_boost,
    )
    with torch.inference_mode():
        output_ids = model.generate(
            **batch,
            max_new_tokens=args.max_new_tokens,
            do_sample=False,
            logits_processor=LogitsProcessorList([logits_processor]) if logits_processor is not None else None,
        )
    prompt_len = int(batch["input_ids"].shape[1])
    text = processor.decode(output_ids[0, prompt_len:], skip_special_tokens=True).strip()
    print(text)


if __name__ == "__main__":
    main()
