# services/log_service.py

import logging
from models.hr_query_log import HRQueryLog

logger = logging.getLogger(__name__)


def store_hr_log(db, user_type, company_id, company_name, role_id, query,
                 intent, response, source, total_time, ai_time, status,
                 *, category=None, true_company_id=None, conversation_id=None,
                 failure_stage=None, provider=None, model=None):
    """One row per turn. The keyword-only group is FR-09's analytics.

    All of them default to None so an existing caller keeps working: a row
    written without them is simply a row from before analytics, which the
    reports treat as such rather than guessing a category for it.

    company_id is the USER id (see models/hr_query_log.py); true_company_id
    is the tenant. Both are stored on purpose.
    """
    try:
        log = HRQueryLog(
            user_type=user_type,
            company_id=company_id,
            company_name=company_name,
            role_id=role_id,
            query=query,
            intent=intent,
            response=response,
            source=source,
            total_time=total_time,
            ai_time=ai_time,
            status=status,
            category=category,
            true_company_id=true_company_id,
            conversation_id=conversation_id,
            failure_stage=failure_stage,
            provider=provider,
            model=model,
        )
        db.add(log)
        db.commit()

    except Exception as e:
        db.rollback()
        logger.error(f"❌ Failed to store HR log: {str(e)}")


def count_recent_turns(db, user_id, intent: str, since) -> int:
    """How many ANSWERED turns (status "success") this USER
    (hr_query_logs.company_id holds the user id) has had with `intent` since
    `since` (naive UTC, like created_at). Refused or failed turns are not
    counted, so a limited user's further attempts do not extend the limit. Used for
    the general-chat allowance (FR-08). Fails OPEN - returns 0 - when the
    count cannot be made: the limit protects the model from load, and a
    database hiccup must not take general chat down with it."""
    try:
        return (db.query(HRQueryLog)
                .filter(HRQueryLog.company_id == user_id,
                        HRQueryLog.intent == intent,
                        HRQueryLog.status == "success",
                        HRQueryLog.created_at >= since)
                .count())
    except Exception as e:
        db.rollback()
        logger.warning("General-chat usage count failed (not limiting): %s", e)
        return 0
