"""天翼云盘凭证管理 v1.0.0 — Cookie + 账号密码双模式"""

import re
import base64
import logging
from typing import Optional

logger = logging.getLogger(__name__)


class Cloud189CredentialManager:
    LOGIN_URL = "https://cloud.189.cn/api/portal/loginUrl.action"
    SSO_URL = "https://open.e.189.cn/api/logbox/oauth2/ssoLogin.action"

    def __init__(self, config):
        self.config = config
        self._cookie: Optional[str] = None

    def validate(self) -> bool:
        if self.config.cookie:
            return len(self.config.cookie) >= 30
        extra = self.config.extra or {}
        return bool(extra.get("username") and extra.get("password"))

    def get_headers(self) -> dict:
        return {
            "Cookie": self._cookie or self.config.cookie,
            "Referer": "https://cloud.189.cn/",
        }

    def login_if_needed(self, session) -> bool:
        """如需账号密码登录，在此执行"""
        if self.config.cookie:
            self._cookie = self.config.cookie
            return True
        extra = self.config.extra or {}
        username = extra.get("username", "")
        password = extra.get("password", "")
        if not username or not password:
            return False
        try:
            logger.info("Attempting 189 cloud login...")
            resp = session.get(self.LOGIN_URL, timeout=30)
            data = resp.json()
            login_url = data.get("toUrl", "")
            session.cookies.clear()
            sso_resp = session.post(
                self.SSO_URL,
                data={"account": username, "password": password,
                      "appKey": "cloud", "returnUrl": login_url},
                timeout=30,
            )
            sso_data = sso_resp.json()
            redirect_url = sso_data.get("toUrl", "")
            if redirect_url:
                session.get(redirect_url, timeout=30)
            self._cookie = "; ".join(
                f"{c.name}={c.value}" for c in session.cookies
            )
            logger.info("189 cloud login successful")
            return bool(self._cookie)
        except Exception as e:
            logger.error(f"189 cloud login failed: {e}")
            return False
