import sqlite3
from hiveos.db import get_db
import json
from datetime import datetime
import os

LOG_FILE_PATH = "chunk_events.log"

def log_chunk_event(chunk_id, task_id, agent_id, result, reason="", tick=None):
    entry = {
        "timestamp": datetime.utcnow().isoformat(),
        "event": "chunk_attempt",
        "chunk": chunk_id,
        "task": task_id,
        "agent": agent_id,
        "result": result,
        "reason": reason,
        "tick": tick
    }
    with open(LOG_FILE_PATH, "a") as log_file:
        log_file.write(json.dumps(entry) + "\n")

def log_chunk_event_db(chunk_id, task_id, agent_id, result, reason="", tick=None, zone_id=None):
    # Stub for future DB logging — not enabled during dev
    
    with get_db() as conn:
        conn.execute(
            "INSERT INTO task_logs (chunk_id, task_id, agent_id, zone_id, result, reason, tick) "
            "VALUES (?, ?, ?, ?, ?, ?, ?)",
            (chunk_id, task_id, agent_id, zone_id, result, reason, tick)
        )
