#!/usr/bin/python3
"""
set_fan_duty - Set PWM duty cycle for a specific fan.

Enables the tachometer, sets duty via both I2C and hwmon,
and saves the speed persistently so it survives reboots.

Usage:
    set_fan_duty <fan_num> <duty_percent> [board_num]

duty_percent: 0-100
"""

import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from fan_common import (
    FANS_PER_BOARD,
    BOARDS,
    get_board_hwmon,
    set_pwm_duty,
    set_pwm_duty_auto,
    set_pwm_duty_i2c,
    get_board_addr,
    save_fan_speeds,
    load_fan_speeds,
    get_transport,
)


def main():
    if len(sys.argv) < 3:
        print(json.dumps({
            "error_msg": "Usage: set_fan_duty <fan_num> <duty_percent> [board_num]"
        }), file=sys.stderr)
        sys.exit(1)

    fan_num = int(sys.argv[1])
    duty_percent = float(sys.argv[2])
    board_num = int(sys.argv[3]) if len(sys.argv) > 3 else 1

    if fan_num < 1 or fan_num > FANS_PER_BOARD:
        print(json.dumps({"error_msg": f"fan_num must be 1-{FANS_PER_BOARD}"}),
              file=sys.stderr)
        sys.exit(1)

    if duty_percent < 0 or duty_percent > 100:
        print(json.dumps({"error_msg": f"duty_percent must be 0-100"}),
              file=sys.stderr)
        sys.exit(1)

    try:
        # Set via I2C (enables tachometer + sets duty reliably)
        dev_addr = get_board_addr(board_num)
        set_pwm_duty_i2c(dev_addr, fan_num, duty_percent)

        # Also set via hwmon for consistency (skip in i2c-only mode)
        pwm_raw = int(round(duty_percent * 255 / 100))
        try:
            hwmon = get_board_hwmon(board_num)
            pwm_raw = set_pwm_duty(hwmon, fan_num, duty_percent)
        except (Exception, ValueError):
            pass

        # Save speed persistently
        speeds = load_fan_speeds()
        # Update or add entry for this fan
        updated = False
        for entry in speeds:
            if entry.get("board") == board_num and entry.get("fan") == fan_num:
                entry["duty"] = int(duty_percent)
                updated = True
                break
        if not updated:
            speeds.append({"board": board_num, "fan": fan_num, "duty": int(duty_percent)})
        save_fan_speeds(speeds)

        output = {
            "board": board_num,
            "fan": fan_num,
            "duty_percent": duty_percent,
            "pwm_raw": pwm_raw,
            "saved": True,
            "success": True,
        }
        print(json.dumps(output, indent=4))

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


if __name__ == "__main__":
    main()
