from pathlib import Path

import click
import tomli as tomllib

from ..config import settings
from ..lib._http import HttpClient


def _load_config(path: Path) -> dict | None:
    if not path.exists():
        return None
    try:
        with open(path, "rb") as f:
            data = tomllib.load(f)
        if not all(k in data for k in ("username", "user_id", "api_key")):
            return None
        return data
    except Exception:
        return None


def _save_config(path: Path, user_info: dict) -> None:
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            f.write(f'username = "{user_info["username"]}"\n')
            f.write(f'user_id = "{user_info["user_id"]}"\n')
            f.write(f'api_key = "{user_info["api_key"]}"\n')
            f.write(f'created_at = "{user_info["created_at"]}"\n')
        try:
            path.chmod(0o600)
        except Exception:
            pass
    except Exception as e:
        raise click.ClickException(f"配置文件保存失败: {e}") from None


def get_saved_api_key() -> str | None:
    data = _load_config(settings.config_path)
    if not data:
        return None
    api_key = str(data.get("api_key", "")).strip()
    return api_key or None


def ensure_login(
    api_key: str | None = None,
    relogin: bool = False,
    save: bool = True,
) -> dict:
    """
    进行登录检查
    优先使用传入的 api_key, 其次使用本地保存的 api_key, 如果都没有则手动输入
    """
    config_path = settings.config_path
    http_client = HttpClient()

    if not relogin and not api_key:
        existing_key = get_saved_api_key()
        if existing_key:
            try:
                user_info = http_client.check_user(api_key=existing_key)
            except Exception:
                click.echo("⚠️ 本地保存的 API Key 无效, 请重新登录")
            else:
                _save_config(config_path, user_info)
                return user_info

    if not api_key:
        api_key = click.prompt("🤖 请输入 API Key", type=str, hide_input=True)

    api_key = str(api_key).strip()
    if not api_key:
        raise click.ClickException("API Key 不能为空")

    try:
        user_info = http_client.check_user(api_key=api_key)
    except Exception as e:
        raise click.ClickException(str(e)) from None

    if save:
        _save_config(config_path, user_info)
    return user_info


@click.option(
    "-k",
    "--api-key",
    type=str,
    help="API Key for authentication",
)
@click.option(
    "-r",
    "--relogin",
    is_flag=True,
    help="Force re-login and overwrite the local API Key",
)
def login(api_key: str | None, relogin: bool):
    """Login to the Trio service"""
    user_info = ensure_login(api_key=api_key, relogin=relogin, save=True)
    click.echo(f"✅ 登录成功，用户 {user_info['username']}")


def logout():
    """Logout from the Trio service"""
    config_path = settings.config_path
    if config_path.exists():
        try:
            config_path.unlink()
        except Exception as e:
            raise click.ClickException(f"配置文件删除失败: {e}") from None
        settings.api_key = ""
        click.echo("✅ 已退出登录")
        return

    click.echo("⚠️ 未检测到登录信息")
