"""Apply a Neon Music playlist-rules download to an encrypted bot configuration."""

import argparse
import gzip
import json
import re
from pathlib import Path

from cryptography.fernet import InvalidToken

import cloud

RANGES = {"short_term", "medium_term", "long_term"}


def validated_rules(document):
    if not isinstance(document, dict) or document.get("format") != "neon-music-playlist-rules" or document.get("version") != 1:
        raise ValueError("Expected a Neon Music playlist-rules JSON download.")
    keys = set()
    result = {}
    for group in ("spotify_top_playlists", "history_playlists"):
        entries = document.get(group)
        if not isinstance(entries, list) or len(entries) > 100:
            raise ValueError("Each rule group must contain a list of up to 100 playlists.")
        result[group] = []
        for entry in entries:
            if not isinstance(entry, dict):
                raise ValueError("Expected a playlist rule object.")
            key, name, limit = (entry.get(field) for field in ("key", "name", "limit"))
            if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,40}", key) or key in keys:
                raise ValueError("Playlist IDs must be unique and contain 1–40 letters, numbers, underscores or hyphens.")
            if not isinstance(name, str) or not name.strip() or len(name) > 100:
                raise ValueError("Give each playlist a name of 1–100 characters.")
            if type(limit) is not int or not 1 <= limit <= 100:
                raise ValueError("Playlist sizes must be whole numbers from 1 to 100.")
            rule = {"key": key, "name": name.strip(), "limit": limit}
            if group == "spotify_top_playlists":
                window = entry.get("range")
                if not isinstance(window, str) or window not in RANGES:
                    raise ValueError("Choose a supported Spotify ranking window.")
                rule["range"] = window
            else:
                days = entry.get("days")
                if type(days) is not int or not 0 <= days <= 36500:
                    raise ValueError("History windows must be whole days from 0 (all time) to 36,500.")
                rule["days"] = days
            keys.add(key)
            result[group].append(rule)
    return result


def apply_rules(path):
    rules = validated_rules(json.loads(path.read_text(encoding="utf-8-sig")))
    target = cloud.STATE / "config.enc"
    if not target.is_file():
        raise ValueError("Download the latest state/config.enc from your private repository first.")
    cipher = cloud.get_cipher()
    config = json.loads(cloud.unpack(cipher, target))
    if not isinstance(config, dict):
        raise ValueError("The encrypted configuration has an unexpected format.")
    config.update(rules)
    encoded = json.dumps(config, ensure_ascii=False, indent=2).encode("utf-8")
    temp = target.with_suffix(".enc.tmp")
    temp.write_bytes(cipher.encrypt(gzip.compress(encoded, mtime=0)))
    temp.replace(target)
    return sum(len(entries) for entries in rules.values())


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("rules", type=Path, help="Downloaded neon-music-playlist-rules.json")
    args = parser.parse_args()
    try:
        count = apply_rules(args.rules)
    except InvalidToken:
        parser.exit(1, "Could not unlock state/config.enc with your local Rotation key.\n")
    except json.JSONDecodeError:
        parser.exit(1, "Could not read the playlist rules or encrypted configuration as JSON.\n")
    except (OSError, ValueError, RuntimeError) as error:
        parser.exit(1, f"{error}\n")
    print(f"Saved {count} playlist rules to state/config.enc. Upload only that encrypted file.")


if __name__ == "__main__":
    main()
