import os
import subprocess
import csv
import json
import time

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FRAMES_DIR = os.path.join(BASE_DIR, "Captured_images")
SCRIPT_PATH = os.path.join(BASE_DIR, "ml_inference.py")
CSV_PATH = os.path.join(BASE_DIR, "inference_ablation_10.csv")

rows = []

def run_inference(image_list):
    start_time = time.perf_counter()

    result = subprocess.run(
        ["python", SCRIPT_PATH] + image_list,
        capture_output=True,
        text=True
    )

    runtime = time.perf_counter() - start_time

    if result.returncode != 0:
        print("Inference error:", result.stderr)
        return None, runtime

    try:
        output_json = json.loads(result.stdout.strip())
        return output_json.get("activity", ""), runtime
    except json.JSONDecodeError:
        print("Failed to parse JSON output:", result.stdout)
        return "", runtime


for folder_name in sorted(os.listdir(FRAMES_DIR)):
    folder_path = os.path.join(FRAMES_DIR, folder_name)

    if not os.path.isdir(folder_path):
        continue

    image_files = sorted(
        [f for f in os.listdir(folder_path) if f.lower().endswith(".jpg")]
    )

    if len(image_files) < 10:
        print(f"Skipping {folder_name} (not enough images)")
        continue

    first_image = os.path.join(folder_path, image_files[0])
    second_image = os.path.join(folder_path, image_files[1])
    third_image = os.path.join(folder_path, image_files[2])
    fourth_image = os.path.join(folder_path, image_files[3])
    fifth_image = os.path.join(folder_path, image_files[4])
    sixth_image = os.path.join(folder_path, image_files[5])
    seventh_image = os.path.join(folder_path, image_files[6])
    eighth_image = os.path.join(folder_path, image_files[7])
    nineth_image = os.path.join(folder_path, image_files[8])
    tenth_image = os.path.join(folder_path, image_files[9])

    print(f"Processing folder: {folder_name}")

    output1, runtime1 = run_inference([first_image])
    output2, runtime2 = run_inference([first_image, second_image])
    output3, runtime3 = run_inference([first_image, second_image, third_image])
    output4, runtime4 = run_inference([first_image, second_image, third_image, fourth_image])
    output5, runtime5 = run_inference([first_image, second_image, third_image, fourth_image, fifth_image])
    output10, runtime10 = run_inference([
        first_image, second_image, third_image, fourth_image, fifth_image,
        sixth_image, seventh_image, eighth_image, nineth_image, tenth_image
    ])

    rows.append([
        output1, runtime1,
        output2, runtime2,
        output3, runtime3,
        output4, runtime4,
        output5, runtime5,
        output10, runtime10
    ])

# ---------- Write CSV ----------
with open(CSV_PATH, "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([
        "first_image_only", "first_image_only_runtime",
        "first_two_images", "first_two_images_runtime",
        "first_three_images", "first_three_images_runtime",
        "first_four_images", "first_four_images_runtime",
        "first_five_images", "first_five_images_runtime",
        "all_ten_images", "all_ten_images_runtime"
    ])
    writer.writerows(rows)

print(f"\nSaved results to {CSV_PATH}")