# radar_data_reader/core/out_processor.py

"""
Contains the business logic for the .out file processing feature.
"""

import multiprocessing as mp
from pathlib import Path
from typing import Optional

from ..utils import logger
from ..core.file_reader import run_worker_process
from ..core.export_profiles import ExportProfile

log = logger.get_logger(__name__)


class OutProcessor:
    """Manages the processing of a single .out file."""

    def __init__(self, command_queue: mp.Queue, result_queue: mp.Queue):
        self.command_queue = command_queue
        self.result_queue = result_queue
        self.worker_process: Optional[mp.Process] = None

    def start_processing(
        self,
        filepath: Path,
        active_profile: ExportProfile,
        enable_profiling: bool = False, # <-- NUOVO PARAMETRO
    ):
        """
        Starts the worker process to read and parse the .out file.
        """
        # Clear queues before starting a new process
        while not self.command_queue.empty():
            try:
                self.command_queue.get_nowait()
            except mp.queues.Empty:
                break
        while not self.result_queue.empty():
            try:
                self.result_queue.get_nowait()
            except mp.queues.Empty:
                break

        worker_args = (
            filepath,
            self.command_queue,
            self.result_queue,
            active_profile,
            enable_profiling, # <-- PASSAGGIO DEL NUOVO PARAMETRO
        )

        self.worker_process = mp.Process(
            target=run_worker_process, args=worker_args, daemon=True
        )
        self.worker_process.start()
        log.info(
            f"Started .out processor worker (PID: {self.worker_process.pid}) for file {filepath.name}"
        )

    def get_worker(self) -> Optional[mp.Process]:
        """Returns the current worker process instance."""
        return self.worker_process