#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SaaS授权系统 - Python客户端

使用说明：
1. 安装依赖：pip install requests
2. 修改 API_KEY 为您的真实API密钥
3. 导入使用：from authorization_client import AuthorizationClient

@author 授权系统
@version 1.0.0
"""

import requests
import json
import time
import os
from typing import Optional, Dict, Any

class AuthorizationClient:
    """授权客户端"""
    
    # ==================== 配置区 ====================
    
    # API密钥（从开发者中心获取）
    # 网址：https://kuio.cn/user/developer
    API_KEY = 'your_api_key_here'
    
    # API接口地址
    BASE_URL = 'https://kuio.cn/api/saas'
    
    # 缓存配置
    CACHE_ENABLED = True
    CACHE_DURATION = 1800  # 30分钟
    CACHE_FILE_PATH = '/tmp/auth_cache.json'
    
    def __init__(self, api_key: Optional[str] = None):
        """初始化"""
        self.api_key = api_key or self.API_KEY
        self.session = requests.Session()
        self.session.headers.update({
            'X-API-Key': self.api_key,
            'User-Agent': 'Python-AuthClient/1.0'
        })
    
    # ==================== 核心方法 ====================
    
    def verify(self, authcode: str, domain: Optional[str] = None, 
               ip: Optional[str] = None) -> Dict[str, Any]:
        """
        验证授权（带缓存）
        
        Args:
            authcode: 授权码
            domain: 域名（可选）
            ip: IP地址（可选）
            
        Returns:
            {'success': bool, 'message': str, 'data': dict}
        """
        # 1. 尝试从缓存读取
        if self.CACHE_ENABLED:
            cached = self._get_cache(authcode)
            if cached is not None:
                return {
                    'success': True,
                    'message': '授权验证成功（缓存）',
                    'data': cached,
                    'from_cache': True
                }
        
        # 2. 调用API验证
        result = self.verify_from_api(authcode, domain, ip)
        
        # 3. 成功则写入缓存
        if result['success'] and self.CACHE_ENABLED:
            self._set_cache(authcode, result['data'])
        
        return result
    
    def verify_from_api(self, authcode: str, domain: Optional[str] = None,
                       ip: Optional[str] = None) -> Dict[str, Any]:
        """从API验证授权（不使用缓存）"""
        url = f'{self.BASE_URL}/verify'
        
        data = {'authcode': authcode}
        if domain:
            data['domain'] = domain
        if ip:
            data['ip'] = ip
        
        try:
            response = self.session.post(
                url, 
                json=data,
                headers={'Content-Type': 'application/json'},
                timeout=10
            )
            
            result = response.json()
            
            if response.status_code == 200 and result.get('code') == 0:
                return {
                    'success': True,
                    'message': result.get('msg', '授权验证成功'),
                    'data': result.get('data', {}),
                    'meta': result.get('meta')
                }
            else:
                return {
                    'success': False,
                    'message': result.get('msg', '授权验证失败'),
                    'code': result.get('code'),
                    'http_code': response.status_code
                }
        except Exception as e:
            return {
                'success': False,
                'message': f'网络请求失败: {str(e)}',
                'error': str(e)
            }
    
    def create_authorization(self, authcode: str, customer_name: str, 
                           **kwargs) -> Dict[str, Any]:
        """
        创建授权
        
        Args:
            authcode: 授权码
            customer_name: 客户名称
            **kwargs: 其他参数（customer_domain, expire_at等）
        """
        url = f'{self.BASE_URL}/authorization/create'
        
        data = {
            'authcode': authcode,
            'customer_name': customer_name,
            **kwargs
        }
        
        try:
            response = self.session.post(url, json=data, timeout=10)
            return response.json()
        except Exception as e:
            return {
                'code': -1,
                'msg': f'请求失败: {str(e)}'
            }
    
    def list_authorizations(self, page: int = 1, page_size: int = 20,
                          **filters) -> Dict[str, Any]:
        """查询授权列表"""
        url = f'{self.BASE_URL}/authorizations'
        
        params = {
            'page': page,
            'page_size': page_size,
            **filters
        }
        
        try:
            response = self.session.get(url, params=params, timeout=10)
            return response.json()
        except Exception as e:
            return {
                'code': -1,
                'msg': f'请求失败: {str(e)}'
            }
    
    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        url = f'{self.BASE_URL}/stats'
        
        try:
            response = self.session.get(url, timeout=10)
            return response.json()
        except Exception as e:
            return {
                'code': -1,
                'msg': f'请求失败: {str(e)}'
            }
    
    # ==================== 缓存方法 ====================
    
    def _get_cache(self, authcode: str) -> Optional[Dict]:
        """从缓存获取"""
        if not os.path.exists(self.CACHE_FILE_PATH):
            return None
        
        try:
            with open(self.CACHE_FILE_PATH, 'r') as f:
                cache = json.load(f)
            
            if authcode not in cache:
                return None
            
            item = cache[authcode]
            
            # 检查是否过期
            if item['expire_time'] < time.time():
                del cache[authcode]
                with open(self.CACHE_FILE_PATH, 'w') as f:
                    json.dump(cache, f)
                return None
            
            return item['data']
        except:
            return None
    
    def _set_cache(self, authcode: str, data: Dict):
        """写入缓存"""
        cache = {}
        
        if os.path.exists(self.CACHE_FILE_PATH):
            try:
                with open(self.CACHE_FILE_PATH, 'r') as f:
                    cache = json.load(f)
            except:
                cache = {}
        
        cache[authcode] = {
            'data': data,
            'expire_time': time.time() + self.CACHE_DURATION
        }
        
        try:
            with open(self.CACHE_FILE_PATH, 'w') as f:
                json.dump(cache, f)
        except Exception as e:
            print(f'缓存写入失败: {e}')
    
    def clear_cache(self, authcode: Optional[str] = None):
        """清除缓存"""
        if authcode is None:
            # 清除所有缓存
            if os.path.exists(self.CACHE_FILE_PATH):
                os.remove(self.CACHE_FILE_PATH)
        else:
            # 清除指定缓存
            if os.path.exists(self.CACHE_FILE_PATH):
                try:
                    with open(self.CACHE_FILE_PATH, 'r') as f:
                        cache = json.load(f)
                    
                    if authcode in cache:
                        del cache[authcode]
                    
                    with open(self.CACHE_FILE_PATH, 'w') as f:
                        json.dump(cache, f)
                except:
                    pass
    
    # ==================== 便捷方法 ====================
    
    def check(self, authcode: str) -> bool:
        """快速验证（仅返回True/False）"""
        result = self.verify(authcode)
        return result['success']
    
    def verify_or_exit(self, authcode: str, domain: Optional[str] = None):
        """验证或退出程序"""
        result = self.verify(authcode, domain)
        
        if not result['success']:
            print('=' * 50)
            print('⚠️  授权验证失败')
            print('=' * 50)
            print(f'授权码：{authcode}')
            print(f'错误信息：{result["message"]}')
            print('=' * 50)
            exit(1)
        
        return result
    
    @staticmethod
    def log(message: str, level: str = 'INFO'):
        """记录日志"""
        timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
        log_line = f'[{timestamp}] [{level}] {message}\n'
        
        log_file = '/tmp/auth_log.txt'
        
        try:
            with open(log_file, 'a') as f:
                f.write(log_line)
        except:
            pass


# ==================== 使用示例 ====================

if __name__ == '__main__':
    # 创建客户端实例
    client = AuthorizationClient('your_api_key_here')
    
    # 示例1：基础验证
    print('\n示例1：基础验证')
    result = client.verify('ABC123XYZ')
    if result['success']:
        print('✅ 授权验证成功！')
        print(f"客户名称：{result['data'].get('customer_name')}")
        print(f"过期时间：{result['data'].get('expire_at')}")
    else:
        print(f'❌ 授权验证失败：{result["message"]}')
    
    # 示例2：快速验证
    print('\n示例2：快速验证')
    if client.check('ABC123XYZ'):
        print('✅ 授权有效')
    else:
        print('❌ 授权无效')
    
    # 示例3：创建授权
    print('\n示例3：创建授权')
    result = client.create_authorization(
        'NEW-2025-001',
        '客户公司名称',
        customer_domain='client.com',
        expire_at='2026-01-01 00:00:00',
        custom_data={'plan': 'professional', 'users': 50}
    )
    if result.get('code') == 0:
        print(f"✅ 授权创建成功！ID：{result['data']['id']}")
    else:
        print(f"❌ 创建失败：{result.get('msg')}")
    
    # 示例4：查询统计
    print('\n示例4：查询统计')
    stats = client.get_stats()
    if stats.get('code') == 0:
        data = stats['data']
        print(f"今日调用：{data['calls']['today']} 次")
        print(f"本月调用：{data['calls']['month']} 次")
        print(f"剩余次数：{data['calls']['remaining']}")
    
    # 示例5：清除缓存
    print('\n示例5：清除缓存')
    client.clear_cache()
    print('✅ 缓存已清除')

