"""Step 1: Ward hierarchical clustering; save the tree for steps 2 and 3."""
# ---------------- SETTINGS: edit these before running ----------------
DATA_FILE = 'data/clusterData_forWine.txt'
DELIMITER = None
X_COLUMNS = ['Mon_AvgSales', 'Freq_NumPurchPastYear', 'Recency_TimeSinceLastPchs']
ROW_IDENTIFIER = 'CustomerID'  # None labels leaves by original row number.
STANDARDIZE = True           # R agnes(stand=TRUE): mean ABSOLUTE deviation, not SD.
WORKFLOW_FOLDER = 'outputs/cluster_workflow'  # Use this same folder in steps 2 and 3.
MAX_OBSERVATIONS = 5000       # Pairwise distances use O(n²) memory; lower for small PCs.

from pathlib import Path
import json
import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import pdist
from model_tools import plt
from input_data import read_data


def main():
    base = Path(__file__).resolve().parent
    folder = base / WORKFLOW_FOLDER
    folder.mkdir(parents=True, exist_ok=True)
    data = read_data(base / DATA_FILE, DELIMITER)
    if not X_COLUMNS or len(set(X_COLUMNS)) != len(X_COLUMNS):
        raise ValueError('Choose a nonempty list of unique numeric predictors.')
    missing = set(X_COLUMNS + ([ROW_IDENTIFIER] if ROW_IDENTIFIER else [])) - set(data.columns)
    if missing:
        raise ValueError(f'Unknown columns: {missing}. Available: {list(data.columns)}')
    values = data[X_COLUMNS].apply(pd.to_numeric, errors='raise').astype(float)
    values = values.replace([np.inf, -np.inf], np.nan)
    complete = values.notna().all(axis=1)
    if not 3 <= complete.sum() <= MAX_OBSERVATIONS:
        raise ValueError('Need at least three complete rows; check MAX_OBSERVATIONS guard.')
    data.insert(0, '_source_row', np.arange(1, len(data)+1))
    # Snapshot all rows. Step 3 keeps excluded rows, with a blank cluster number.
    retained = data.loc[complete].copy()
    values = values.loc[complete]
    means = values.mean()
    scales = (values-means).abs().mean() if STANDARDIZE else pd.Series(1.0, index=X_COLUMNS)
    if (scales == 0).any() or (values.nunique() <= 1).any():
        raise ValueError('A clustering variable is constant. Remove it from X_COLUMNS.')
    scaled = (values-means)/scales if STANDARDIZE else values.copy()
    distances = pdist(scaled.to_numpy(), metric='euclidean')
    tree = linkage(distances, method='ward')
    # Only replace the workflow after the new input and hierarchy are valid.
    # Remove old evaluation/assignment outputs; they refer to the previous tree.
    for filename in ['cluster_evaluation.csv', 'cluster_details.csv',
                     'cluster_evaluation_shiny_layout.csv', 'silhouette_by_k.png',
                     'cluster_assignments.csv', 'cluster_profiles.csv', 'cluster_sizes.csv']:
        (folder / filename).unlink(missing_ok=True)
    data.to_csv(folder / 'source_data.csv', index=False)
    retained.to_csv(folder / 'retained_data.csv', index=False)
    data.loc[~complete].to_csv(folder / 'excluded_rows.csv', index=False)
    scaled.to_csv(folder / 'scaled_data.csv', index=False)
    pd.DataFrame({'mean':means, 'scale':scales}).to_csv(folder / 'scaling.csv', index_label='variable')
    pd.DataFrame(tree, columns=['child_1','child_2','height','size']).to_csv(folder / 'linkage.csv', index=False)
    pd.DataFrame({'distance': distances}).to_csv(folder / 'distances.csv', index=False)
    metadata = {'data_file': DATA_FILE, 'variables': X_COLUMNS, 'row_identifier':ROW_IDENTIFIER,
                'standardize':STANDARDIZE, 'n_retained':len(retained),
                'note':'Ward Euclidean distances; agnes-compatible mean absolute deviation scaling.'}
    (folder / 'settings.json').write_text(json.dumps(metadata, indent=2))
    labels = retained[ROW_IDENTIFIER].astype(str).tolist() if ROW_IDENTIFIER else retained['_source_row'].astype(str).tolist()
    plt.figure(figsize=(13, 6))
    dendrogram(tree, labels=labels, leaf_rotation=90, leaf_font_size=8 if len(labels)<100 else 4)
    plt.title('Ward hierarchical clustering'); plt.ylabel('Merge height')
    plt.tight_layout(); plt.savefig(folder / 'cluster_tree.png', dpi=160); plt.close()
    print(f'Retained {len(retained)} rows; excluded {int((~complete).sum())}.')
    print(f'Tree saved in {folder}. Next run cluster_evaluate.py.')


if __name__ == '__main__':
    main()
