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

import database
import email_service
from services.runtime import get_logger
from services.state import safe_batch_append_result


def _get_batch_id_from_source(source: str):
    """从source中提取批次ID（source格式: user_scheduled:batch_xxx）"""
    if not source:
        return None
    if source.startswith("user_scheduled:batch_"):
        return source.split(":", 1)[1]
    return None


def _send_batch_task_email_if_configured(batch_info: dict):
    """批次任务：当所有账号完成后发送打包邮件（在锁外调用）。"""
    logger = get_logger()
    try:
        batch_user_id = batch_info.get("user_id")
        if not batch_user_id:
            return
        user_info = database.get_user_by_id(batch_user_id)
        if not user_info or not user_info.get("email"):
            return
        if not database.get_user_email_notify(batch_user_id):
            return
        if not batch_info.get("screenshots"):
            return
        email_service.send_batch_task_complete_email_async(
            user_id=batch_user_id,
            email=user_info["email"],
            username=user_info["username"],
            schedule_name=batch_info.get("schedule_name", "未命名任务"),
            browse_type=batch_info.get("browse_type", "应读"),
            screenshots=batch_info["screenshots"],
        )
        logger.info(f"[批次邮件] 已发送打包邮件，包含 {len(batch_info['screenshots'])} 条记录")
    except Exception as e:
        logger.warning(f"[批次邮件] 发送失败: {e}")


def _batch_task_record_result(
    batch_id: str,
    account_name: str,
    screenshot_path: str,
    total_items: int,
    total_attachments: int,
):
    """批次任务：记录单账号结果，达到完成条件时触发邮件并回收内存。"""
    logger = get_logger()
    batch_info = safe_batch_append_result(
        batch_id,
        {
            "account_name": account_name,
            "path": screenshot_path,
            "items": total_items,
            "attachments": total_attachments,
        },
    )
    if batch_info:
        logger.info(
            f"[批次邮件] 批次 {batch_id} 已完成: {batch_info.get('completed')}/{batch_info.get('total_accounts')}，准备发送邮件"
        )
        _send_batch_task_email_if_configured(batch_info)

