# ui/worker.py

import time
import logging
from PyQt5.QtCore import QThread, pyqtSignal
from core.generator import MetadataGenerator
from utils.file_utils import extract_filename
from config import t

logger = logging.getLogger(__name__)

class Worker(QThread):
    progress = pyqtSignal(int)
    log = pyqtSignal(str)
    finished = pyqtSignal(list)
    error = pyqtSignal(str)

    def __init__(
        self, 
        paths, 
        service, 
        title_len, 
        desc_len, 
        tags_len, 
        platform="adobe", 
        model=None, 
        vision="Gemini",
        gen_lang="en",  # <--- новый параметр
    ):
        super().__init__()
        self.paths = paths
        self.service = service
        self.title_len = title_len
        self.desc_len = desc_len
        self.tags_len = tags_len
        self.durations = []
        self.platform = platform
        self.model = model
        self.vision = vision
        self.gen_lang = gen_lang  # <--- сохранить

    def run(self):
        try:
            gen = MetadataGenerator(
                self.service, 
                self.platform, 
                model=self.model, 
                vision=self.vision
            )
        except Exception as e:
            msg = t("error_init_generator").format(error=str(e))
            logger.exception(msg)
            self.error.emit(msg)
            return

        recs = []
        total = len(self.paths)
        for idx, path in enumerate(self.paths, start=1):
            fn = extract_filename(path)
            message = t("log_generating_for").format(filename=fn)
            self.log.emit(f"[{idx}/{total}] {message}")
            logger.info(message)

            start = time.perf_counter()
            try:
                data = gen.generate(
                    filepath=path,
                    title_len=self.title_len,
                    desc_len=self.desc_len,
                    tags_len=self.tags_len,
                    gen_lang=self.gen_lang,  # <--- пробрасываем язык!
                )
            except Exception as e:
                msg = t("error_generating_for").format(
                    filename=fn, error=str(e)
                )
                logger.exception(msg)
                self.error.emit(msg)
                return

            duration = time.perf_counter() - start
            self.durations.append(duration)

            resp_msg = t("response_time_log").format(duration=duration)
            logger.info(resp_msg)
            self.log.emit(f"[{idx}/{total}] {resp_msg}")

            data["filename"] = fn
            data["path"] = path
            recs.append(data)

            self.progress.emit(int(idx / total * 100))

        if self.durations:
            avg = sum(self.durations) / len(self.durations)
            tel_msg = t("telemetry_summary").format(
                count=len(self.durations),
                avg=avg
            )
            logger.info(tel_msg)
            self.log.emit(tel_msg)

        self.finished.emit(recs)
