#!/usr/bin/env python3
"""
POLYGON REGION COHERENCE ANALYSIS (USER-CONTROLLED)
=====================================================

Analyzes coherence across selected polygon regions (cells, rows, columns)
and generates pairwise compatibility scores for visual composition.

Configuration:
- Edit cells_to_analyze.json to specify which cells to analyse
- Shows clear logging of what data is being used
- Validates all files exist before processing

Pipeline:
1. Load configuration from cells_to_analyze.json
2. Validate CSV data directory and cell files
3. Load coherence values from specified cells only
4. Calculate emergence signatures as regions aggregate
5. Generate pairwise combinations for selected cells
6. Score pairs for high-coherence (compatible) and low-coherence (complementary)
7. Output: pair_coherence_composition.json with categorised pairs

use 3x4-coherence-analysis
"""

import os
import sys
import json
import pandas as pd
import numpy as np
from pathlib import Path
from itertools import combinations
from typing import Dict, List, Tuple
from scipy.stats import linregress

try:
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
except Exception:
    plt = None

# ============================================================================
# CONFIGURATION LOADING
# ============================================================================

CONFIG_FILE = Path(__file__).parent.parent / "config" / "cells_to_analyze.json"

print("=" * 100)
print("POLYGON REGION COHERENCE ANALYSIS (USER-CONTROLLED)")
print("=" * 100)
print("")

# Load configuration
print("STEP 0: LOAD CONFIGURATION")
print("-" * 100)

if not CONFIG_FILE.exists():
    print(f"✗ ERROR: Configuration file not found: {CONFIG_FILE}")
    print("  Create it with: cells_to_analyze.json")
    sys.exit(1)

with open(CONFIG_FILE, 'r') as f:
    config = json.load(f)

_csv_dir_raw = config['analysis_config']['csv_directory']
_csv_dir_path = Path(_csv_dir_raw)
# Resolve relative paths against the config file's directory so the workflow
# folder is portable regardless of where the script is run from.
if _csv_dir_path.is_absolute():
    CSV_DIR = _csv_dir_path
else:
    CSV_DIR = CONFIG_FILE.parent / _csv_dir_path
SELECTED_CELLS = config['analysis_config']['selected_cells']
OUTPUT_DIR = Path(__file__).parent.parent / "config"

print(f"✓ Configuration loaded: {CONFIG_FILE}")
print(f"  CSV directory: {CSV_DIR}")
print(f"  Selected cells: {len(SELECTED_CELLS)} cells")
print(f"  Cell list: {SELECTED_CELLS}")
print("")

# ============================================================================
# DATA VALIDATION
# ============================================================================

print("STEP 1: VALIDATE DATA SOURCES")
print("-" * 100)

if not CSV_DIR.exists():
    print(f"✗ ERROR: CSV directory not found: {CSV_DIR}")
    sys.exit(1)

print(f"✓ CSV directory exists: {CSV_DIR}")

# Check which cell files actually exist
found_files = {}
missing_files = []

for cell in SELECTED_CELLS:
    filename = f"cell_{cell}_full_vectors_coordinates.csv"
    filepath = CSV_DIR / filename
    
    if filepath.exists():
        found_files[cell] = filepath
        print(f"  ✓ {cell}: FOUND")
    else:
        missing_files.append(cell)
        print(f"  ✗ {cell}: NOT FOUND")

print("")
print(f"Summary: {len(found_files)} files found, {len(missing_files)} missing")

if missing_files:
    print(f"⚠ WARNING: Missing data for: {missing_files}")
    if len(found_files) == 0:
        print("✗ ERROR: No cell files found! Check CSV_DIRECTORY setting.")
        sys.exit(1)
    else:
        print(f"Continuing with {len(found_files)} available cells...")
else:
    print("✓ All selected cell files available")

print("")

# ============================================================================
# GRID STRUCTURE
# ============================================================================

GRID_COLS = 3
GRID_ROWS = 4
ROWS = [f"r{row}" for row in range(1, GRID_ROWS + 1)]
COLUMNS = [f"c{col}" for col in range(1, GRID_COLS + 1)]

print(f"Grid structure: {GRID_COLS} columns × {GRID_ROWS} rows")
print(f"Cells being analysed: {list(found_files.keys())}")
print("")

# ============================================================================
# COHERENCE CALCULATION FROM VECTORS
# ============================================================================

def calculate_coherence_from_coords(coords_list: List[Tuple]) -> Dict:
    """
    Calculate coherence metrics from line segment endpoint coordinates.
    
    Args:
        coords_list: list of (x1, y1, x2, y2) tuples representing line segments
    
    Returns:
        {
            'vectors': count of line segments,
            'clustering': max_dist / min_dist from centroid,
            'dispersion': std_dev / mean distance,
            'coherence': clustering / (1 + dispersion)
        }
    """
    # Accept singleton cells (one vector row) as valid input.
    if len(coords_list) < 1:
        return None

    # Extract all endpoints from line segments
    points = []
    for x1, y1, x2, y2 in coords_list:
        points.append([x1, y1])
        points.append([x2, y2])

    points = np.array(points)
    centroid = np.mean(points, axis=0)

    # Calculate distances from centroid
    distances = np.linalg.norm(points - centroid, axis=1)

    if len(distances) < 2:
        return None

    # Degenerate case: all endpoints collapse to one location.
    # Keep the record but mark coherence as zero rather than failing the run.
    if distances.max() == 0:
        return {
            'vectors': len(coords_list),
            'clustering': 0.0,
            'dispersion': 0.0,
            'coherence': 0.0
        }

    clustering = distances.max() / distances.min() if distances.min() > 0 else 0
    mean_dist = distances.mean()
    dispersion = (distances.std() / mean_dist) if mean_dist > 0 else 0
    coherence = clustering / (1 + dispersion)

    return {
        'vectors': len(coords_list),
        'clustering': round(clustering, 6),
        'dispersion': round(dispersion, 6),
        'coherence': round(coherence, 4)
    }

def load_csv_vectors(filepath: Path) -> List[Tuple]:
    """Load vector coordinates from CSV file."""
    try:
        df = pd.read_csv(filepath)
        coords = df[['x1', 'y1', 'x2', 'y2']].values.tolist()
        return coords
    except Exception as e:
        print(f"  ERROR loading {filepath}: {e}")
        return None

# ============================================================================
# REGION COHERENCE ANALYSIS
# ============================================================================

def analyze_cell_coherence(found_files: Dict) -> Dict[str, Dict]:
    """Analyze coherence for each cell in found_files (user-selected)."""
    print("STEP 2: CELL-LEVEL COHERENCE (user-selected cells)")
    print("-" * 100)
    
    cell_coherence = {}
    skipped_cells = []
    
    for cell_name, filepath in sorted(found_files.items()):
        coords = load_csv_vectors(filepath)
        if coords:
            metrics = calculate_coherence_from_coords(coords)
            if metrics is None:
                skipped_cells.append(cell_name)
                print(f"  ⚠ {cell_name:8} skipped: insufficient/degenerate geometry for coherence calculation")
                continue
            cell_coherence[cell_name] = metrics
            print(f"  {cell_name:8} → coherence = {metrics['coherence']:.4f} ({metrics['vectors']} vectors)")
        else:
            skipped_cells.append(cell_name)
            print(f"  ⚠ {cell_name:8} skipped: CSV could not be loaded")
    
    print(f"\n  Total cells analysed: {len(cell_coherence)}")
    if skipped_cells:
        print(f"  Skipped cells: {skipped_cells}")
    if cell_coherence:
        print(f"  Average coherence: {np.mean([c['coherence'] for c in cell_coherence.values()]):.4f}")
    print("")
    
    return cell_coherence

def analyze_row_coherence() -> Dict[str, Dict]:
    """Analyze coherence for each row (aggregate of 3 cells)."""
    print("STEP 2: ROW-LEVEL COHERENCE (3 cells per row)")
    print("-" * 90)
    
    row_coherence = {}
    skipped_rows = []

    row_files = {
        row: CSV_DIR / f"row_{row}_full_vectors_coordinates.csv"
        for row in range(1, GRID_ROWS + 1)
    }
    existing_rows = [row for row, path in row_files.items() if path.exists()]

    if not existing_rows:
        print("  ℹ No row aggregate CSV files found; skipping row-level coherence analysis")
        print("")
        return row_coherence
    
    for row in range(1, GRID_ROWS + 1):
        filename = f"row_{row}_full_vectors_coordinates.csv"
        filepath = row_files[row]
        
        if not filepath.exists():
            print(f"  ⚠ {filename} not found")
            continue
        
        coords = load_csv_vectors(filepath)
        if coords:
            metrics = calculate_coherence_from_coords(coords)
            if metrics is None:
                skipped_rows.append(row)
                print(f"  ⚠ r{row}: skipped due to insufficient/degenerate geometry")
                continue
            row_key = f"r{row}"
            row_coherence[row_key] = metrics
            print(f"  {row_key:8} → coherence = {metrics['coherence']:.4f} ({metrics['vectors']} vectors)")
    
    print(f"\n  Total rows analysed: {len(row_coherence)}")
    if skipped_rows:
        print(f"  Skipped rows: {skipped_rows}")
    if row_coherence:
        print(f"  Average coherence: {np.mean([r['coherence'] for r in row_coherence.values()]):.4f}")
    print("")
    
    return row_coherence

def analyze_column_coherence() -> Dict[str, Dict]:
    """Analyze coherence for each column (aggregate of 4 cells)."""
    print("STEP 3: COLUMN-LEVEL COHERENCE (4 cells per column)")
    print("-" * 90)
    
    column_coherence = {}
    skipped_columns = []

    col_file_candidates = {}
    for col in range(1, GRID_COLS + 1):
        primary = CSV_DIR / f"column_{col}_full_vectors_coordinates.csv"
        alternate = CSV_DIR / f"col_{col}_full_vectors_coordinates.csv"
        col_file_candidates[col] = (primary, alternate)

    existing_cols = [
        col for col, (primary, alternate) in col_file_candidates.items()
        if primary.exists() or alternate.exists()
    ]

    if not existing_cols:
        print("  ℹ No column aggregate CSV files found; skipping column-level coherence analysis")
        print("")
        return column_coherence
    
    for col in range(1, GRID_COLS + 1):
        # Try different filename patterns
        filename = f"column_{col}_full_vectors_coordinates.csv"
        filepath = col_file_candidates[col][0]
        
        # Alternative pattern
        if not filepath.exists():
            filename = f"col_{col}_full_vectors_coordinates.csv"
            filepath = col_file_candidates[col][1]
        
        if not filepath.exists():
            print(f"  ⚠ Column {col} file not found (tried: column_*.csv, col_*.csv)")
            continue
        
        coords = load_csv_vectors(filepath)
        if coords:
            metrics = calculate_coherence_from_coords(coords)
            if metrics is None:
                skipped_columns.append(col)
                print(f"  ⚠ c{col}: skipped due to insufficient/degenerate geometry")
                continue
            col_key = f"c{col}"
            column_coherence[col_key] = metrics
            print(f"  {col_key:8} → coherence = {metrics['coherence']:.4f} ({metrics['vectors']} vectors)")
    
    print(f"\n  Total columns analysed: {len(column_coherence)}")
    if skipped_columns:
        print(f"  Skipped columns: {skipped_columns}")
    if column_coherence:
        print(f"  Average coherence: {np.mean([c['coherence'] for c in column_coherence.values()]):.4f}")
    print("")
    
    return column_coherence

def calculate_emergence_signatures(cell_coherence: Dict,
                                  row_coherence: Dict,
                                  column_coherence: Dict) -> Dict:
    """
    Calculate emergence signatures: coherence degradation patterns across scales.
    Key insight: as spatial constraint decreases (cell → row → column),
    coherence should degrade predictably due to increased polygon density variation.
    """
    print("STEP 4: EMERGENCE SIGNATURES (coherence degradation across scales)")
    print("-" * 90)
    
    signatures = {}
    
    # For each cell, track coherence at cell level vs aggregated levels
    for col in range(1, GRID_COLS + 1):
        for row in range(1, GRID_ROWS + 1):
            cell_key = f"c{col}r{row}"
            row_key = f"r{row}"
            col_key = f"c{col}"
            
            if cell_key in cell_coherence:
                cell_coh = cell_coherence[cell_key]['coherence']
                row_coh = row_coherence.get(row_key, {}).get('coherence', None)
                col_coh = column_coherence.get(col_key, {}).get('coherence', None)
                
                signatures[cell_key] = {
                    'cell_level': cell_coh,
                    'row_level': row_coh,
                    'column_level': col_coh,
                    'degradation_pattern': []
                }
                
                # Calculate degradation
                if row_coh:
                    deg_to_row = ((cell_coh - row_coh) / cell_coh * 100) if cell_coh != 0 else 0
                    signatures[cell_key]['degradation_pattern'].append({
                        'from': 'cell',
                        'to': 'row',
                        'change_percent': round(deg_to_row, 2)
                    })
                
                if col_coh:
                    deg_to_col = ((cell_coh - col_coh) / cell_coh * 100) if cell_coh != 0 else 0
                    signatures[cell_key]['degradation_pattern'].append({
                        'from': 'cell',
                        'to': 'column',
                        'change_percent': round(deg_to_col, 2)
                    })
    
    print(f"  Calculated signatures for {len(signatures)} cell regions")
    
    # Show examples
    for i, (key, sig) in enumerate(list(signatures.items())[:3]):
        print(f"    {key}: cell={sig['cell_level']:.4f} → row={sig['row_level']} → col={sig['column_level']}")
    print("    ...")
    print("")
    
    return signatures

# ============================================================================
# PAIRWISE COHERENCE SCORING
# ============================================================================

def calculate_diversity_coefficient(cell1_coherence: float,
                                   cell2_coherence: float) -> float:
    """
    Calculate normalized diversity coefficient σ in [0, 1].
    σ = |c1 - c2| / max(c1, c2)
    """
    denom = max(cell1_coherence, cell2_coherence)
    if denom <= 0:
        return 0.0
    return abs(cell1_coherence - cell2_coherence) / denom


def calculate_diversity_coefficient_std(cell1_coherence: float,
                                        cell2_coherence: float) -> float:
    """Legacy diversity metric retained for transition comparison."""
    return float(np.std([cell1_coherence, cell2_coherence]))

def score_pair_compatibility(cell1_coherence: float,
                            cell2_coherence: float) -> Tuple[float, str]:
    """
    Score pair compatibility for two regions.
    
    Returns:
        (score, category)
        - score: 0-1 (1 = perfectly compatible, 0 = incompatible)
        - category: "high_coherence_compatible" or "low_coherence_complementary"
    """
    # Compatibility score: measure of how similar the coherence values are
    similarity = 1.0 - (abs(cell1_coherence - cell2_coherence) / (max(cell1_coherence, cell2_coherence) + 1e-6))
    
    # Category determination
    if similarity > 0.95:  # Very similar coherence → high compatibility
        return (similarity, "high_coherence_compatible")
    elif similarity < 0.70:  # Different coherence → complementary
        return (similarity, "low_coherence_complementary")
    else:
        return (similarity, "moderate_mixed")

def generate_pair_combinations(cell_coherence: Dict) -> Dict:
    """Generate all pairwise region combinations and score them."""
    print("STEP 5: PAIRWISE COMBINATION ANALYSIS")
    print("-" * 90)
    
    high_coherence_pairs = []
    low_coherence_pairs = []
    moderate_pairs = []
    
    cells = sorted(list(cell_coherence.keys()))
    
    # Generate all possible cross-boundary pairs
    for i, cell1 in enumerate(cells):
        for cell2 in cells[i+1:]:
            coh1 = cell_coherence[cell1]['coherence']
            coh2 = cell_coherence[cell2]['coherence']
            diversity_norm = calculate_diversity_coefficient(coh1, coh2)
            diversity_std = calculate_diversity_coefficient_std(coh1, coh2)
            
            score, category = score_pair_compatibility(coh1, coh2)
            
            pair_data = {
                'pair': f"{cell1} → {cell2}",
                'cell1': cell1,
                'cell2': cell2,
                'coherence1': round(coh1, 4),
                'coherence2': round(coh2, 4),
                'compatibility_score': round(score, 4),
                'diversity_coefficient': round(diversity_norm, 6),
                'diversity_coefficient_std': round(diversity_std, 6),
                'category': category,
                'vectors1': cell_coherence[cell1]['vectors'],
                'vectors2': cell_coherence[cell2]['vectors']
            }
            
            if category == "high_coherence_compatible":
                high_coherence_pairs.append(pair_data)
            elif category == "low_coherence_complementary":
                low_coherence_pairs.append(pair_data)
            else:
                moderate_pairs.append(pair_data)
    
    # Sort by score
    high_coherence_pairs.sort(key=lambda x: x['compatibility_score'], reverse=True)
    low_coherence_pairs.sort(key=lambda x: x['diversity_coefficient'], reverse=True)
    
    # -----------------------------------------------------------------------
    # Compute linear regression: σ → coherence_loss (derived from actual data)
    # coherence_loss per pair = baseline_coherence − mean(coh1, coh2)
    # where baseline = maximum single-cell coherence across all pairs
    # -----------------------------------------------------------------------
    all_pairs = high_coherence_pairs + low_coherence_pairs + moderate_pairs
    all_coh_vals = [p['coherence1'] for p in all_pairs] + [p['coherence2'] for p in all_pairs]
    baseline_coherence = max(all_coh_vals) if all_coh_vals else 1.0
    
    sigmas = np.array([p['diversity_coefficient'] for p in all_pairs])
    sigmas_std = np.array([p['diversity_coefficient_std'] for p in all_pairs])
    losses = np.array([baseline_coherence - (p['coherence1'] + p['coherence2']) / 2
                       for p in all_pairs])
    
    if len(sigmas) >= 2 and sigmas.std() > 0:
        reg = linregress(sigmas, losses)
        regression_formula = {
            'slope': round(float(reg.slope), 6),
            'intercept': round(float(reg.intercept), 6),
            'r_squared': round(float(reg.rvalue ** 2), 6),
            'p_value': round(float(reg.pvalue), 6),
            'std_err': round(float(reg.stderr), 6),
            'baseline_coherence': round(float(baseline_coherence), 6),
            'n_pairs': len(all_pairs),
            'description': (
                f'Coherence Loss = {reg.slope:.4f}σ '
                f'{"+" if reg.intercept >= 0 else ""}{reg.intercept:.4f}'
            ),
            'note': 'Computed by linear regression from all pairs in this run using normalized diversity'
        }
    else:
        regression_formula = {
            'slope': None,
            'intercept': None,
            'r_squared': None,
            'baseline_coherence': round(float(baseline_coherence), 6),
            'n_pairs': len(all_pairs),
            'note': 'Insufficient pair variance to compute regression'
        }

    if len(sigmas_std) >= 2 and sigmas_std.std() > 0:
        reg_std = linregress(sigmas_std, losses)
        regression_formula_std_legacy = {
            'slope': round(float(reg_std.slope), 6),
            'intercept': round(float(reg_std.intercept), 6),
            'r_squared': round(float(reg_std.rvalue ** 2), 6),
            'p_value': round(float(reg_std.pvalue), 6),
            'std_err': round(float(reg_std.stderr), 6),
            'baseline_coherence': round(float(baseline_coherence), 6),
            'n_pairs': len(all_pairs),
            'description': (
                f'Coherence Loss = {reg_std.slope:.4f}σ_std '
                f'{"+" if reg_std.intercept >= 0 else ""}{reg_std.intercept:.4f}'
            ),
            'note': 'Legacy comparison: std-based diversity regression'
        }
    else:
        regression_formula_std_legacy = {
            'slope': None,
            'intercept': None,
            'r_squared': None,
            'baseline_coherence': round(float(baseline_coherence), 6),
            'n_pairs': len(all_pairs),
            'note': 'Insufficient pair variance to compute std-based regression'
        }

    print(f"  Total pairs generated: {len(cells) * (len(cells) - 1) // 2}")
    print(f"  High-coherence (compatible):    {len(high_coherence_pairs)} pairs")
    print(f"  Low-coherence (complementary):  {len(low_coherence_pairs)} pairs")
    print(f"  Moderate/Mixed:                 {len(moderate_pairs)} pairs")
    
    if regression_formula.get('slope') is not None:
        print(f"  Regression formula (computed):  {regression_formula['description']}")
        print(f"  R² = {regression_formula['r_squared']:.4f}  |  n = {regression_formula['n_pairs']} pairs")
    if regression_formula_std_legacy.get('slope') is not None:
        print(f"  Legacy std regression:         {regression_formula_std_legacy['description']}")
        print(f"  R² = {regression_formula_std_legacy['r_squared']:.4f}  |  n = {regression_formula_std_legacy['n_pairs']} pairs")
    print("")
    
    # Show top examples
    if high_coherence_pairs:
        print("  Top HIGH-COHERENCE compatible pairs:")
        for pair in high_coherence_pairs[:3]:
            print(f"    {pair['pair']:20} | scores: {pair['coherence1']:.4f}, {pair['coherence2']:.4f} | compatibility: {pair['compatibility_score']:.4f}")
    print("")
    
    if low_coherence_pairs:
        print("  Top LOW-COHERENCE complementary pairs (high diversity):")
        for pair in low_coherence_pairs[:3]:
            print(f"    {pair['pair']:20} | scores: {pair['coherence1']:.4f}, {pair['coherence2']:.4f} | σ: {pair['diversity_coefficient']:.6f}")
    print("")
    
    return {
        'high_coherence_compatible': high_coherence_pairs,
        'low_coherence_complementary': low_coherence_pairs,
        'moderate_mixed': moderate_pairs,
        'regression_formula': regression_formula,
        'regression_formula_std_legacy': regression_formula_std_legacy,
        'summary': {
            'total_pairs': len(high_coherence_pairs) + len(low_coherence_pairs) + len(moderate_pairs),
            'cell_count': len(cells)
        }
    }

# ============================================================================
# OUTPUT GENERATION
# ============================================================================

def generate_output_json(cell_coherence: Dict,
                        row_coherence: Dict,
                        column_coherence: Dict,
                        emergence_signatures: Dict,
                        pair_analysis: Dict) -> str:
    """Generate comprehensive JSON output for JSX consumption."""
    
    output = {
        'metadata': {
            'analysis': 'Polygon Region Coherence Analysis',
            'grid': f'{GRID_COLS}×{GRID_ROWS}',
            'timestamp': pd.Timestamp.now().isoformat()
        },
        'region_coherence': {
            'cells': cell_coherence,
            'rows': row_coherence,
            'columns': column_coherence
        },
        'emergence_signatures': emergence_signatures,
        'pairwise_analysis': pair_analysis
    }
    
    return json.dumps(output, indent=2)


def generate_regression_plot(pair_analysis: Dict, output_dir: Path) -> None:
    """Write regression scatter/fit plots alongside the JSON output."""
    if plt is None:
        print("⚠ Plot skipped: matplotlib is not available in this environment")
        return

    all_pairs = (
        pair_analysis.get('high_coherence_compatible', [])
        + pair_analysis.get('moderate_mixed', [])
        + pair_analysis.get('low_coherence_complementary', [])
    )
    if not all_pairs:
        print("⚠ Plot skipped: no pairs available")
        return

    baseline = pair_analysis.get('regression_formula', {}).get('baseline_coherence')
    if baseline is None:
        all_cohs = [p['coherence1'] for p in all_pairs] + [p['coherence2'] for p in all_pairs]
        baseline = max(all_cohs) if all_cohs else 1.0

    colors = {
        'high_coherence_compatible': '#2ca02c',
        'moderate_mixed': '#ff8c00',
        'low_coherence_complementary': '#d62728'
    }

    fig, ax = plt.subplots(figsize=(11, 7))

    # Plot each pair category with consistent colors.
    for category in ('high_coherence_compatible', 'moderate_mixed', 'low_coherence_complementary'):
        pairs = pair_analysis.get(category, [])
        if not pairs:
            continue

        sigmas = [p['diversity_coefficient'] for p in pairs]
        losses = [baseline - (p['coherence1'] + p['coherence2']) / 2 for p in pairs]
        ax.scatter(
            sigmas,
            losses,
            s=42,
            alpha=0.85,
            color=colors[category],
            edgecolors='white',
            linewidths=0.4,
            label=f"{category} (n={len(pairs)})"
        )

    reg = pair_analysis.get('regression_formula', {})
    if reg.get('slope') is not None and reg.get('intercept') is not None:
        x_vals = np.array([p['diversity_coefficient'] for p in all_pairs])
        x_line = np.linspace(float(x_vals.min()), float(x_vals.max()), 200)
        y_line = reg['slope'] * x_line + reg['intercept']
        ax.plot(x_line, y_line, color='#1f77b4', linewidth=2.2, label='normalized regression fit')

    legacy = pair_analysis.get('regression_formula_std_legacy', {})

    ax.set_title('Pairwise Coherence Loss vs Normalized Diversity (Stage 4)', fontsize=13, pad=10)
    ax.set_xlabel('normalized diversity coefficient (σ = |c1 - c2| / max(c1, c2))', fontsize=11)
    ax.set_ylabel('coherence loss (baseline - mean pair coherence)', fontsize=11)
    ax.grid(True, linestyle='--', linewidth=0.6, alpha=0.35)
    ax.legend(loc='best', fontsize=9)

    lines = []
    if reg.get('slope') is not None:
        lines.append(f"normalized: loss = {reg['slope']:.4f}σ + {reg['intercept']:.4f}, R²={reg['r_squared']:.4f}")
    if legacy.get('slope') is not None:
        lines.append(f"legacy std: loss = {legacy['slope']:.4f}σ_std + {legacy['intercept']:.4f}, R²={legacy['r_squared']:.4f}")
    if lines:
        ax.text(
            0.01,
            0.01,
            "\n".join(lines),
            transform=ax.transAxes,
            ha='left',
            va='bottom',
            fontsize=9,
            bbox={'boxstyle': 'round,pad=0.3', 'facecolor': 'white', 'edgecolor': '#bbbbbb', 'alpha': 0.9}
        )

    png_path = output_dir / 'pair_coherence_regression.png'
    svg_path = output_dir / 'pair_coherence_regression.svg'

    fig.tight_layout()
    fig.savefig(png_path, dpi=180)
    fig.savefig(svg_path)
    plt.close(fig)

    print(f"✓ Generated: {png_path}")
    print(f"✓ Generated: {svg_path}")

# ============================================================================
# MAIN EXECUTION
# ============================================================================

if __name__ == "__main__":
    # Step 2: Analyse coherence at each region level (using selected cells only)
    cell_coherence = analyze_cell_coherence(found_files)
    row_coherence = analyze_row_coherence()
    column_coherence = analyze_column_coherence()
    
    if not cell_coherence:
        print("✗ ERROR: No cell coherence data loaded from CSV files.")
        print(f"  Checked directory: {CSV_DIR}")
        print(f"  Selected cells: {SELECTED_CELLS}")
        sys.exit(1)
    
    # Step 2: Calculate emergence signatures
    emergence_signatures = calculate_emergence_signatures(
        cell_coherence, row_coherence, column_coherence
    )
    
    # Step 3: Generate pairwise analysis
    pair_analysis = generate_pair_combinations(cell_coherence)
    
    # Step 4: Output JSON
    print("STEP 6: GENERATING OUTPUT")
    print("-" * 90)
    
    json_output = generate_output_json(
        cell_coherence, row_coherence, column_coherence,
        emergence_signatures, pair_analysis
    )

    # Write into a run-specific subfolder matching the csv_directory leaf,
    # e.g. csv_directory "csv_exports/2" → output OUTPUT_DIR / "2" / ...
    # Falls back to OUTPUT_DIR root for legacy flat layouts.
    _csv_dir_parts = Path(_csv_dir_raw).parts
    _run_subfolder = _csv_dir_parts[-1] if len(_csv_dir_parts) > 1 else ""
    if _run_subfolder:
        _out_dir = OUTPUT_DIR / _run_subfolder
        _out_dir.mkdir(parents=True, exist_ok=True)
    else:
        _out_dir = OUTPUT_DIR
    output_file = _out_dir / "pair_coherence_composition.json"
    with open(output_file, 'w') as f:
        f.write(json_output)

    generate_regression_plot(pair_analysis, _out_dir)

    print(f"✓ Generated: {output_file}")
    print(f"  File size: {output_file.stat().st_size / 1024:.1f} KB")
    print("")
    
    print("=" * 90)
    print("ANALYSIS COMPLETE")
    print("=" * 90)
    print(f"\nOutput ready for JSX polygon extraction:")
    print(f"  - High-coherence pairs: Use 'high_coherence_compatible' category")
    print(f"  - Low-coherence pairs: Use 'low_coherence_complementary' category")
    print(f"  - Cell coordinates: Extract from 'cell1', 'cell2' fields")
    print("")
