import os
import json
import sys
import numpy as np
import cv2
import math
from scipy.ndimage import label
from scipy.special import expit  # sigmoid

def classify_segments(img, R, eta, tau_j):
    assert img.shape == R.shape
    H, W = img.shape

    stroke_R = R[img == 1]
    if stroke_R.size == 0:
        return img.copy(), np.zeros_like(img, bool)
    R_hat = R / stroke_R.max()

    out_img = img.copy().astype(np.uint8)
    joint_mask = np.zeros_like(img, dtype=bool)

    struct8 = np.ones((3, 3), dtype=int)

    complexes = []
    for y in range(1, H - 1):
        for x in range(1, W - 1):
            if img[y, x] != 1:
                continue

            patch = img[(y-1):(y+2), (x-1):(x+2)]
            bg = (patch == 0).astype(int)
            bg[1, 1] = 0

            labels, num_comp = label(bg, structure=struct8)
            C = num_comp

            score = eta * C + (1 - eta) * R_hat[y, x]
            Pj = expit(score)

            if Pj > tau_j:
                joint_mask[y, x] = True
                complexes.append((y, x))

    out_img[joint_mask] = 2
    return out_img, joint_mask, complexes
