"""
FillDrainPump config: reads schedule from file; logs ESP32 sync requests.
"""
import os
from datetime import datetime
from flask import Blueprint, request

from config import FILLDRAIN_SCHEDULE_FILE, FILLDRAIN_LOG_FILE

bp = Blueprint("filldrain", __name__)

SCHEDULE_FILE = FILLDRAIN_SCHEDULE_FILE
LOG_FILE = FILLDRAIN_LOG_FILE

DEFAULT_ON1 = "08:00"
DEFAULT_ON2 = "19:00"
DEFAULT_DURATION = "5"


def read_schedule():
    """Read on1, on2, duration from schedule file. Return (on1, on2, duration) strings."""
    if not os.path.isfile(SCHEDULE_FILE):
        return DEFAULT_ON1, DEFAULT_ON2, DEFAULT_DURATION
    try:
        with open(SCHEDULE_FILE, "r", encoding="utf-8") as f:
            lines = [line.strip() for line in f.readlines()]
        on1 = lines[0] if len(lines) > 0 and lines[0] else DEFAULT_ON1
        on2 = lines[1] if len(lines) > 1 and lines[1] else DEFAULT_ON2
        duration = lines[2] if len(lines) > 2 and lines[2] else DEFAULT_DURATION
        return on1, on2, duration
    except Exception:
        return DEFAULT_ON1, DEFAULT_ON2, DEFAULT_DURATION


def log_entry(data: dict):
    """Append one line to log file with timestamp and data."""
    try:
        log_dir = os.path.dirname(LOG_FILE)
        if log_dir and not os.path.isdir(log_dir):
            os.makedirs(log_dir, exist_ok=True)
        with open(LOG_FILE, "a", encoding="utf-8") as f:
            ts = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
            f.write(f"{ts} | {data}\n")
    except Exception as e:
        print(f"Log write error: {e}")


@bp.route("/sync", methods=["GET", "POST"])
def sync():
    """
    ESP32 sends: epoch, time, on1, on2, duration (query or JSON).
    Respond with 3 lines: on1, on2, duration (from schedule file).
    """
    if request.method == "POST" and request.is_json:
        data = request.get_json(silent=True) or {}
        epoch = data.get("epoch", "")
        time_str = data.get("time", "")
        on1 = data.get("on1", "")
        on2 = data.get("on2", "")
        duration = data.get("duration", "")
    else:
        epoch = request.args.get("epoch", "")
        time_str = request.args.get("time", "")
        on1 = request.args.get("on1", "")
        on2 = request.args.get("on2", "")
        duration = request.args.get("duration", "")

    log_data = {
        "client_ip": request.remote_addr,
        "epoch": epoch,
        "time": time_str,
        "on1": on1,
        "on2": on2,
        "duration": duration,
    }
    log_entry(log_data)

    s_on1, s_on2, s_duration = read_schedule()
    body = f"{s_on1}\n{s_on2}\n{s_duration}\n"
    return body, 200, {"Content-Type": "text/plain; charset=utf-8"}
