from django.core.management.base import BaseCommand
from django.conf import settings
import oss2
from aliyunsdkcore.client import AcsClient

class Command(BaseCommand):
    help = 'Check Aliyun configuration status'

    def handle(self, *args, **options):
        self.stdout.write("Checking Aliyun Configuration...")
        
        configs = {
            'ALIYUN_ACCESS_KEY_ID': settings.ALIYUN_ACCESS_KEY_ID,
            'ALIYUN_ACCESS_KEY_SECRET': settings.ALIYUN_ACCESS_KEY_SECRET,
            'ALIYUN_OSS_BUCKET_NAME': settings.ALIYUN_OSS_BUCKET_NAME,
            'ALIYUN_OSS_ENDPOINT': settings.ALIYUN_OSS_ENDPOINT,
            'ALIYUN_TINGWU_APP_KEY': settings.ALIYUN_TINGWU_APP_KEY,
        }

        all_valid = True
        for key, value in configs.items():
            if not value:
                self.stdout.write(self.style.ERROR(f"[MISSING] {key} is not set or empty"))
                all_valid = False
            else:
                masked_value = value[:4] + "****" + value[-4:] if len(value) > 8 else "****"
                self.stdout.write(self.style.SUCCESS(f"[OK] {key}: {masked_value}"))

        if not all_valid:
            self.stdout.write(self.style.ERROR("\nConfiguration check FAILED. Some required settings are missing."))
            return

        # Test OSS Connection
        self.stdout.write("\nTesting OSS Connection...")
        try:
            auth = oss2.Auth(configs['ALIYUN_ACCESS_KEY_ID'], configs['ALIYUN_ACCESS_KEY_SECRET'])
            bucket = oss2.Bucket(auth, configs['ALIYUN_OSS_ENDPOINT'], configs['ALIYUN_OSS_BUCKET_NAME'])
            bucket.get_bucket_info()
            self.stdout.write(self.style.SUCCESS("[OK] OSS Connection successful"))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"[FAILED] OSS Connection failed: {e}"))
            
        # Test Tingwu Client Initialization
        self.stdout.write("\nTesting Tingwu Client Initialization...")
        try:
            client = AcsClient(
                configs['ALIYUN_ACCESS_KEY_ID'],
                configs['ALIYUN_ACCESS_KEY_SECRET'],
                "cn-beijing"
            )
            self.stdout.write(self.style.SUCCESS("[OK] Tingwu Client initialized"))
        except Exception as e:
             self.stdout.write(self.style.ERROR(f"[FAILED] Tingwu Client init failed: {e}"))

