import os
import json
import time
import importlib.util
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn

app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

# This serves index.html, script.js, style.css, and inter.css automatically
app.mount("/", StaticFiles(directory=".", html=True), name="static")

HISTORY_FILE = "memory.json"

# --- LOAD YOUR SCRIPTS ---
try:
    mod_a = importlib.import_module("script_a")
    mod_b = importlib.import_module("script_b")
    print("✅ Scripts loaded.")
except Exception as e:
    print(f"⚠️ Script load error: {e}")
    mod_a = None
    mod_b = None

# --- MEMORY FUNCTIONS ---
def save_memory(prompt, result):
    data = []
    if os.path.exists(HISTORY_FILE):
        with open(HISTORY_FILE, "r") as f:
            try:
                data = json.load(f)
            except:
                data = []
    data.append({"prompt": prompt, "result": result, "time": time.time()})
    with open(HISTORY_FILE, "w") as f:
        json.dump(data, f, indent=2)
    return {"status": "saved"}

def get_memory():
    if not os.path.exists(HISTORY_FILE):
        return []
    try:
        with open(HISTORY_FILE, "r") as f:
            return json.load(f)
    except:
        return []

def clear_memory():
    if os.path.exists(HISTORY_FILE):
        os.remove(HISTORY_FILE)
    return {"status": "cleared"}

# --- ENDPOINTS ---

@app.post("/memory-save")
async def memory_save(prompt: str = "", result: str = ""):
    save_memory(prompt, result)
    return {"status": "saved"}

@app.get("/memory-load")
async def memory_load():
    return get_memory()

@app.post("/memory-clear")
async def memory_clear():
    return clear_memory()

@app.post("/run-a")
async def run_a(prompt: str = ""):
    if not mod_a: return {"error": "Script A not loaded"}
    try:
        res = mod_a.func_a(prompt) 
        return {"result": str(res)}
    except Exception as e:
        return {"error": str(e)}

@app.post("/run-b")
async def run_b(prompt: str = ""):
    if not mod_b: return {"error": "Script B not loaded"}
    try:
        res = mod_b.func_b(prompt)
        return {"result": str(res)}
    except Exception as e:
        return {"error": str(e)}

@app.post("/run-workflow")
async def run_workflow(prompt: str = ""):
    if mod_a:
        try:
            res = mod_a.func_a(prompt)
            return {"output": str(res)}
        except Exception as e:
            return {"output": f"Error: {str(e)}"}
    return {"output": "No script loaded"}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)
