# models/hr_query_log.py

from sqlalchemy import Column, Integer, String, Float, JSON, DateTime, Index
from datetime import datetime
from database import Base


class HRQueryLog(Base):
    __tablename__ = "hr_query_logs"
    __table_args__ = (
        # The per-user general-chat allowance (FR-08) counts a user's recent
        # answers by intent on every request - see log_service.count_recent_turns.
        Index("ix_hr_query_logs_user_intent_created", "company_id", "intent", "created_at"),
    )

    id = Column(Integer, primary_key=True, index=True)

    role_id = Column(Integer, nullable=True)
    company_id = Column(Integer, nullable=True)
    user_type = Column(String, nullable=True)
    company_name = Column(String, nullable=True) 

    query = Column(String, nullable=False)
    intent = Column(String, nullable=True)

    response = Column(JSON, nullable=True)

    source = Column(String, nullable=False)

    total_time = Column(Float, nullable=True)
    ai_time = Column(Float, nullable=True)

    log_type = Column(String, default="api")
    status = Column(String, default="success")

    # ── FR-09 analytics ────────────────────────────────────────────────────
    # Added rather than given their own table: this row already holds the
    # prompt and the answer, so a second table would mean two copies of every
    # prompt, two retention obligations and a dual-write that can diverge.
    # The reporting view hr_query_analytics (migration b8c9d0e1f2a3) leaves
    # out query/response, which keeps metrics readable without exposing what
    # people typed.

    #: "general" | "hr_query" | "hrms_action" — see hr_graph.conversation_category.
    #: Written at request time, never derived at report time: the frozensets it
    #: comes from live in application code, so deriving later would silently
    #: recategorise every historical row the next time an intent is added.
    category = Column(String, nullable=True, index=True)

    #: The real TENANT. `company_id` above holds the USER id (main.py:
    #: `company_id = user_payload.get("user_id")`), so grouping by that column
    #: gives per-user rows, not per-company. Both are stored deliberately:
    #: company_id counts active Helix users, true_company_id groups by tenant.
    true_company_id = Column(Integer, nullable=True, index=True)

    #: Lets "conversations" be counted, not just messages.
    conversation_id = Column(String, nullable=True, index=True)

    #: WHICH dependency failed, because `status` is binary. An ERP 401, an LLM
    #: 400 and Redis being down all log as "failure" today, so a dashboard can
    #: say "3% failed" but not whether to call the ERP team or restart Redis.
    failure_stage = Column(String, nullable=True)

    provider = Column(String, nullable=True)   # e.g. "race"
    model = Column(String, nullable=True)      # e.g. "gpt-oss-120b"

    created_at = Column(DateTime, default=datetime.utcnow)