import redis
import json
import os
import logging
from dotenv import load_dotenv
from typing import Optional, Dict

from services.nlp_service import preprocess_query

# Load environment variables
load_dotenv()

logger = logging.getLogger(__name__)

QUERY_CACHE_ENABLED = os.getenv("QUERY_CACHE_ENABLED", "true").strip().lower() not in ("false", "0", "no")

REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
REDIS_DB = int(os.getenv("REDIS_DB", 0))
REDIS_EXPIRATION = int(os.getenv("REDIS_EXPIRATION", 3600))
# None when unset, which is what redis-py wants for an unauthenticated
# server - so an environment without a password behaves as it always did.
# REDIS_USERNAME is only needed for a Redis 6+ ACL user; a plain
# `requirepass` server authenticates as "default" with the password alone.
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD") or None
REDIS_USERNAME = os.getenv("REDIS_USERNAME") or None

# v4: keys scoped per company_id (fixes cross-tenant cache leak) — v3 entries
# (unscoped, global across all companies) will expire naturally
# v5 (P1, Oct 26): every v4 answer was written before the HR-only prompt rule,
# the reaction classifier fix and the fallback fix, and some (the HR-pitch
# reply to "no way") were wrong. Bumped so the deploy drops them all at once
# instead of replaying them for the rest of their 30-day TTL.
CACHE_VERSION = "v5"

try:
    r = redis.Redis(
        host=REDIS_HOST,
        port=REDIS_PORT,
        db=REDIS_DB,
        username=REDIS_USERNAME,
        password=REDIS_PASSWORD,
        decode_responses=True,
        socket_connect_timeout=5,
        socket_timeout=5,
        retry_on_timeout=True
    )
    r.ping()
    logger.info("✓ Redis connected successfully")
except Exception as e:
    logger.warning(f"Redis connection failed: {str(e)}. Caching disabled.")
    r = None


def build_cache_key(query: str, company_id: int) -> str:
    return f"{CACHE_VERSION}:hr_query:{company_id}:{preprocess_query(query)}"


def get_cached_query(query: str, company_id: int) -> Optional[Dict]:
    if not QUERY_CACHE_ENABLED:
        return None

    if not r:
        logger.warning("Redis not available, skipping cache")
        return None

    cache_key = build_cache_key(query, company_id)

    try:
        data = r.get(cache_key)

        if data:
            try:
                logger.info(f"⚡ Cache HIT | {cache_key}")
                parsed = json.loads(data)

                #  Ignore failed cache
                if not parsed.get("success"):
                    logger.warning(f"Ignoring failed cache | {cache_key}")
                    return None

                return parsed

            except json.JSONDecodeError:
                logger.warning(f"Corrupted cache → deleting {cache_key}")
                r.delete(cache_key)
                return None

        logger.info(f" Cache MISS | {cache_key}")
        return None

    except Exception as e:
        logger.error(f"Cache GET error: {str(e)}")
        return None


def set_cached_query(query: str, company_id: int, result: Dict, expire: Optional[int] = None) -> bool:
    if not QUERY_CACHE_ENABLED:
        return False

    if not r:
        logger.warning("Redis not available, cannot cache")
        return False

    cache_key = build_cache_key(query, company_id)

    try:
        if not result.get("success"):
            logger.warning(f"⚠ Skipping cache for failed response | {cache_key}")
            return False

        ttl = expire or REDIS_EXPIRATION
        r.set(cache_key, json.dumps(result), ex=ttl)

        logger.info(f"Cache SET | {cache_key} | TTL={ttl}s")
        return True

    except Exception as e:
        logger.error(f"Cache SET error: {str(e)}")
        return False


def clear_cache(pattern: str = "*") -> bool:
    if not r:
        logger.warning("Redis not available, cannot clear cache")
        return False

    try:
        full_pattern = f"{CACHE_VERSION}:{pattern}"
        count = 0

        for key in r.scan_iter(full_pattern):
            r.delete(key)
            count += 1

        logger.info(f"Cleared {count} keys | pattern={full_pattern}")
        return True

    except Exception as e:
        logger.error(f"Cache CLEAR error: {str(e)}")
        return False


def is_redis_alive() -> bool:
    try:
        return r.ping() if r else False
    except Exception:
        return False