from __future__ import annotations
from PyQt6.QtCore import QObject, QProcess, pyqtSignal
from pathlib import Path

class TranslationWorker(QObject):
    log_line = pyqtSignal(str)
    finished = pyqtSignal(bool, str)  # success, output_path
    error = pyqtSignal(str)

    def __init__(self, transart_script: Path, article_path: Path, direction: str, parent=None):
        super().__init__(parent)
        self._script = transart_script
        self._article_path = article_path
        self._direction = direction  # e.g. "it-en" or "en-it"
        self._process = QProcess(self)
        self._process.readyReadStandardOutput.connect(self._on_stdout)
        self._process.readyReadStandardError.connect(self._on_stderr)
        self._process.finished.connect(self._on_finished)

    def start(self):
        self._process.start("python3", [
            str(self._script),
            "--direction", self._direction,
            str(self._article_path),
        ])

    def _on_stdout(self):
        data = self._process.readAllStandardOutput().data().decode("utf-8", errors="replace")
        for line in data.splitlines():
            self.log_line.emit(line)

    def _on_stderr(self):
        data = self._process.readAllStandardError().data().decode("utf-8", errors="replace")
        for line in data.splitlines():
            self.log_line.emit(f"[stderr] {line}")

    def _on_finished(self, exit_code: int, _):
        success = exit_code == 0
        path_str = str(self._article_path)
        if "/it/" in path_str:
            out = path_str.replace("/it/", "/en/", 1)
        elif "/en/" in path_str:
            out = path_str.replace("/en/", "/it/", 1)
        else:
            out = ""
        if not success:
            self.error.emit(f"transart.py exited with code {exit_code}")
        self.finished.emit(success, out)
