"""Group parsed verses into phrases and attach the working-model expected motif.
Disjunctive hierarchy (level): sof-pasuk 1, etnachta 1, segol 2, zakef-gadol 2, zakef-katan 2,
revia 3, tevir 4, tipcha 4, pashta 4, zarka 4, geresh 4, gershayim 4, yetiv 4, shalshelet 4,
pazer 4, telisha-gedola 4, telisha-ketana 4, karnei-parah 4, pazer 4.
Conjunctives: munach, merkha, mahpach, darga, qadma, mercha-kefula, yerach-ben-yomo, tsinnorit.
A phrase ends at a disjunctive; the disjunctive word carries the phrase's motif, and the
preceding conjunctive words (in the same phrase) carry the lead-in figures.
"""
import sys, json
sys.path.insert(0, "/home/hatch/workspace/lein-practice/validate")
from trope import parse_verse

DISJ = {'sof-pasuk','etnachta','segol','zakef-gadol','zakef-katan','revia','tevir','tipcha',
        'pashta','zarka','geresh','gershayim','yetiv','shalshelet','pazer','telisha-gedola',
        'telisha-ketana','karnei-parah','legarmeh'}
CONJ = {'munach','merkha','mahpach','darga','qadma','mercha-kefula','yerach-ben-yomo','tsinnorit'}

def verse_phrases(text):
    """Return list of phrases; each phrase = list of (plain_word, [tropes]) ending at a disjunctive."""
    words = parse_verse(text)
    phrases=[]; cur=[]
    for w in words:
        if not w['tropes'] and not w['plain'].strip():
            continue
        cur.append(w)
        if any(t in DISJ for t in w['tropes']):
            phrases.append(cur); cur=[]
    if cur: phrases.append(cur)
    return phrases

def phrase_head(ph):
    """The disjunctive trope that closes the phrase."""
    for w in reversed(ph):
        for t in w['tropes']:
            if t in DISJ: return t
    return None

def phrase_words(ph):
    return ' '.join(w['plain'] for w in ph)

# Working model (report §2.5): ta'am -> degree sequence (degrees in C major; 7 below tonic = -1 etc.)
# Represented as semitone offsets from tonic (major scale): 1=0, 2=2, 3=4, 4=5, 5=7, 6=9, 7=11, below: 7=-1, 6=-3, 5=-5, 4=-7, b7=-2
DEG = {1:0, 2:2, 3:4, 4:5, 5:7, 6:9, 7:11}
def d(*degrees, below=()):
    """degrees as scale degrees; negative degree = below tonic (e.g. -7 = 7 below = -1 semitone)."""
    out=[]
    for x in degrees:
        if x>0: out.append(DEG[x])
        else: out.append(DEG[-x]-12)
    return out
def flat7():
    return -2  # B-flat below tonic (segol melisma)

WORKING = {
 'sof-pasuk': d(2,2,3,1),
 'etnachta': d(1,1,2),
 'zakef-katan': d(5,5,3,2),
 'zakef-gadol': d(1,1,3,5,3,2),
 'tipcha': d(2,3),
 'revia': d(3,3,2,1,-7,-6),
 'tevir': d(2,1,-7,1,2),
 'pashta': d(1,5),
 'yetiv': d(5,5),
 'segol': d(1,2,1),
 'zarka': d(1,1),
 'munach': None,  # contextual
 'kadma': d(1,1),
 'mahpach': d(5,5,1),
 'merkha': None,  # contextual
 'darga': d(5,5,4,3,2),
 'telisha-gedola': d(3,2,3),
 'telisha-ketana': d(3,2,1),
 'geresh': d(5,5,2),
 'gershayim': d(1,2,3,2,1,2,3),
 'pazer': d(1,1,2,2,3,6,5,3,2),
 'shalshelet': None,  # forum: 2 pazers
 'karnei-parah': None,
 'mercha-kefula': None,
 'yerach-ben-yomo': None,
}
# lead-in figures (conjunctive word immediately before the disjunctive, same phrase)
LEAD = {
 ('merkha','tipcha'): d(-7,2,-7),
 ('merkha','tevir'): d(2,2),
 ('merkha','sof-pasuk'): d(3,1),
 ('munach','etnachta'): d(1,1),
 ('munach','zakef-katan'): d(3,3,2),
 ('munach','yetiv'): d(3,3,2),
 ('munach','zarka'): d(1,1),
 ('munach','segol'): d(1,1),
 ('munach','telisha-gedola'): d(1,1),
 ('munach','telisha-ketana'): d(1,1),
 ('mahpach','pashta'): d(5,5,1),
 ('darga','tevir'): d(5,5,4,3,2),
 ('qadma','pashta'): d(1,1),
}

if __name__=='__main__':
    gen1=json.load(open('/home/hatch/workspace/lein-practice/validate/gen1.json'))
    verses = gen1[0]+gen1[1][:3]
    total=0
    for vi,v in enumerate(verses):
        phs = verse_phrases(v)
        total+=len(phs)
        print(f"\nGen {1 if vi<31 else 2}:{vi%31+1}  ({len(phs)} phrases)")
        for ph in phs:
            print(f"   [{phrase_head(ph):>15}] {phrase_words(ph)}")
    print(f"\nTOTAL phrases in Gen 1:1-2:3: {total}")
