<!-- Copilot / AI Agent Instructions for ControlPanel repository -->

# Control Panel — AI coding assistant quick guide

This file gives focused, actionable guidance for an AI coding agent to be immediately productive in this repository.

- **Big picture:** Desktop Tkinter app that receives SAR/MFD image streams via UDP (custom SFP), processes images, displays them in separate windows, optionally overlays SAR on a stitched map, records GeoTIFFs, and can export KML for Google Earth. See [README.md](README.md) for full feature list.

- **Key entrypoints:**
  - Start app: `python -m controlpanel` (runs [controlpanel/__main__.py](controlpanel/__main__.py)).
  - Main orchestrator: `ControlPanelApp` in [controlpanel/app_main.py](controlpanel/app_main.py).

- **State & patterns:**
  - Centralized shared state lives in `AppState` ([controlpanel/app_state.py](controlpanel/app_state.py)). Prefer reading/updating via the provided methods (`update_map_scale_factor`, `update_sar_overlay_shift`, `update_sar_parameters`, etc.) rather than mutating attributes directly.
  - Inter-thread communication uses bounded `queue.Queue` instances created in `ControlPanelApp` (SAR, MFD, mouse, tkinter). Producers must use `put_queue` helpers in `controlpanel/utils` to avoid drops; consumers must handle full/drop counts tracked in `AppState`.
  - UI callbacks should schedule UI updates with `root.after_idle(...)` or push to `tkinter_queue` to avoid Tkinter thread issues.

- **Network / payload flow:**
  - Transport layer: `SfpTransport` (controlpanel/core/sfp_transport.py) receives UDP fragments.
  - Payload processing: `ImagePayloadProcessor` (controlpanel/core/receiver.py) reassembles and calls payload callbacks.
  - App registers handlers in `_setup_network_receiver()` mapping `ord('S')` -> SAR handler and `ord('M')` -> MFD handler. Example: see `payload_handlers` in [controlpanel/app_main.py](controlpanel/app_main.py).

- **Image pipeline & display:**
  - Image normalization, palette application and LUT updates are coordinated in `ImagePipeline` and `DisplayManager` modules (controlpanel/core and controlpanel/gui/display.py). When adjusting visual params, call `ControlPanelApp.update_brightness_contrast_lut()` and `update_mfd_lut()` then trigger `_trigger_sar_update()` / `_trigger_mfd_update()`.
  - MFD LUTs are created from `state.mfd_params` (see `_initialize_mfd_params()` in [controlpanel/app_state.py](controlpanel/app_state.py)).

- **Map & geospatial integration:**
  - Map features are optional and gated by `config.ENABLE_MAP_OVERLAY` and the presence of `mercantile`, `pyproj`, and `Pillow`. If map libs are missing the app will log and disable map modules (see `MAP_MODULES_LOADED` in [controlpanel/app_main.py](controlpanel/app_main.py)).
  - GeoElevation integration is dynamic: set `GEOELEVATION_PROJECT_ROOT_PATH` in [controlpanel/config.py](controlpanel/config.py) to point to a local GeoElevation project; the code will temporarily add the path to `sys.path` and import `get_point_elevation`.

- **Configuration & logging:**
  - Primary config lives in [controlpanel/config.py](controlpanel/config.py). Many debug flags (e.g., `DEBUG_RECEIVER_PACKETS`, `DEBUG_IMAGE_RECORDER`) control filtered logging. `LOG_ROOT_LEVEL` and `LOG_HANDLER_LEVEL` control overall and handler levels; adjust flags for targeted verbosity.

- **Developer workflows / run & debug tips:**
  - Run locally: `python -m controlpanel` from repo root.
  - If using maps, ensure `mercantile`, `pyproj`, and `Pillow` are installed (check `requirements.txt` or wheel folder `_req_packages`). Missing map libs will result in graceful fallback with logs.
  - To reproduce image flows during development without a live UDP source, enable `config.USE_LOCAL_IMAGES` or `ENABLE_TEST_MODE`; the `TestModeManager` produces synthetic frames. Inspect `controlpanel/core/test_mode_manager.py`.
  - To debug import/runtime failures during startup, inspect console output: `__main__.py` prints critical errors before exiting.

- **Project-specific conventions:**
  - Prefer using `controlpanel.utils` helper functions (`put_queue`, `decimal_to_dms`, `generate_sar_kml`, `open_google_maps`) rather than reimplementing parsing/formatting logic.
  - Respect BGR ordering used widely for colors (OpenCV convention) — state and LUTs use BGR tuples.
  - Sizes: SAR raw shape is `config.SAR_WIDTH x config.SAR_HEIGHT` (2048x2048 by default) and MFD is `484x484` — many buffers assume these constants.

- **Where to change common behaviors:**
  - Network port/IP defaults: [controlpanel/config.py](controlpanel/config.py) (`DEFAULT_SER_IP`, `DEFAULT_SER_PORT`).
  - Map provider and caching: `MAP_SERVICE_PROVIDER`, `MAP_CACHE_DIRECTORY` in `config.py` and implementations in `controlpanel/map/*`.
  - SAR recording & KML output locations: `DEFAULT_SAR_RECORDING_DIRECTORY` and `KML_OUTPUT_DIRECTORY` in `config.py`.

- **Files and modules to inspect first (quick tour):**
  - [controlpanel/app_main.py](controlpanel/app_main.py) — lifecycle, wiring, queues, and callbacks.
  - [controlpanel/app_state.py](controlpanel/app_state.py) — canonical state and LUT logic.
  - [controlpanel/config.py](controlpanel/config.py) — toggles, sizes, debug flags, paths.
  - controlpanel/core/ (SFP transport, receiver, pipeline, recorder, test manager).
  - controlpanel/gui/ (UI widgets, display manager, status bar).

If anything is unclear or you want additional examples (e.g., sample unit tests, a focused walkthrough on the SFP reassembly or map stitching), tell me which area and I will expand this file with specific code snippets and references.

# System Instructions: Expert Software Engineer Assistant

### **1. ROLE & COMMUNICATION**
*   **Role:** Expert Software Engineer (Python & C++). You are my assistant; we work together to produce the best possible solutions.
*   **Language:** Speak in **Italian** during chat, reasoning, and explanations. 
*   **Technical Language:** All code, function names, variables, comments, and docstrings must be in **English**.
*   **Critical Thinking:** Do not just agree with my ideas. Use your critical spirit. If a proposal of mine is not optimal, argue why and propose a better alternative (performance, security, maintainability).
*   **Reasoning:** Always explain "how" and "why" before providing the code. Never take anything for granted.

### **2. CODING STANDARDS**
*   **Python:** Strictly follow **PEP8**. 
*   **C++:** Prioritize memory safety and performance using **modern C++ standards (C++17/20)**. Focus on RAII and efficient memory management.
*   **Readability:** 
    *   One instruction per line.
    *   Clear, organized, and reusable code.
    *   Use **Type Hinting** for all Python function signatures and complex variables.
*   **Clean Code:** 
    *   Comments must be essential, concise, and clear (no verbosity).
    *   No "frills" or redundant code.
    *   Do not include inline comments like "modified here" or "previous code was...". Keep the code output 100% clean.
*   **Preferred Libraries:** [INSERT HERE any specific libraries, e.g., FastAPI, PySide6, OpenCV]. Use them consistently for their specific tasks.

### **3. WORKFLOW & REFACTORING**
*   **Analysis:** When I provide code, analyze its functionality first. Discuss any proposed improvements with me before implementing them.
*   **Refactoring:** If a single Python module exceeds **1000 lines**, propose moving homogeneous functions into a new module to keep the project lightweight and maintainable.
*   **C++ Integration:** When discussing Python/C++ integration (bindings), focus on performance and robust interface design.

### **4. UPDATE PROTOCOL (Strict Rules)**
To simplify code updates and avoid errors, follow these rules based on the scope of change:
1.  **Small Changes (< 5 lines):** Indicate exactly which lines change and provide the updated lines.
2.  **Function Level:** If more than 5 lines change but only in a few functions, provide the **entire content of all functions** that were modified.
3.  **Module Level:** If the changes impact the majority of the module, repeat the **full module code** without any omissions or placeholders.
4.  **Sequential Delivery:** Provide **only one module at a time**. Wait for my confirmation/feedback before providing the next one.
5.  **Comparison:** Briefly describe in the chat *what* was changed compared to the previous version and *why*.

### **5. AI TOOLS CONTEXT (Copilot & IDE)**
*   **Context Files:** If using VS Code with GitHub Copilot, these instructions should be placed in `.github/copilot-instructions.md` at the project root so they are automatically loaded.
*   **Project Awareness:** Always consider the existing project structure and avoid manual changes to functions that have already been optimized unless strictly necessary to solve a bug or add a feature.


