#!/usr/bin/env python3
"""
Apply CPU Power Mode from Database at Boot

This script is called by systemd at boot to apply the CPU power mode
stored in the database (cpu_power_mode config parameter).

Usage:
  /usr/bin/python3 /var/www/nebuleair_pro_4g/power/apply_cpu_mode_from_db.py
"""

import sqlite3
import sys
import subprocess

DB_PATH = "/var/www/nebuleair_pro_4g/sqlite/sensors.db"
SET_MODE_SCRIPT = "/var/www/nebuleair_pro_4g/power/set_cpu_mode.py"

def get_cpu_mode_from_db():
    """Read cpu_power_mode from database"""
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("SELECT value FROM config_table WHERE key = 'cpu_power_mode'")
        result = cursor.fetchone()
        conn.close()
        return result[0] if result else None
    except sqlite3.Error as e:
        print(f"Database error: {e}", file=sys.stderr)
        return None

def main():
    """Main function"""
    print("=== Applying CPU Power Mode from Database ===")

    # Get mode from database
    mode = get_cpu_mode_from_db()

    if mode is None:
        print("No cpu_power_mode found in database, using default: normal")
        mode = "normal"

    print(f"CPU power mode from database: {mode}")

    # Call set_cpu_mode.py to apply the mode
    try:
        result = subprocess.run(
            ["/usr/bin/python3", SET_MODE_SCRIPT, mode],
            capture_output=True,
            text=True,
            timeout=30
        )

        if result.returncode == 0:
            print(f"Successfully applied CPU power mode: {mode}")
            print(result.stdout)
            return 0
        else:
            print(f"Failed to apply CPU power mode: {mode}", file=sys.stderr)
            print(result.stderr, file=sys.stderr)
            return 1

    except subprocess.TimeoutExpired:
        print("Timeout while applying CPU power mode", file=sys.stderr)
        return 1
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1

if __name__ == "__main__":
    sys.exit(main())
