import os
import json
import subprocess
import requests
import logging
import pandas as pd
import mysql.connector
from mysql.connector import Error

# --- CONFIGURAZIONE E LOGGING ---
def load_config(config_path):
    with open(config_path, encoding="utf-8") as f:
        return json.load(f)

def setup_logging(log_dir, log_file, debug=False):
    os.makedirs(log_dir, exist_ok=True)
    log_path = os.path.join(log_dir, log_file)
    logging.basicConfig(
        level=logging.DEBUG if debug else logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[
            logging.FileHandler(log_path),
            logging.StreamHandler()
        ]
    )

# --- ESTRAZIONE DATI DAI FILE MDB ---
def extract_data_from_mdb(mdb_path, tables):
    data = {}
    for table in tables:
        try:
            # Use mdb-export to extract the table data
            result = subprocess.run(
                ["mdb-export", mdb_path, table],
                capture_output=True,
                text=True,
                check=True
            )
            # Convert the CSV output to a DataFrame
            df = pd.read_csv(pd.compat.StringIO(result.stdout))
            data[table] = df.to_dict(orient='records')
        except subprocess.CalledProcessError as e:
            logging.error(f"Error extracting table {table} from {mdb_path}: {e}")
    return data

# --- INVIO DATI ALL'API ---
def send_to_api(endpoint, token, payload):
    headers = {
        'Authorization': f'Bearer {token}',
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
    try:
        response = requests.post(endpoint, headers=headers, json=payload)
        response.raise_for_status()
        logging.info(f"Data sent successfully to {endpoint}: {response.json()}")
    except requests.exceptions.RequestException as e:
        logging.error(f"Error sending data to {endpoint}: {e}")

# --- PROCESSO PRINCIPALE ---
def main():
    base_dir = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(base_dir, "agent_config.json")
    cfg = load_config(config_path)

    setup_logging(cfg["LogDirectory"], cfg.get("LogFile", "agent.log"), cfg.get("Debug", False))

    input_directory = cfg["InputDirectory"]
    api_base_url = cfg["ApiBaseUrl"]
    token = cfg["AdminToken"]

    # Define the tables to extract based on previous data cleaning efforts
    tables_to_extract = ["stabili", "fornitori", "condomin"]

    # Process each MDB file in the input directory
    for root, _, files in os.walk(input_directory):
        for file in files:
            if file.endswith('.mdb'):
                mdb_path = os.path.join(root, file)
                logging.info(f"Processing MDB file: {mdb_path}")

                # Extract data from the MDB file
                extracted_data = extract_data_from_mdb(mdb_path, tables_to_extract)

                # Send each table's data to the corresponding API endpoint
                for table, records in extracted_data.items():
                    if table == "stabili":
                        endpoint = f"{api_base_url}/api/v1/import/condominio"
                    elif table == "fornitori":
                        endpoint = f"{api_base_url}/api/v1/import/fornitore"
                    elif table == "condomin":
                        endpoint = f"{api_base_url}/api/v1/import/anagrafica"
                    else:
                        continue

                    for record in records:
                        send_to_api(endpoint, token, record)

if __name__ == "__main__":
    main()