# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 23:44:22 2026

@author: scige
"""
#%%
import sys
import logging
import numpy as np
import pyopencl as cl
from datetime import datetime
#%%
# --- CONFIGURAZIONE LOGGING (Log4Python style) ---
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler(sys.stderr), logging.FileHandler("app.log")]
)
logger = logging.getLogger("MainApp")

# --- 1. DEMO I/O E FORMATTING ---
def demo_basics():
    ora = datetime.now().strftime("%H:%M:%S")
    # I/O Binario ed Hex
    dati_raw = b'\xde\xad\xbe\xef'
    logger.info(f"Avvio demo alle {ora}")
    print(f"Dati Binari (Hex): {dati_raw.hex()}")
    
    # Print personalizzato (sep, end, file)
    with open("test_output.txt", "w") as f:
        print("PYTHON", "I/O", "DEMO", sep=" | ", end=" \n", file=f)

# --- 2. CALCOLO ACCELERATO (OpenCL per AMD/NVIDIA/Intel) ---
def demo_opencl():
    try:
        # Dati di test (float32 è cruciale per molte GPU)
        a_cpu = np.array([1, 2, 3, 4], dtype=np.float32)
        
        # Inizializzazione
        ctx = cl.create_some_context()
        queue = cl.CommandQueue(ctx)
        mf = cl.mem_flags

        # CORREZIONE TYPEERROR: firma corretta (ctx, flags, size, hostbuf)
        # Passiamo hostbuf come argomento nominato per chiarezza
        a_gpu = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a_cpu)
        res_gpu = cl.Buffer(ctx, mf.WRITE_ONLY, size=a_cpu.nbytes)

        # Kernel C-Like
        kernel = """
        __kernel void square(__global const float *a, __global float *res) {
            int i = get_global_id(0);
            res[i] = a[i] * a[i];
        }
        """
        prg = cl.Program(ctx, kernel).build()
        prg.square(queue, a_cpu.shape, None, a_gpu, res_gpu)

        # Recupero dati
        res_cpu = np.empty_like(a_cpu)
        cl.enqueue_copy(queue, res_cpu, res_gpu)
        
        logger.info(f"Calcolo GPU completato: {res_cpu}")
        
    except Exception as e:
        logger.error("Errore durante il calcolo GPU", exc_info=True)

if __name__ == "__main__":
    demo_basics()
    demo_opencl()