"""Stardew Valley trainer bridge — real savegame + console commands."""
import os
import json
import shutil
import logging

logger = logging.getLogger('SweetCheat.StardewBridge')

def get_save_folder():
    appdata = os.environ.get('APPDATA', os.path.expanduser('~'))
    return os.path.join(appdata, 'StardewValley', 'Saves')

def list_save_files():
    folder = get_save_folder()
    if not os.path.isdir(folder):
        return []
    saves = []
    for farm_name in os.listdir(folder):
        farm_path = os.path.join(folder, farm_name)
        if not os.path.isdir(farm_path): continue
        save_path = os.path.join(farm_path, farm_name)
        if os.path.exists(save_path):
            saves.append(save_path)
    return sorted(saves, key=os.path.getmtime, reverse=True)

def read_save(save_path):
    try:
        with open(save_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        logger.error(f"Could not read savegame: {e}")
        return None

def write_save(save_path, data):
    backup = save_path + '.bak'
    shutil.copy2(save_path, backup)
    with open(save_path, 'w', encoding='utf-8') as f:
        json.dump(data, f)
    return True

CHEATS = {
    'money': {
        'name': 'Infinite Money',
        'field': ['money'],
        'type': 'int',
        'default': 999999999,
    },
    'max_health': {
        'name': 'Max Health',
        'field': ['maxHealth'],
        'type': 'int',
        'default': 200,
    },
    'health': {
        'name': 'Full Health',
        'field': ['health'],
        'type': 'int',
        'default': 200,
    },
    'stamina': {
        'name': 'Infinite Stamina',
        'field': ['stamina'],
        'type': 'float',
        'default': 999.0,
    },
    'max_items': {
        'name': 'Max Inventory Stacks',
        'field': [],
        'type': 'function',
        'fn': lambda data: _max_stacks(data),
    },
    'max_skills': {
        'name': 'Max All Skills',
        'field': ['experiencePoints'],
        'type': 'function',
        'fn': lambda data: _max_skills(data),
    },
    'friendship': {
        'name': 'Max Friendship',
        'field': ['friendshipData'],
        'type': 'function',
        'fn': lambda data: _max_friendship(data),
    },
}

def _max_stacks(data):
    changed = 0
    for item in data.get('items', []):
        if isinstance(item, dict):
            stack = item.get('Stack')
            if isinstance(stack, int) and 0 < stack < 999:
                item['Stack'] = 999
                changed += 1
    return changed

def _max_skills(data):
    exp = data.get('experiencePoints', {})
    if isinstance(exp, dict):
        for k in exp:
            exp[k] = 15000
    elif isinstance(exp, list) and len(exp) >= 10:
        for i in range(len(exp)):
            exp[i] = 15000
    return True

def _max_friendship(data):
    friends = data.get('friendshipData', {})
    if isinstance(friends, dict):
        for npc in friends.values():
            if isinstance(npc, dict):
                npc['Points'] = 2500
                npc['Status'] = 'Married' if npc.get('Status') == 'Married' else 'BestFriend'
    return True

def apply_cheat(save_path, cheat_id, value=None):
    meta = CHEATS.get(cheat_id)
    if not meta:
        return False, f"Unknown cheat: {cheat_id}"
    data = read_save(save_path)
    if data is None:
        return False, "Savegame konnte nicht gelesen werden"

    try:
        if meta['type'] == 'function':
            meta['fn'](data)
        else:
            target = data
            for key in meta['field'][:-1]:
                target = target.setdefault(key, {})
            final = meta['field'][-1]
            v = value if value is not None else meta['default']
            if meta['type'] == 'int':
                v = int(v)
            elif meta['type'] == 'float':
                v = float(v)
            target[final] = v

        write_save(save_path, data)
        return True, meta['name'] + " aktiviert"
    except Exception as e:
        logger.exception("apply_cheat failed")
        return False, f"Fehler: {e}"

def get_cheats():
    return {k: v['name'] for k, v in CHEATS.items()}

if __name__ == '__main__':
    saves = list_save_files()
    print('Saves:', saves[:3])
    if saves:
        print(get_cheats())
        print(apply_cheat(saves[0], 'money'))
