"""Minimal local HTTP server exposing the Complaint Guidance Agent as `agent_ask`.

Deliberately small — this is a dev/demo server, not a production API. Session state is an
in-memory dict, same known limitation as the original build (see project memory: "no
durable/auditable session-state store").
"""
import argparse
import json
import os
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

from agent_core import ReasoningAgent

ROOT = Path(__file__).parent
AGENT = ReasoningAgent()
SESSIONS = {}   # session_id -> list of {"note", "response"} turns
FACTS = {}      # session_id -> facts dict carried across turns


def dispatch(body):
    action = body.get("action")

    if action == "health":
        return {"ok": True}

    if action == "groq_probe":
        # One-off connectivity test: can this App Runner service reach Groq's public API?
        # Fetches the key from Secrets Manager at call time rather than via an env var, so
        # this probe needs no redeploy-time secret wiring beyond IAM read access.
        import requests
        import boto3
        try:
            sm = boto3.client("secretsmanager", region_name="us-east-1")
            key = sm.get_secret_value(
                SecretId="arn:aws:secretsmanager:us-east-1:039324591237:secret:esure-complaint-guidance-v2/groq-api-key-LGNP4y"
            )["SecretString"]
            r = requests.get("https://api.groq.com/openai/v1/models",
                              headers={"Authorization": f"Bearer {key}"}, timeout=10)
            return {"ok": r.status_code == 200, "status": r.status_code,
                    "body_snippet": r.text[:300]}
        except Exception as exc:  # noqa: BLE001
            return {"ok": False, "error": str(exc)}

    if action == "agent_ask":
        session_id = body.get("session_id") or "default"
        history = SESSIONS.setdefault(session_id, [])
        result = AGENT.run(body.get("text", ""), history=history, carried=FACTS.get(session_id))
        FACTS[session_id] = result["facts"]
        history.append({"note": body.get("text", ""),
                         "response_json": result.pop("_response_json", None)})
        result["turn"] = len(history)
        return result

    if action == "reset":
        session_id = body.get("session_id") or "default"
        SESSIONS.pop(session_id, None)
        FACTS.pop(session_id, None)
        return {"ok": True}

    return {"error": "unknown action: %r" % action}


class Handler(SimpleHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length") or 0)
        try:
            body = json.loads(self.rfile.read(length) or b"{}")
            result = dispatch(body)
            status = 200
        except Exception as exc:  # noqa: BLE001 - surface any failure to the caller, not a 500 wall
            result = {"error": str(exc)}
            status = 400
        payload = json.dumps(result).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def log_message(self, fmt, *args):
        print("%s - %s" % (self.address_string(), fmt % args))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--port", type=int, default=4173)
    args = parser.parse_args()
    os.chdir(ROOT)
    host = os.environ.get("BIND_HOST", "127.0.0.1")
    print("Workspace: http://%s:%s/workspace.html" % (host, args.port))
    ThreadingHTTPServer((host, args.port), Handler).serve_forever()


if __name__ == "__main__":
    main()
