import hashlib
import hmac
import time
import uuid
import pytest
from httpx import AsyncClient
from core.config import get_settings


def create_telegram_auth_payload(
    user_id: int,
    first_name: str,
    last_name: str | None = None,
    username: str | None = None,
    photo_url: str | None = None,
    auth_date: int | None = None,
    bot_token: str | None = None,
) -> dict:
    settings = get_settings()
    token = bot_token or settings.TELEGRAM_BOT_TOKEN
    date_val = int(time.time()) if auth_date is None else auth_date

    data = {
        "id": user_id,
        "first_name": first_name,
        "auth_date": date_val,
    }
    if last_name:
        data["last_name"] = last_name
    if username:
        data["username"] = username
    if photo_url:
        data["photo_url"] = photo_url

    # Calculate valid HMAC-SHA256 signature
    check_pairs = [f"{k}={v}" for k, v in sorted(data.items())]
    data_check_string = "\n".join(check_pairs)
    secret_key = hashlib.sha256(token.encode("utf-8")).digest()
    sig_hash = hmac.new(secret_key, data_check_string.encode("utf-8"), hashlib.sha256).hexdigest()

    data["hash"] = sig_hash
    return data


@pytest.mark.asyncio
async def test_telegram_auth_success_and_login(async_client: AsyncClient):
    """Test full Telegram login flow with real cryptographic signature."""
    tg_user_id = 992837410
    payload = create_telegram_auth_payload(
        user_id=tg_user_id,
        first_name="Pavel",
        last_name="Durov",
        username="pavel_official",
    )

    resp = await async_client.post("/api/v1/auth/telegram", json=payload)
    assert resp.status_code == 200, resp.text
    data = resp.json()
    assert data["success"] is True
    assert "access_token" in data["data"]
    access_token = data["data"]["access_token"]

    # Verify user profile via /auth/me
    me_resp = await async_client.get(
        "/api/v1/auth/me",
        headers={"Authorization": f"Bearer {access_token}"},
    )
    assert me_resp.status_code == 200
    me_data = me_resp.json()["data"]
    assert me_data["telegram_user_id"] == tg_user_id
    assert me_data["telegram_username"] == "pavel_official"
    assert "Pavel" in me_data["full_name"]


@pytest.mark.asyncio
async def test_telegram_auth_tampered_payload_rejected(async_client: AsyncClient):
    """Test that modifying any field without re-signing causes 401 verification failure."""
    payload = create_telegram_auth_payload(
        user_id=883192031,
        first_name="Alice",
    )
    # Attacker tries to impersonate another user ID
    payload["id"] = 111111111

    resp = await async_client.post("/api/v1/auth/telegram", json=payload)
    assert resp.status_code == 401
    assert "verification failed" in resp.json()["message"].lower()


@pytest.mark.asyncio
async def test_telegram_auth_replay_expired_rejected(async_client: AsyncClient):
    """Test that auth_date older than 24 hours is rejected to prevent replay attacks."""
    expired_date = int(time.time()) - 90000  # 25 hours ago
    payload = create_telegram_auth_payload(
        user_id=773829104,
        first_name="Bob",
        auth_date=expired_date,
    )

    resp = await async_client.post("/api/v1/auth/telegram", json=payload)
    assert resp.status_code == 401
    assert "expired" in resp.json()["message"].lower()


@pytest.mark.asyncio
async def test_telegram_auth_future_timestamp_rejected(async_client: AsyncClient):
    """Test that timestamps far in the future are rejected."""
    future_date = int(time.time()) + 600  # 10 minutes in future
    payload = create_telegram_auth_payload(
        user_id=663829104,
        first_name="Charlie",
        auth_date=future_date,
    )

    resp = await async_client.post("/api/v1/auth/telegram", json=payload)
    assert resp.status_code == 401
    assert "future" in resp.json()["message"].lower()


@pytest.mark.asyncio
async def test_telegram_account_linking(async_client: AsyncClient):
    """Test linking a Telegram account to an existing email/password account."""
    email = f"user_{uuid.uuid4().hex[:8]}@example.com"
    reg_resp = await async_client.post(
        "/api/v1/auth/register",
        json={"email": email, "password": "StrongPassword2026!", "full_name": "Standard User"},
    )
    assert reg_resp.status_code == 201
    token = reg_resp.json()["data"]["access_token"]

    link_payload = create_telegram_auth_payload(
        user_id=554433221,
        first_name="Linked",
        username="linked_tg",
    )

    link_resp = await async_client.post(
        "/api/v1/auth/telegram/link",
        headers={"Authorization": f"Bearer {token}"},
        json=link_payload,
    )
    assert link_resp.status_code == 200
    user_data = link_resp.json()["data"]
    assert user_data["telegram_user_id"] == 554433221
    assert user_data["telegram_username"] == "linked_tg"


@pytest.mark.asyncio
async def test_telegram_config_endpoint(async_client: AsyncClient):
    """Test widget config endpoint returns bot username."""
    resp = await async_client.get("/api/v1/auth/telegram/config")
    assert resp.status_code == 200
    data = resp.json()["data"]
    assert "bot_username" in data
