TOOL_NAME = "failure_tracker"
TOOL_DESCRIPTION = """Log failed user queries and track improvement ideas. Actions: log_failure (save an unanswered query with optional reason), add_improvement (save a concrete improvement item), list_failures/list_improvements (review logged entries). Data persists in output/ as JSON."""
TOOL_ARGS = '{"action":{"type":"string","enum":["log_failure","add_improvement","list_improvements","list_failures","help"],"description":"Action to perform"},"query":{"type":"string","description":"The unanswered query to log (required for log_failure)"},"reason":{"type":"string","description":"Reason for failure (optional for log_failure)"},"item":{"type":"string","description":"Improvement item to add (required for add_improvement)"}}'

import json
import os
from datetime import datetime
from pathlib import Path
from tools._std import tool_ok, tool_error

LOG_FILE = Path('output/failure_tracker_log.json')
IMP_FILE = Path('output/failure_tracker_improvements.json')

def _ensure_file(file_path: Path):
    if not file_path.parent.exists():
        file_path.parent.mkdir(parents=True, exist_ok=True)
    if not file_path.is_file():
        file_path.write_text(json.dumps([]))

def _load(file_path: Path):
    _ensure_file(file_path)
    try:
        return json.loads(file_path.read_text())
    except Exception:
        return []

def _save(file_path: Path, data):
    file_path.write_text(json.dumps(data, ensure_ascii=False, indent=2))

def run(args: dict) -> str:
    action = args.get('action')
    if action == 'log_failure':
        query = args.get('query')
        if not query:
            return tool_error("'query' is required for log_failure.")
        reason = args.get('reason') or 'No matching skill'
        entry = {
            'timestamp': datetime.utcnow().isoformat(),
            'query': query,
            'reason': reason
        }
        log = _load(LOG_FILE)
        log.append(entry)
        _save(LOG_FILE, log)
        return tool_ok(entry, f"Logged failure: {query}")
    elif action == 'add_improvement':
        item = args.get('item')
        if not item:
            return tool_error("'item' is required for add_improvement.")
        items = _load(IMP_FILE)
        if item not in items:
            items.append(item)
            _save(IMP_FILE, items)
            return tool_ok({"item": item}, f"Added improvement: {item}")
        else:
            return tool_ok({"item": item}, f"Improvement already exists: {item}")
    elif action == 'list_improvements':
        items = _load(IMP_FILE)
        return tool_ok({"improvements": items}, f"{len(items)} improvement(s)")
    elif action == 'list_failures':
        log = _load(LOG_FILE)
        return tool_ok({"failures": log}, f"{len(log)} failure(s)")
    elif action == 'help':
        return tool_ok(None, "Actions: log_failure, add_improvement, list_improvements, list_failures, help")
    else:
        return tool_error(f"Unknown action '{action}'. Use action='help' for usage.")
