import base64, hashlib, hmac, re, subprocess, time
from pathlib import Path
secret=Path('/srv/apps/sotlab-users/data/session_secret').read_bytes()
def ck(username):
    ts=str(int(time.time()))
    payload=f'{username}:{ts}'
    sig=hmac.new(secret, payload.encode(), hashlib.sha256).hexdigest()
    return base64.urlsafe_b64encode(f'{payload}:{sig}'.encode()).decode()
jar='/tmp/music_play_cookiejar.txt'
Path(jar).unlink(missing_ok=True)
cookie=ck('sotgee')

def curl(url, out, extra=None):
    cmd=['curl','-sS','-D',out+'.h','-o',out+'.b','--max-time','30','-c',jar,'-b',jar,'-H',f'Cookie: sotlab_session={cookie}']
    if extra: cmd += extra
    cmd.append(url)
    r=subprocess.run(cmd,capture_output=True,text=True)
    h=Path(out+'.h').read_text(errors='replace') if Path(out+'.h').exists() else ''
    b=Path(out+'.b').read_text(errors='replace') if Path(out+'.b').exists() else ''
    return r.returncode,h,b
for url,name in [
    ('https://music.sotlab.co.uk/login.php','/tmp/login'),
    ('https://music.sotlab.co.uk/index.php','/tmp/index'),
    ('https://music.sotlab.co.uk/browse.php?action=song','/tmp/songs'),
]:
    rc,h,b=curl(url,name)
    print('URL',url,'rc',rc,'head',' | '.join(h.splitlines()[:8]),'len',len(b))
    print('markers',{m:(m in b or m in h) for m in ['play/index.php','stream.php','play.php','song.php','play_item','Unauthorized','Access Denied','Are You Man Enough']})
body='\n'.join((Path(p).read_text(errors='replace') if Path(p).exists() else '') for p in ['/tmp/index.b','/tmp/songs.b'])
urls=sorted(set(re.findall(r'(?:href|src|data-url|url)=["\']([^"\']*(?:play|stream)[^"\']*)', body)))
print('PLAY_URLS', urls[:20])
# Try a likely Ampache stream endpoint for song id 1 if no URL found.
for u in urls[:3] + ['/play/index.php?ssid=1&type=song']:
    full=u if u.startswith('http') else 'https://music.sotlab.co.uk'+u
    rc,h,b=curl(full,'/tmp/stream', ['-L','-r','0-4095'])
    bb=Path('/tmp/stream.b').read_bytes()[:64] if Path('/tmp/stream.b').exists() else b''
    print('STREAM_TEST',full,'rc',rc,'head',' | '.join(h.splitlines()[:14]),'bytes',bb[:32])
