"""
Unit Tests for Poe2VisualTool Commercial License Engine
Kiểm thử mã hóa, chữ ký số HMAC, thời hạn, khóa theo HWID và lưu trữ license.dat.
"""

import time
from pathlib import Path
import pytest
from src.commercial.license_manager import LicenseManager, LicenseTier


@pytest.fixture
def mock_hwid():
    return "PVT-A1B2-C3D4-E5F6-7890"


@pytest.fixture
def other_hwid():
    return "PVT-FFFF-EEEE-DDDD-CCCC"


def test_lifetime_key_validation(mock_hwid, tmp_path: Path):
    """Kiểm tra sinh và xác thực License Vĩnh Viễn (LIFETIME)."""
    lm = LicenseManager(license_file_path=tmp_path / "license.dat", custom_hwid=mock_hwid)
    key = LicenseManager.generate_product_key(mock_hwid, LicenseTier.LIFETIME)

    assert key.startswith("PVTK-L")
    valid, tier, exp, msg = lm.verify_product_key(key)
    assert valid is True
    assert tier == LicenseTier.LIFETIME
    assert exp == 0

    # Lưu và tải lại từ file
    assert lm.save_license(key) is True
    info = lm.load_license()
    assert info.is_valid is True
    assert info.tier == LicenseTier.LIFETIME
    assert info.days_left == 99999
    assert info.expires_at is None


def test_subscription_key_validation(mock_hwid, tmp_path: Path):
    """Kiểm tra License thuê bao có thời hạn (SUBSCRIPTION 30 ngày)."""
    lm = LicenseManager(license_file_path=tmp_path / "license.dat", custom_hwid=mock_hwid)
    key = LicenseManager.generate_product_key(mock_hwid, LicenseTier.SUBSCRIPTION, duration_days=30)

    assert key.startswith("PVTK-S")
    valid, tier, exp, msg = lm.verify_product_key(key)
    assert valid is True
    assert tier == LicenseTier.SUBSCRIPTION
    assert exp > int(time.time())

    # Lưu và thẩm định
    assert lm.save_license(key) is True
    info = lm.load_license()
    assert info.is_valid is True
    assert info.tier == LicenseTier.SUBSCRIPTION
    assert 29 <= info.days_left <= 30
    assert info.expires_at is not None


def test_wrong_hwid_rejected(mock_hwid, other_hwid, tmp_path: Path):
    """Kiểm tra key sinh cho máy A bị từ chối trên máy B."""
    key_for_b = LicenseManager.generate_product_key(other_hwid, LicenseTier.LIFETIME)
    lm_a = LicenseManager(license_file_path=tmp_path / "license.dat", custom_hwid=mock_hwid)

    valid, tier, exp, msg = lm_a.verify_product_key(key_for_b)
    assert valid is False
    assert "HWID khác biệt" in msg


def test_tampered_key_rejected(mock_hwid, tmp_path: Path):
    """Kiểm tra nếu người dùng tự ý sửa dù chỉ 1 ký tự thì chữ ký số bị từ chối ngay."""
    key = LicenseManager.generate_product_key(mock_hwid, LicenseTier.LIFETIME)
    # Đổi ký tự cuối
    last_char = key[-1]
    tampered_char = "0" if last_char != "0" else "1"
    tampered_key = key[:-1] + tampered_char

    lm = LicenseManager(license_file_path=tmp_path / "license.dat", custom_hwid=mock_hwid)
    valid, tier, exp, msg = lm.verify_product_key(tampered_key)
    assert valid is False
    assert "Chữ ký không khớp" in msg


def test_trial_activation(mock_hwid, tmp_path: Path):
    """Kiểm tra kích hoạt chế độ dùng thử tự động."""
    lm = LicenseManager(license_file_path=tmp_path / "license.dat", custom_hwid=mock_hwid)
    assert lm.activate_trial(hours=24) is True

    info = lm.load_license()
    assert info.is_valid is True
    assert info.tier == LicenseTier.TRIAL
    assert info.days_left >= 0
