#!/usr/bin/python3
"""
save_profiles - Save fan profiles to the persistent config file.

Reads JSON from stdin and writes it to /etc/45drives/fan-controller/profiles.json.
Creates the directory if it does not exist.

Input JSON (stdin):
{
  "version": 1,
  "activeProfileId": null,
  "profiles": [ ... ]
}

Output (JSON to stdout):
{ "success": true }
"""

import json
import os
import sys

CONFIG_DIR  = "/etc/45drives/fan-controller"
CONFIG_PATH = os.path.join(CONFIG_DIR, "profiles.json")


def main():
    try:
        data = json.loads(sys.stdin.read())

        # Ensure the config directory exists
        os.makedirs(CONFIG_DIR, mode=0o755, exist_ok=True)

        # Write atomically: write to a temp file then rename
        tmp_path = CONFIG_PATH + ".tmp"
        with open(tmp_path, "w") as f:
            json.dump(data, f, indent=2)
            f.write("\n")
        os.rename(tmp_path, CONFIG_PATH)

        print(json.dumps({"success": True}))

    except Exception as e:
        error = {"error_msg": str(e), "success": False}
        print(json.dumps(error), file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
