#!/usr/bin/python3
"""Serves powercontrol.log entries filtered by time window and pod list.

Used by the generator group modal to show power control actions (manual and
automated) alongside the charted generator data.
"""

import cgi
import json
from datetime import datetime, timedelta

print("Content-Type: application/json\n")

POWERCONTROL_LOG_FILE = '/opt/ngon/logs/powercontrol.log'


def main():
    form = cgi.FieldStorage()

    try:
        hours = int(form.getvalue('hours', '24'))
    except (ValueError, TypeError):
        hours = 24

    pods_param = form.getvalue('pods', '') or ''
    requested_pods = {p.strip() for p in pods_param.split(',') if p.strip()}

    cutoff = datetime.now() - timedelta(hours=hours)
    entries = []

    try:
        with open(POWERCONTROL_LOG_FILE, 'r') as f:
            lines = f.readlines()
    except FileNotFoundError:
        lines = []

    for line in lines:
        line = line.strip()
        if not line:
            continue

        parts = line.split(',', 5)
        if len(parts) < 5:
            continue

        timestamp, pod_field, count, action, user = parts[:5]
        reason = parts[5] if len(parts) > 5 else ''

        try:
            ts = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            continue

        if ts < cutoff:
            continue

        # pod_field may be a single pod or " / "-joined list
        entry_pods = [p.strip() for p in pod_field.split(' / ') if p.strip()]

        if requested_pods and not (requested_pods & set(entry_pods)):
            continue

        entries.append({
            'timestamp': timestamp,
            'pods': entry_pods,
            'count': int(count) if count.isdigit() else count,
            'action': action,
            'user': user,
            'reason': reason,
            'automated': user in ('MM', 'AW', 'AS'),
        })

    print(json.dumps({'entries': entries}))


main()
