#!/usr/bin/env python3
"""
Second Brain Processor
Watches bot.log for new messages, classifies them, and stores in appropriate buckets.
"""
import re
import time
import sys
from config import LOG_FILE
from storage import add_entry, get_last_position, save_position
from classifier import classify_message

# Pattern to match log lines: Date: 2026-01-15T21:38:16.392600 | Message: texto
LOG_PATTERN = re.compile(r"^Date: ([\d\-T:.]+) \| Message: (.+)$")

POLL_INTERVAL = 2  # seconds


def parse_log_line(line: str) -> tuple[str, str] | None:
    """Parse a log line and extract timestamp and message."""
    match = LOG_PATTERN.match(line.strip())
    if match:
        return match.group(1), match.group(2)
    return None


def process_new_lines():
    """Process any new lines in the log file since last run."""
    if not LOG_FILE.exists():
        print(f"Log file not found: {LOG_FILE}")
        return

    last_position = get_last_position()

    with open(LOG_FILE, "r") as f:
        lines = f.readlines()

    new_lines = lines[last_position:]
    if not new_lines:
        return

    print(f"Processing {len(new_lines)} new line(s)...")

    for i, line in enumerate(new_lines):
        parsed = parse_log_line(line)
        if not parsed:
            continue

        timestamp, message = parsed
        print(f"  Classifying: {message[:50]}...")

        category, confidence = classify_message(message)
        entry = add_entry(category, message, timestamp, confidence)

        print(f"  -> {category} (confidence: {confidence:.2f})")

    save_position(len(lines))
    print(f"Position saved: {len(lines)}")


def run_once():
    """Process new lines once and exit."""
    print("Running single pass...")
    process_new_lines()
    print("Done.")


def run_daemon():
    """Continuously watch for new log entries."""
    print(f"Starting brain processor daemon...")
    print(f"Watching: {LOG_FILE}")
    print(f"Poll interval: {POLL_INTERVAL}s")
    print("-" * 40)

    while True:
        try:
            process_new_lines()
            time.sleep(POLL_INTERVAL)
        except KeyboardInterrupt:
            print("\nShutting down...")
            break
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(POLL_INTERVAL)


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--once":
        run_once()
    else:
        run_daemon()
