# vorto_utils/qinglong.py - QingLong panel env variable client
import requests


class QingLongClient:
    """QingLong panel environment variable client.

    Usage:
        ql = QingLongClient("S_NKF")
        ql = QingLongClient("S_NKF", "http://host:5700丨client_id丨client_secret")

        ql.update_env("13800138000", "phone#token#unifyId", "牛卡福:138****0000|到期:2026-12-31")
        ql.delete_env("13800138000")
    """

    def __init__(self, os_var_name, ql_config_str=None):
        """
        Args:
            os_var_name: QingLong env variable name, e.g. "S_NKF"
            ql_config_str: Config string "host丨client_id丨client_secret".
                          Falls back to middleware bucket if not provided.
        """
        if ql_config_str is None:
            try:
                import middleware
                ql_config_str = middleware.bucketGet('s_vorto', 'qlname') or ''
            except ImportError:
                ql_config_str = ''

        self.os_var_name = os_var_name
        self.host = ''
        self.client_id = ''
        self.client_secret = ''

        if ql_config_str:
            configs = ql_config_str.replace('|', '丨').split('丨')
            if len(configs) >= 3:
                self.host = configs[0].strip()
                self.client_id = configs[1].strip()
                self.client_secret = configs[2].strip()

    def is_configured(self):
        """Check if QingLong is properly configured"""
        return bool(self.host and self.client_id and self.client_secret)

    def get_token(self):
        """Get QingLong access token.

        Returns:
            str: Access token, None on failure.
        """
        if not self.is_configured():
            return None
        try:
            url = f'{self.host}/open/auth/token?client_id={self.client_id}&client_secret={self.client_secret}'
            resp = requests.get(url, timeout=10).json()
            if resp.get('code') == 200:
                return resp['data']['token']
            return None
        except Exception:
            return None

    def update_env(self, username, env_value, remark=''):
        """Update or create a QingLong environment variable.

        Args:
            username: User identifier (matched in remarks).
            env_value: Environment variable value.
            remark: Environment variable remark.

        Returns:
            bool: Whether the operation succeeded.
        """
        if not self.is_configured():
            return False

        try:
            token = self.get_token()
            if not token:
                return False

            headers = {'Authorization': f'Bearer {token}'}

            envs = requests.get(
                f'{self.host}/open/envs?searchValue={username}',
                headers=headers,
                timeout=10
            ).json().get('data', [])
            env_id = next((e.get('id') for e in envs if e['name'] == self.os_var_name), None)

            env_data = {
                'name': self.os_var_name,
                'value': env_value,
                'remarks': remark
            }

            if env_id:
                env_data['id'] = env_id
                requests.put(f'{self.host}/open/envs', headers=headers, json=env_data, timeout=10)
                requests.put(f'{self.host}/open/envs/enable', headers=headers, json=[env_id], timeout=10)
            else:
                resp = requests.post(f'{self.host}/open/envs', headers=headers, json=[env_data], timeout=10).json()
                if resp.get('data'):
                    new_id = resp['data'][0].get('_id') or resp['data'][0].get('id')
                    if new_id:
                        requests.put(f'{self.host}/open/envs/enable', headers=headers, json=[new_id], timeout=10)
            return True
        except Exception:
            return False

    def delete_env(self, username):
        """Delete a QingLong environment variable.

        Args:
            username: User identifier (matched in remarks).

        Returns:
            bool: Whether the operation succeeded.
        """
        if not self.is_configured():
            return False

        try:
            token = self.get_token()
            if not token:
                return False

            headers = {'Authorization': f'Bearer {token}'}
            envs = requests.get(f'{self.host}/open/envs', headers=headers, timeout=10).json().get('data', [])

            for env in envs:
                if env['name'] == self.os_var_name and username in env.get('remarks', ''):
                    env_id = env.get('_id') or env.get('id')
                    requests.delete(f'{self.host}/open/envs', headers=headers, json=[env_id], timeout=10)
                    return True
            return False
        except Exception:
            return False
