import json
import os
import tempfile
from pathlib import Path


def get_state_file(agent: str, task_id: str) -> Path:
    user = os.getlogin()
    return Path(tempfile.gettempdir()) / f"notilens_{user}_{agent}_{task_id}.json"


def read_state(state_file: Path) -> dict:
    if not state_file.exists():
        return {}
    try:
        return json.loads(state_file.read_text())
    except Exception:
        return {}


def write_state(state_file: Path, state: dict) -> None:
    state_file.write_text(json.dumps(state, indent=2))


def update_state(state_file: Path, updates: dict) -> None:
    state = read_state(state_file)
    state.update(updates)
    write_state(state_file, state)


def delete_state(state_file: Path) -> None:
    if state_file.exists():
        state_file.unlink()
