"""Yeni hesapları panel API'sine iletmek için yardımcı modül."""
from __future__ import annotations

import json
import logging
import threading
from typing import Any, Dict

import requests
from requests import exceptions as requests_exceptions

LOGGER = logging.getLogger(__name__)
_PANEL_ENDPOINT = "https://xfollowtest.com/add/data-create"
_PANEL_API_KEY = "0f9c9ce3669764cb35a8372810c46c1b7fbb0017"
_PANEL_ENABLED = False
_CONFIG_LOCK = threading.Lock()


def _coerce_bool(value: Any) -> bool:
    if isinstance(value, bool):
        return value
    if isinstance(value, (int, float)):
        return value != 0
    if isinstance(value, str):
        lowered = value.strip().lower()
        return lowered in {"1", "true", "yes", "on"}
    return False


def configure_panel_sender(value: Any) -> None:
    """config.json'daki send_panel ayarını belleğe uygula."""

    enabled = _coerce_bool(value)
    global _PANEL_ENABLED
    with _CONFIG_LOCK:
        _PANEL_ENABLED = enabled



def _is_enabled() -> bool:
    with _CONFIG_LOCK:
        return _PANEL_ENABLED


def send_account_to_panel(record: Dict[str, Any]) -> None:
    """Panel servisine hesap verilerini gönder."""

    if not _is_enabled():
        return

    username = str(record.get("username") or "").strip()
    password = str(record.get("password") or "").strip()
    email_address = str(record.get("email_address") or "").strip()
    email_id = str(record.get("email_id") or "").strip()
    auth_token = str(record.get("auth_token") or "").strip()
    csrf_token = str(record.get("csrf_token") or "").strip()

    if not username or not password or not auth_token or not csrf_token:
        LOGGER.debug(
            "Panel submission skipped: required fields are missing (username=%s, auth=%s).",
            username,
            bool(auth_token),
        )
        return

    payload = {
        "key": _PANEL_API_KEY,
        "username": username,
        "password": password,
        "mail": email_address,
        "mailpass": email_id,
        "ct0": csrf_token,
        "authtoken": auth_token,
        "2fasecret": None,
    }

    try:
        response = requests.post(
            _PANEL_ENDPOINT,
            headers={"Content-Type": "application/json"},
            data=json.dumps(payload),
            timeout=15,
        )
    except requests_exceptions.RequestException as exc:
        LOGGER.warning("Panel submission failed: %s", exc)
        return

    if response.status_code >= 400:
        preview = (response.text or "").strip()
        if len(preview) > 200:
            preview = preview[:200] + "..."
        LOGGER.warning(
            "Panel submission was rejected with status %s: %s",
            response.status_code,
            preview,
        )
        return

    LOGGER.info("Panel submission succeeded: %s", username)
