#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

from flask_login import UserMixin

from services.state import safe_get_task_status


class User(UserMixin):
    """Flask-Login 用户类"""

    def __init__(self, user_id: int):
        self.id = user_id


class Admin(UserMixin):
    """管理员类"""

    def __init__(self, admin_id: int):
        self.id = admin_id
        self.is_admin = True


class Account:
    """账号类（用于内存缓存与任务执行）"""

    def __init__(
        self,
        account_id: str,
        user_id: int,
        username: str,
        password: str,
        remember: bool = True,
        remark: str = "",
    ):
        self.id = account_id
        self.user_id = user_id
        self.username = username
        self._password = password
        self.remember = remember
        self.remark = remark or ""

        # 运行状态
        self.is_running = False
        self.should_stop = False
        self.status = "未开始"

        # 任务数据
        self.total_items = 0
        self.total_attachments = 0
        self.last_browse_type = ""

        # 浏览器自动化对象（主任务）
        self.automation = None

        # 代理配置（浏览与截图共用）
        self.proxy_config = None

    @property
    def password(self) -> str:
        return self._password

    def __repr__(self) -> str:
        return f"Account(id={self.id}, username={self.username}, status={self.status})"

    def to_dict(self) -> dict:
        result = {
            "id": self.id,
            "username": self.username,
            "status": self.status,
            "remark": self.remark,
            "total_items": self.total_items,
            "total_attachments": self.total_attachments,
            "is_running": self.is_running,
        }

        ts = safe_get_task_status(self.id)
        if ts:
            progress = ts.get("progress", {}) or {}
            result["detail_status"] = ts.get("detail_status", "")
            result["progress_items"] = progress.get("items", 0)
            result["progress_attachments"] = progress.get("attachments", 0)
            result["start_time"] = ts.get("start_time", 0)
            if ts.get("start_time"):
                import time

                elapsed = int(time.time() - ts["start_time"])
                result["elapsed_seconds"] = elapsed
                mins, secs = divmod(elapsed, 60)
                result["elapsed_display"] = f"{mins}分{secs}秒"
        else:
            status_map = {
                "已完成": "任务完成",
                "截图中": "正在截图",
                "浏览完成": "浏览完成",
                "登录失败": "登录失败",
                "已暂停": "任务已暂停",
            }
            for key, val in status_map.items():
                if key in self.status:
                    result["detail_status"] = val
                    break

        return result

