from datetime import datetime

def _is_night(timestamp: str) -> bool:
    try:
        t = datetime.fromisoformat(timestamp)
        return t.hour >= 23 or t.hour <= 5
    except Exception:
        return False

def generate_suggestions(total_by_utility: dict, emissions: dict, data: list[dict]) -> list[str]:
    suggestions: list[str] = []

    if any(d["value"] > 0 for d in data if _is_night(d["timestamp"])):
        suggestions.append("Schedule automatic shutdown for equipment outside working hours.")

    if total_by_utility.get("air-conditioning", 0) > 1000:
        suggestions.append("Optimize AC setpoints and consider high-efficiency AC units.")

    if total_by_utility.get("steam", 0) > 800:
        suggestions.append("Improve steam line insulation and investigate waste heat recovery.")

    if total_by_utility.get("electricity", 0) > 4000:
        suggestions.append("Perform an energy audit focusing on lighting and motors.")

    suggestions.extend([
        "Improve building insulation to reduce heating and cooling loads.",
        "Monitor abnormal consumption spikes to detect leaks or malfunctioning equipment.",
        "Train staff and occupants on energy-saving best practices.",
    ])

    # De‑duplicate while preserving order
    seen = set()
    unique = []
    for s in suggestions:
        if s not in seen:
            seen.add(s)
            unique.append(s)
    return unique
