#!/usr/bin/env python3
"""Portable Task API Server v3.0"""
import sys
sys.path.insert(0, '../python/Lib/site-packages')

from flask import Flask, jsonify, request
from flask_cors import CORS
from datetime import datetime
import json
import os

app = Flask(__name__)
CORS(app)

DATA_DIR = os.path.dirname(os.path.abspath(__file__))
TASK_FILE = os.path.join(DATA_DIR, "task.json")
INBOX_FILE = os.path.join(DATA_DIR, "inbox.json")

def load_json(path):
    try:
        with open(path, 'r') as f: return json.load(f)
    except: return None

def save_json(path, data):
    with open(path, 'w') as f: json.dump(data, f, indent=2, default=str)

def load_inbox():
    try:
        with open(INBOX_FILE, 'r') as f: return json.load(f)
    except: return []

def add_inbox(msg):
    inbox = load_inbox()
    inbox.append(msg)
    with open(INBOX_FILE, 'w') as f: json.dump(inbox[-100:], f, indent=2, default=str)

@app.route('/health')
def health():
    return jsonify({"status": "ok", "version": "3.0"})

@app.route('/task', methods=['POST'])
def create_task():
    task_text = (request.json or {}).get('task', '')
    if not task_text: return jsonify({"error": "task required"}), 400
    task = {"id": datetime.now().strftime("%Y%m%d%H%M%S"), "task": task_text, "status": "pending"}
    save_json(TASK_FILE, task)
    add_inbox({"type": "task", "task": task_text, "id": task["id"], "time": datetime.now().isoformat()})
    return jsonify({"ok": True, "task_id": task["id"]})

@app.route('/task', methods=['GET'])
def get_task():
    task = load_json(TASK_FILE)
    if not task or task.get('status') == 'completed':
        return jsonify({"task": None})
    return jsonify({"task": task})

@app.route('/result', methods=['POST'])
def submit_result():
    data = request.json or {}
    task = load_json(TASK_FILE)
    if task:
        task['status'] = 'completed'
        task['result'] = data.get('result', '')
        save_json(TASK_FILE, task)
    add_inbox({"type": "result", "result": data.get('result', ''), "time": datetime.now().isoformat()})
    return jsonify({"ok": True})

@app.route('/inbox')
def get_inbox():
    return jsonify({"messages": load_inbox()[-int(request.args.get('limit', 10)):]})

@app.route('/status')
def status():
    return jsonify({"task": load_json(TASK_FILE), "inbox": len(load_inbox())})

@app.route('/')
def index():
    return "<h1>Task API v3.0</h1><p>POST /task, GET /task, POST /result, GET /inbox</p>"

if __name__ == '__main__':
    print("Task API Server on http://localhost:5054")
    app.run(host='0.0.0.0', port=5054)
