"""Raw acquisition producer for the external Kamil ADC radar mode."""

from __future__ import annotations

import argparse
from contextlib import suppress
import logging
from pathlib import Path
import signal
import threading
import time

import numpy as np

from python_app.hardware_full.kamil_adc_service import KamilAdcService
from python_app.hardware_full.switch_service import SwitchService
from python_app.models.dataset_model import ComboKey, SweepCollection, TraceData
from python_app.models.run_config_model import RunConfigModel, SwitchModel
from python_app.orchestration.shm import ShmRingWriter
from python_app.storage.npz.serialize import RAW_MAGIC, serialize_trace_collection

logger = logging.getLogger(__name__)


def main() -> int:
    """Run producer process until config or signal requests exit."""
    parser = argparse.ArgumentParser(description="Publish Kamil ADC raw sweeps to SHM rings")
    parser.add_argument("--config", required=True, type=Path, help="Path to run_config.json")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
    stop_requested = threading.Event()

    def request_stop(_signum: int, _frame: object) -> None:
        stop_requested.set()

    signal.signal(signal.SIGINT, request_stop)
    signal.signal(signal.SIGTERM, request_stop)

    config = RunConfigModel.load_from_path(args.config)
    if not config.is_kamil_adc:
        raise RuntimeError("kamil_adc_raw_producer requires radar.model='kamil_adc'")
    config.ensure_combos()

    raw_writer = ShmRingWriter(
        config.rings.raw.name,
        config.rings.raw.capacity,
        config.rings.raw.slot_size_bytes,
    )
    raw_tap_writer = ShmRingWriter(
        config.rings.raw_tap.name,
        config.rings.raw_tap.capacity,
        config.rings.raw_tap.slot_size_bytes,
    )
    radar = KamilAdcService(config)
    input_switch = _switch_from_model(config.input_switch)
    output_switch = _switch_from_model(config.output_switch)

    try:
        radar.open()
        radar.configure(config.radar.sweep)
        output_switch.open()
        input_switch.open()

        collection_id = 1
        while not stop_requested.is_set():
            collection_start = time.monotonic()
            capture_start_ns = time.monotonic_ns()
            traces: list[TraceData] = []

            for combo in config.combos:
                if stop_requested.is_set():
                    break
                output_switch.switch_to(combo.output)
                input_switch.switch_to(combo.input)
                if config.runtime.settling_ms > 0:
                    time.sleep(config.runtime.settling_ms / 1000.0)

                sweep = radar.acquire()
                traces.append(
                    TraceData(
                        combo=ComboKey(input=combo.input, output=combo.output),
                        frequency_hz=np.asarray(sweep.x, dtype=np.float32),
                        s11=np.asarray(sweep.trace("s11"), dtype=np.complex64),
                        s21=np.asarray(sweep.trace("s21"), dtype=np.complex64),
                    )
                )

            if len(traces) != len(config.combos):
                break

            collection = SweepCollection(
                collection_id=collection_id,
                monotonic_ns=time.monotonic_ns(),
                traces=traces,
                capture_start_ns=capture_start_ns,
                capture_end_ns=time.monotonic_ns(),
            )
            payload = serialize_trace_collection(collection, RAW_MAGIC)
            if not raw_writer.push(payload):
                raise RuntimeError(
                    f"Raw payload size {len(payload)} exceeds ring slot size {raw_writer.slot_size_bytes}"
                )
            if not raw_tap_writer.push(payload):
                raise RuntimeError(
                    f"Raw tap payload size {len(payload)} exceeds ring slot size {raw_tap_writer.slot_size_bytes}"
                )

            if not config.runtime.continuous:
                break
            collection_duration_s = time.monotonic() - collection_start
            if collection_id == 1 or collection_id % 20 == 0 or collection_duration_s > 2.0:
                logger.info("Kamil ADC collection %d acquired in %.3f s", collection_id, collection_duration_s)
            collection_id += 1
    finally:
        with suppress(Exception):
            output_switch.close()
        with suppress(Exception):
            input_switch.close()
        radar.close()
        raw_tap_writer.close()
        raw_writer.close()

    logger.info("Kamil ADC raw producer stopped")
    return 0


def _switch_from_model(model: SwitchModel) -> SwitchService:
    return SwitchService(
        name=model.name,
        positions=model.positions,
        mode=model.driver_mode,
        driver=model.driver,
        gpio_chip=model.gpio_chip,
        pin_a=model.pin_a,
        pin_b=model.pin_b,
        invert_logic=model.invert_logic,
        default_position=model.default_position,
    )


if __name__ == "__main__":
    raise SystemExit(main())
