#!/usr/bin/env python3
import os
import sys
import time
from datetime import datetime

LOG = ".kilo/logs/cron_reviews.log"
HEADER = "=== 2026-"


def last_entries():
    if not os.path.exists(LOG):
        return []
    with open(LOG, "r", encoding="utf-8") as f:
        lines = [line.strip() for line in f if line.strip()]
    return [line for line in lines if line.startswith(HEADER)]


def read_findings():
    if not os.path.exists(LOG):
        return []
    with open(LOG, "r", encoding="utf-8") as f:
        text = f.read()
    blocks = []
    current = []
    for line in text.splitlines():
        if line.startswith("==="):
            if current:
                blocks.append("\n".join(current))
                current = []
        current.append(line)
    if current:
        blocks.append("\n".join(current))
    return blocks


def verdict():
    entries = last_entries()
    if not entries:
        print(f"[{datetime.now().isoformat()}] LOG MISSING: {LOG}")
        return

    last = entries[-1].split(" ===")[-1].strip()
    findings_blocks = read_findings()
    recent = findings_blocks[-3:] if len(findings_blocks) >= 3 else findings_blocks

    frozen = False
    if len(recent) >= 2:
        if all(block == recent[0] for block in recent):
            frozen = True

    if frozen:
        print(f"[{datetime.now().isoformat()}] VERDICT: CRON FROZEN (findings block repeated)")
    else:
        print(f"[{datetime.now().isoformat()}] VERDICT: CRON ALIVE | last={last}")
    sys.stdout.flush()


def main():
    print(f"[{datetime.now().isoformat()}] MONITOR STARTED | watching={LOG}")
    sys.stdout.flush()
    try:
        while True:
            verdict()
            time.sleep(1800)
    except KeyboardInterrupt:
        print(f"\n[{datetime.now().isoformat()}] MONITOR STOPPED")
        sys.stdout.flush()


if __name__ == "__main__":
    main()
