================================================================================
EXPERIMENT 5: APRIORI ALGORITHM (FREQUENT PATTERNS ONLY)
No ML libraries - Pure Python Loops - Supports Text List and One-Hot Formats
================================================================================

import os
from itertools import combinations
import numpy as np
import pandas as pd

# ===== USER SETTINGS =====
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "transactions_list.csv")
MIN_SUPPORT = 0.3      # Minimum support ratio (e.g. 0.3 = 30%)
GENERATE_RULES = False  # Set to False for 'Frequent Patterns Only', True for 'Association Rules'
MIN_CONFIDENCE = 0.5   # Minimum confidence threshold (only used if GENERATE_RULES=True)

# 1. Load transactions into list of sets (Supports Delimited text and One-Hot)
df = pd.read_csv(FILE_PATH)
non_id = [c for c in df.columns if "id" not in c.lower()]

if len(non_id) >= 2 and df[non_id].isin([0, 1]).all().all():
    # One-Hot Matrix format
    transactions = [frozenset(c for c in non_id if row[c] == 1) for _, row in df.iterrows()]
else:
    # Delimited text format
    col = non_id[0]
    delim = ';' if ';' in str(df[col].iloc[0]) else ','
    transactions = [frozenset(x.strip() for x in str(r).split(delim) if x.strip()) for r in df[col].dropna()]

n = len(transactions)
min_count = int(np.ceil(MIN_SUPPORT * n)) if 0.0 < MIN_SUPPORT <= 1.0 else int(MIN_SUPPORT)
print(f"Loaded {n} transactions from {os.path.basename(FILE_PATH)}")
print(f"Min Support Threshold = {min_count} transactions ({min_count/n:.1%})\n")

def support(itemset):
    return sum(1 for t in transactions if itemset.issubset(t))

# 2. Generate L1 (Frequent 1-itemsets)
items = sorted(list({item for t in transactions for item in t}))
c1 = [frozenset([i]) for i in items]
l_curr = {c: support(c) for c in c1 if support(c) >= min_count}

all_frequent = dict(l_curr)
k = 1

# 3. Iterative Ck and Lk generation
while l_curr:
    print(f"--- Frequent {k}-Itemsets (L{k}) ---")
    for itemset, cnt in sorted(l_curr.items(), key=lambda x: sorted(list(x[0]))):
        print(f"{{{', '.join(sorted(itemset))}}} -> Support: {cnt}/{n} ({cnt/n:.1%})")
        
    lk_list = list(l_curr.keys())
    ck = {lk_list[i] | lk_list[j] for i in range(len(lk_list)) for j in range(i + 1, len(lk_list)) if len(lk_list[i] | lk_list[j]) == k + 1}
    l_next = {c: support(c) for c in ck if support(c) >= min_count}
    
    all_frequent.update(l_next)
    l_curr = l_next
    k += 1

print(f"\nTotal Frequent Patterns: {len(all_frequent)}")

# 4. Association Rules (Optional - Enabled if GENERATE_RULES = True)
if GENERATE_RULES:
    print(f"\n--- ASSOCIATION RULES (Min Confidence >= {MIN_CONFIDENCE:.1%}) ---")
    rule_count = 0
    for itemset in all_frequent:
        if len(itemset) >= 2:
            for r in range(1, len(itemset)):
                for left in combinations(sorted(itemset), r):
                    A = frozenset(left)
                    B = itemset - A
                    conf = support(itemset) / support(A)
                    if conf >= MIN_CONFIDENCE:
                        rule_count += 1
                        print(f"{{{', '.join(sorted(A))}}} -> {{{', '.join(sorted(B))}}} | Confidence = {conf:.2%}")
    print(f"Total Association Rules Generated: {rule_count}")
else:
    print("Association rules skipped (GENERATE_RULES = False as per class instruction).")
