#!/usr/bin/env python3
"""Ajustes de la maestra y mapas de los mandos DE ESTE cliente, sin perfiles online."""
import os,re,sys,struct,shutil,subprocess,time,xml.etree.ElementTree as ET
from pathlib import Path
MAPPING={'b':'a','a':'b','x':'y','y':'x','l2':'lefttrigger','r2':'righttrigger','l3':'leftstick','r3':'rightstick','pageup':'leftshoulder','pagedown':'rightshoulder','start':'start','select':'back','up':'dpup','down':'dpdown','left':'dpleft','right':'dpright','joystick1up':'lefty','joystick1left':'leftx','joystick2up':'righty','joystick2left':'rightx','hotkey':'guide'}
def crc(data):
    d=bytearray(data[:0x354]);d[12:14]=b'\0\0';c=0
    for v in d:
        c^=v<<8
        for _ in range(8):c=((c<<1)^0x1021)&65535 if c&32768 else (c<<1)&65535
    return (~c)&65535
def resolucion():
    # Modo de pantalla actual (Batocera ya aplicó videomode=max-1920x1080), con tope 1080p.
    # En una pantalla de 720p la ventana del juego no debe quedar más grande que la imagen.
    try:
        m=re.match(r'^(\d+)x(\d+)$',os.environ.get('PES13_RESOLUCION',''))
        if not m:m=re.search(r'current (\d+) x (\d+)',subprocess.run(['xrandr','--current'],capture_output=True,text=True,timeout=5).stdout)
        w,h=int(m.group(1)),int(m.group(2))
        if w>=640 and h>=480:return min(w,1920),min(h,1080)
    except Exception:pass
    return 1920,1080
def configurar(prefix,template):
    p=Path(prefix)/'drive_c/users/root/Documents/KONAMI/Pro Evolution Soccer 2013/settings.dat'
    if Path(prefix).resolve() not in p.resolve().parents:
        raise ValueError('Documents apunta fuera de la botella: se conserva sin modificar')
    p.parent.mkdir(parents=True,exist_ok=True)
    if not p.exists():shutil.copyfile(template,p)
    d=bytearray(p.read_bytes())
    if len(d)!=0x354 or d[:4]!=b'WECF' or struct.unpack_from('<H',d,12)[0]!=crc(d):
        raise ValueError('settings.dat no reconocido: se conserva sin modificar')
    before=bytes(d);struct.pack_into('<ii',d,16,*resolucion());struct.pack_into('<i',d,28,2);d[14]|=8
    struct.pack_into('<H',d,12,crc(d))
    if bytes(d)!=before:
        shutil.copy2(p,str(p)+'.antes-mundogames-'+time.strftime('%Y%m%d-%H%M%S'));p.write_bytes(d)
    (Path(prefix)/'drive_c/ProgramData/KONAMI/Pro Evolution Soccer 2013/download').mkdir(parents=True,exist_ok=True)
def mapas(paths):
    result={}
    for path in paths:
        if not Path(path).exists():continue
        for c in ET.parse(path).getroot().findall('.//inputConfig'):
            guid=c.get('deviceGUID','')
            if c.get('type')!='joystick' or len(guid)!=32:continue
            fields=[guid,c.get('deviceName','Mando').replace(',',' '),'platform:Linux'];inputs=list(c.findall('input'))
            buttons={i.get('id') for i in inputs if i.get('type')=='button' and i.get('name')!='hotkey'}
            for i in inputs:
                name=i.get('name','');key=MAPPING.get(name);kind=i.get('type');idx=i.get('id','0');v=int(i.get('value','0'))
                if not key or (name=='hotkey' and idx in buttons):continue
                if kind=='button':val='b'+idx
                elif kind=='hat':val='h'+idx+'.'+str(v)
                elif kind=='axis':
                    if 'joystick' in name:val='a'+idx+('~' if v>0 else '')
                    elif key.startswith('dp'):val=('-' if v<0 else '+')+'a'+idx
                    else:val='a'+idx
                else:continue
                fields.append(key+':'+val)
            result[guid]=','.join(fields)+','
    return list(result.values())
def main():
    root=Path(os.environ.get('PES13_ROOT','/userdata'));base=root/'system/pes2013'
    prefix=os.environ.get('WINEPREFIX')
    if prefix:
        try:configurar(prefix,base/'settings.dat.plantilla')
        except Exception as e:print('PES13: '+str(e),file=sys.stderr);sys.exit(1)
    try:
        rows=mapas([os.environ.get('PES13_ES_SYSTEM','/usr/share/emulationstation/es_input.cfg'),str(root/'system/configs/emulationstation/es_input.cfg')])
        incoming=os.environ.get('SDL_GAMECONTROLLERCONFIG','').splitlines()
        print('\n'.join(rows+[s for s in incoming if s.strip()]))
    except Exception:print(os.environ.get('SDL_GAMECONTROLLERCONFIG',''))
if __name__=='__main__':main()
