import logging
import sqlite3

from google import genai
from google.genai import types

from app.config import GEMINI_API_KEY, GEMINI_MODEL
from app.content.fact_check import verify_fact
from app.content.prompts import FactContent, build_prompt
from app.dedup.store import find_duplicate, get_recent_facts

logger = logging.getLogger(__name__)

_client = genai.Client(api_key=GEMINI_API_KEY)

MAX_GENERATION_ATTEMPTS = 5


def _call_gemini(category_display_name: str, avoid_facts: list[str]) -> FactContent:
    prompt = build_prompt(category_display_name, avoid_facts)
    response = _client.models.generate_content(
        model=GEMINI_MODEL,
        contents=prompt,
        config=types.GenerateContentConfig(
            response_mime_type="application/json",
            response_schema=FactContent,
            temperature=1.0,
        ),
    )
    return FactContent.model_validate_json(response.text)


def generate_unique_fact(
    conn: sqlite3.Connection,
    category_slug: str,
    category_display_name: str,
) -> FactContent | None:
    avoid_facts = get_recent_facts(conn, category_slug)

    for attempt in range(1, MAX_GENERATION_ATTEMPTS + 1):
        content = _call_gemini(category_display_name, avoid_facts)

        duplicate = find_duplicate(conn, category_slug, content.fact)
        if duplicate is not None:
            logger.warning(
                "Duplicate/near-duplicate fact rejected for %s (attempt %d/%d): %r ~ %r",
                category_slug, attempt, MAX_GENERATION_ATTEMPTS, content.fact, duplicate,
            )
            avoid_facts.append(content.fact)
            continue

        is_valid, reason = verify_fact(content.fact)
        if not is_valid:
            logger.warning(
                "Fact failed Wikipedia verification for %s (attempt %d/%d): %r (reason: %s)",
                category_slug, attempt, MAX_GENERATION_ATTEMPTS, content.fact, reason,
            )
            avoid_facts.append(content.fact)
            continue

        return content

    logger.error("Failed to generate a verified unique fact for %s after %d attempts", category_slug, MAX_GENERATION_ATTEMPTS)
    return None
