import os
from datetime import datetime, timedelta, timezone

import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from database import Base
from models.token_usage_log import TokenUsageLog
from models.quota_policy import QuotaPolicy
import services.quota_service as quota_service


@pytest.fixture
def db():
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine, tables=[TokenUsageLog.__table__, QuotaPolicy.__table__])
    Session = sessionmaker(bind=engine)
    session = Session()
    yield session
    session.close()


def _add_usage(db, user_id, total_tokens, created_at, role_id=1):
    log = TokenUsageLog(
        user_id=user_id, role_id=role_id, provider="deepseek", source="chat",
        total_tokens=total_tokens, created_at=created_at,
    )
    db.add(log)
    db.commit()


def _add_policy(db, scope_type, scope_id, daily=None, weekly=None, monthly=None, is_active=True):
    policy = QuotaPolicy(
        scope_type=scope_type, scope_id=scope_id,
        daily_token_limit=daily, weekly_token_limit=weekly, monthly_token_limit=monthly,
        is_active=is_active,
    )
    db.add(policy)
    db.commit()
    return policy


# ── resolve_policy precedence ──────────────────────────────────────────────

def test_resolve_policy_returns_none_when_no_rows(db):
    assert quota_service.resolve_policy(db, user_id=1, role_id=1) is None


def test_resolve_policy_precedence_user_over_role_over_default(db):
    _add_policy(db, "default", None, daily=1000)
    _add_policy(db, "role", 1, daily=2000)
    _add_policy(db, "user", 42, daily=3000)

    user_policy = quota_service.resolve_policy(db, user_id=42, role_id=1)
    assert user_policy.daily_token_limit == 3000

    role_policy = quota_service.resolve_policy(db, user_id=99, role_id=1)
    assert role_policy.daily_token_limit == 2000

    default_policy = quota_service.resolve_policy(db, user_id=99, role_id=7)
    assert default_policy.daily_token_limit == 1000


def test_resolve_policy_ignores_inactive_rows(db):
    _add_policy(db, "user", 42, daily=3000, is_active=False)
    _add_policy(db, "default", None, daily=1000)

    policy = quota_service.resolve_policy(db, user_id=42, role_id=None)
    assert policy.daily_token_limit == 1000


# ── timezone / period-boundary correctness ───────────────────────────────────

def test_period_boundary_respects_configured_timezone(db, monkeypatch):
    monkeypatch.setenv("QUOTA_TIMEZONE", "Asia/Kolkata")  # UTC+5:30

    # 23:59 local time on day N == 18:29 UTC on day N
    local_tz = quota_service._get_timezone()
    day_n_local = datetime(2026, 6, 10, 23, 59, tzinfo=local_tz)
    day_n_utc = day_n_local.astimezone(timezone.utc)
    _add_usage(db, user_id=1, total_tokens=500, created_at=day_n_utc)

    # "Now" is just past midnight local on day N+1
    now_day_n_plus_1_local = datetime(2026, 6, 11, 0, 5, tzinfo=local_tz)
    now_utc_equivalent = now_day_n_plus_1_local.astimezone(timezone.utc)

    # usage_in_window uses datetime.now() internally, so simulate "now" by
    # monkeypatching the module's datetime via the start boundary directly:
    start_utc = quota_service._period_start(now_day_n_plus_1_local, "daily").astimezone(timezone.utc)
    assert start_utc > day_n_utc  # day N's row must fall BEFORE day N+1's start

    total_after_boundary = db.query(TokenUsageLog).filter(
        TokenUsageLog.user_id == 1, TokenUsageLog.created_at >= start_utc
    ).count()
    assert total_after_boundary == 0


def test_usage_in_window_sums_only_current_period(db, monkeypatch):
    monkeypatch.setenv("QUOTA_TIMEZONE", "UTC")
    # Fixed, mid-month reference point — real datetime.now() would make the
    # "2 days ago" fixture below cross into the previous calendar month
    # whenever this test happens to run in the first two days of a month,
    # silently dropping it out of the monthly window and failing this test
    # for a reason that has nothing to do with the code under test.
    # quota_service.py does `from datetime import datetime`, so its own
    # datetime.now() call is patchable via this module attribute.
    fixed_now = datetime(2026, 6, 15, 12, 0, tzinfo=timezone.utc)

    class _FixedDatetime(datetime):
        @classmethod
        def now(cls, tz=None):
            return fixed_now.astimezone(tz) if tz else fixed_now

    monkeypatch.setattr(quota_service, "datetime", _FixedDatetime)

    _add_usage(db, user_id=1, total_tokens=100, created_at=fixed_now)
    _add_usage(db, user_id=1, total_tokens=200, created_at=fixed_now - timedelta(days=2))  # outside daily window

    assert quota_service.usage_in_window(db, user_id=1, period="daily") == 100
    assert quota_service.usage_in_window(db, user_id=1, period="monthly") == 300


# ── check_quota thresholds ───────────────────────────────────────────────────

def test_check_quota_unlimited_when_no_policy(db):
    result = quota_service.check_quota(db, user_id=1, role_id=1)
    assert result == {"allowed": True, "breaches": [], "warnings": [], "policy_source": "unlimited"}


def test_check_quota_warns_at_80_percent(db, monkeypatch):
    monkeypatch.setenv("QUOTA_TIMEZONE", "UTC")
    _add_policy(db, "user", 1, daily=1000)
    _add_usage(db, user_id=1, total_tokens=850, created_at=datetime.now(timezone.utc))

    result = quota_service.check_quota(db, user_id=1, role_id=None)
    assert result["allowed"] is True
    assert len(result["warnings"]) == 1
    assert result["warnings"][0]["period"] == "daily"
    assert result["breaches"] == []


def test_check_quota_blocks_at_100_percent(db, monkeypatch):
    monkeypatch.setenv("QUOTA_TIMEZONE", "UTC")
    _add_policy(db, "user", 1, daily=1000)
    _add_usage(db, user_id=1, total_tokens=1000, created_at=datetime.now(timezone.utc))

    result = quota_service.check_quota(db, user_id=1, role_id=None)
    assert result["allowed"] is False
    assert len(result["breaches"]) == 1
    assert result["breaches"][0]["period"] == "daily"


def test_check_quota_allows_when_under_limit(db, monkeypatch):
    monkeypatch.setenv("QUOTA_TIMEZONE", "UTC")
    _add_policy(db, "user", 1, daily=1000)
    _add_usage(db, user_id=1, total_tokens=500, created_at=datetime.now(timezone.utc))

    result = quota_service.check_quota(db, user_id=1, role_id=None)
    assert result["allowed"] is True
    assert result["breaches"] == []
    assert result["warnings"] == []


# ── record_usage ──────────────────────────────────────────────────────────

def test_record_usage_inserts_row(db):
    quota_service.record_usage(
        db, user_id=1, company_id=99, role_id=1, conversation_id=None,
        provider="openai", model="gpt-4o-mini", source="intent",
        prompt_tokens=10, completion_tokens=5, total_tokens=15, is_estimated=False,
    )
    rows = db.query(TokenUsageLog).all()
    assert len(rows) == 1
    assert rows[0].total_tokens == 15
    assert rows[0].source == "intent"
