#!/usr/bin/env python3
"""
渐进式任务管理
"""

import time
from typing import Optional, Callable

from .types import ProgressInfo
from ..logger import logger

class ProgressiveTask:
    """渐进式任务包装器"""
    
    def __init__(self, task_name: str, total_steps: int = 100):
        self.task_name = task_name
        self.total_steps = total_steps
        self.current_step = 0
        self.start_time = None
        self.progress_callback: Optional[Callable[[ProgressInfo], None]] = None
    
    def set_progress_callback(self, callback: Callable[[ProgressInfo], None]):
        """设置进度回调"""
        self.progress_callback = callback
    
    def start(self):
        """开始任务"""
        self.start_time = time.time()
        self.current_step = 0
        self._report_progress("任务开始")
        logger.debug(f"Task started: {self.task_name}")
    
    def update(self, step: int = None, message: str = ""):
        """更新进度"""
        if step is not None:
            self.current_step = step
        else:
            self.current_step += 1
        
        self._report_progress(message)
    
    def finish(self, message: str = "任务完成"):
        """完成任务"""
        self.current_step = self.total_steps
        self._report_progress(message)
        logger.debug(f"Task finished: {self.task_name}")
    
    def _report_progress(self, message: str):
        """报告进度"""
        if self.progress_callback and self.start_time:
            elapsed = time.time() - self.start_time
            
            # 估算剩余时间
            if self.current_step > 0:
                avg_time_per_step = elapsed / self.current_step
                remaining_steps = self.total_steps - self.current_step
                estimated_remaining = avg_time_per_step * remaining_steps
            else:
                estimated_remaining = 0.0
            
            progress = ProgressInfo(
                current=self.current_step,
                total=self.total_steps,
                message=message,
                elapsed_time=elapsed,
                estimated_remaining=estimated_remaining
            )
            
            self.progress_callback(progress)
