"""Measure a phrase's pitch contour with the harmonic-product fundamental method.
Returns a list of stable notes (t0, t1, midi_float, midi_round, dur).
"""
import numpy as np, librosa

class PitchMeasurer:
    def __init__(self, path, sr=22050):
        self.y, self.sr = librosa.load(path, sr=sr, mono=True)
        self.path = path
    def _spectrum(self, tc, win=0.25):
        seg = self.y[int((tc-win/2)*self.sr):int((tc+win/2)*self.sr)]
        if len(seg) < 1024: return None, None
        seg = seg*np.hanning(len(seg))
        S = np.abs(np.fft.rfft(seg, n=16384))
        freqs = np.fft.rfftfreq(16384, 1/self.sr)
        return freqs, S
    def fund(self, tc, win=0.25, fmin=90, fmax=380):
        """Harmonic-product fundamental with a requirement for energy at f itself."""
        freqs, S = self._spectrum(tc, win)
        if S is None: return None, 0.0
        smax = np.max(S)
        best=None
        for f in np.arange(fmin, fmax, 0.5):
            idx0=np.argmin(np.abs(freqs-f)); e0=S[idx0]
            prod=1.0
            for h in (1,2,3):
                idx=np.argmin(np.abs(freqs-f*h))
                prod*= (S[idx]+1e-9)
            score = (prod**(1/3)) * (1.0 if e0>0.12*smax else 0.25)
            if best is None or score>best[1]: best=(f,score)
        return best[0], best[1]/ (smax+1e-9)
    def contour(self, t0, t1, step=0.05, win=0.25):
        """Pitch contour (midi) at step intervals across [t0,t1]."""
        times = np.arange(t0, t1, step)
        midis=[]; confs=[]
        for tc in times:
            f, sc = self.fund(tc, win)
            if f is None: midis.append(np.nan); confs.append(0.0)
            else: midis.append(librosa.hz_to_midi(f)); confs.append(sc)
        return times, np.array(midis), np.array(confs)
    def notes(self, t0, t1, step=0.05, win=0.25, min_dur=0.09, max_dev=0.45):
        """Stable-note sequence for a window. Returns list of (t0,t1,midi,round,dur)."""
        times, midis, confs = self.contour(t0, t1, step, win)
        # median filter (3) to kill single-frame jumps
        m = midis.copy()
        for i in range(1, len(m)-1):
            vals=[x for x in (m[i-1],m[i],m[i+1]) if not np.isnan(x)]
            if vals: m[i]=np.median(vals)
        out=[]; i=0
        n=len(m)
        while i<n:
            if np.isnan(m[i]) or confs[i]<0.02:
                i+=1; continue
            j=i; vals=[m[i]]
            while j+1<n and not np.isnan(m[j+1]) and confs[j+1]>=0.02 and abs(m[j+1]-np.median(vals))<=max_dev:
                j+=1; vals.append(m[j])
            dur=(j-i+1)*step
            if dur>=min_dur:
                mm=float(np.median(vals))
                out.append((float(times[i]), float(times[j]), mm, int(round(mm)), float(dur)))
            i=j+1
        return out

def degrees_from_midi(midi_seq, tonic_midi):
    """Convert a sequence of MIDI notes to scale degrees relative to tonic (major scale).
    Returns list of (degree, octave) where degree 1..7, octave 0=tonic octave, -1=below, 1=above.
    Uses nearest diatonic note; also returns the raw semitone offset."""
    MAJOR = {0:1, 2:2, 4:3, 5:4, 7:5, 9:6, 11:7}
    out=[]
    for m in midi_seq:
        off = m - tonic_midi
        pc = int(round(off)) % 12
        octv = int(np.floor((off+6)/12)) if off>=0 else int(np.floor(off/12))
        # nearest diatonic degree
        best=None
        for semi, deg in MAJOR.items():
            d = min(abs(pc-semi), 12-abs(pc-semi))
            if best is None or d<best[0]: best=(d, deg, semi)
        out.append((best[1], octv, round(off,1)))
    return out
