"""Entity profile view."""
import json

from django.shortcuts import render, get_object_or_404

from analysis.models import EntityProfile


def entity_profile(request, entity_id):
    """Detailed profile for a single entity."""
    entity = get_object_or_404(EntityProfile, id=entity_id)
    run = entity.run

    # Compute deviation from cluster mean
    deviations = {}
    if entity.feature_json and entity.cluster:
        cluster_features = {
            f.feature_name: {'mean': f.mean, 'std': f.std}
            for f in entity.cluster.features.all()
        }
        for col, val in entity.feature_json.items():
            if col in cluster_features and cluster_features[col].get('std') and cluster_features[col]['std'] > 1e-10:
                deviations[col] = {
                    'value': val,
                    'cluster_mean': cluster_features[col]['mean'],
                    'zscore': (val - cluster_features[col]['mean']) / cluster_features[col]['std'],
                }

    return render(request, 'analysis/entity_profile.html', {
        'entity': entity,
        'run': run,
        'deviations': deviations,
    })
