from __future__ import annotations

import json
from pathlib import Path

from openclaw_lite.auth import AuthManager
from openclaw_lite.config import load_config, save_config


def test_pairing_code_claim_grants_access(tmp_path: Path) -> None:
    manager = AuthManager(
        {
            "data_dir": str(tmp_path),
            "telegram": {"owner_user_ids": [1], "pairing": {"ttl_seconds": 300}},
        }
    )
    ticket = manager.generate_pairing_code(created_by=1)
    assert manager.is_approved(222, 333) is False
    result = manager.claim_pairing_code(ticket["code"], user_id=222, chat_id=333)
    assert result["approved"] is True
    assert manager.is_approved(222, 333) is True


def test_owner_and_allowlists_are_respected(tmp_path: Path) -> None:
    manager = AuthManager(
        {
            "data_dir": str(tmp_path),
            "telegram": {
                "owner_user_ids": [7],
                "owner_chat_ids": [77],
                "allowed_user_ids": [8],
                "allowed_chat_ids": [88],
            },
        }
    )
    assert manager.is_owner(7, None) is True
    assert manager.is_owner(None, 77) is True
    assert manager.is_approved(7, 999) is True
    assert manager.is_approved(8, None) is True
    assert manager.is_approved(None, 88) is True
    assert manager.is_approved(99, 999) is False


def test_pairing_state_persists_and_can_be_reloaded(tmp_path: Path) -> None:
    config = {
        "data_dir": str(tmp_path),
        "telegram": {"owner_user_ids": [1], "pairing": {"enabled": True, "code_ttl_sec": 120}},
    }
    manager = AuthManager(config)
    ticket = manager.generate_pairing_code(created_by=1)
    manager.claim_pairing_code(ticket["code"], user_id=55, chat_id=66)

    second = AuthManager(config)
    assert second.is_approved(55, None) is True
    assert second.is_approved(None, 66) is True
    assert second.summary()["grants"][0]["via"] == "pairing_code"


def test_load_config_supports_pairing_and_allowlists(tmp_path: Path) -> None:
    config_path = tmp_path / "config.yaml"
    config_path.write_text(
        """
telegram:
  bot_token: test-token
  owner_user_ids: [100]
  owner_chat_ids: [200]
  allowed_user_ids: [300]
  allowed_chat_ids: [400]
  pairing:
    enabled: true
    code_ttl_sec: 777
""",
        encoding="utf-8",
    )
    config = load_config(config_path)
    assert config.telegram.owner_user_ids == [100]
    assert config.telegram.owner_chat_ids == [200]
    assert config.telegram.allowed_user_ids == [300]
    assert config.telegram.allowed_chat_ids == [400]
    assert config.telegram.pairing.enabled is True
    assert config.telegram.pairing.code_ttl_sec == 777

    save_config(config, config_path)
    saved = json.loads(config_path.read_text(encoding="utf-8").replace("'", '"')) if False else None
    reloaded = load_config(config_path)
    assert reloaded.telegram.allowed_user_ids == [300]
    assert reloaded.telegram.pairing.code_ttl_sec == 777
