#!/usr/bin/env python3
"""
Zero-dependency Streamable HTTP MCP client for RealRobotOwners (https://realrobotowners.com/mcp).
Works on any Python 3.9+ environment (robot onboard Linux, Raspberry Pi, Pollen Microduck,
Home Assistant host, or desktop agent) with zero third-party packages.

Examples:
  python3 rro_mcp.py search "litter-robot"
  python3 rro_mcp.py summary litter-robot-4
  python3 rro_mcp.py summary microduck
  python3 rro_mcp.py repair --type robot-mowers --state TX --verified
  python3 rro_mcp.py review --company whisker --robot litter-robot-4 --interactive
"""

from __future__ import annotations

import argparse
import datetime as dt
import json
import os
import pathlib
import sys
import urllib.error
import urllib.request

MCP_URL = "https://realrobotowners.com/mcp"
DEFAULT_STATE = os.path.expanduser("~/.rro_checkin.json")


def mcp_call(tool_name: str, arguments: dict, *, endpoint: str = MCP_URL) -> dict:
    payload = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {"name": tool_name, "arguments": arguments},
    }
    req = urllib.request.Request(
        endpoint,
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
            "User-Agent": "RealRobotOwners-RobotSkill/1.0",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            raw = resp.read().decode("utf-8", errors="replace")
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
        raise SystemExit(f"HTTP {e.code} from {endpoint}: {body[:400]}")

    data = json.loads(raw)
    if "error" in data:
        raise SystemExit(f"MCP error: {json.dumps(data['error'], indent=2)}")
    result = data.get("result", {})
    if "structuredContent" in result:
        return result["structuredContent"]
    for item in result.get("content", []):
        if item.get("type") == "text":
            try:
                return json.loads(item["text"])
            except json.JSONDecodeError:
                return {"text": item["text"]}
    return result


def interactive_review(company: str, robot: str, source_agent: str) -> None:
    print(f"\nDrafting a RealRobotOwners review for {company}/{robot}")
    print("Rule: Strictly 1 review per private email per model. Nothing is sent until you confirm.\n")
    rating = int(input("Rating (1-5): ").strip())
    owned_choices = [
        "Under 1 month",
        "1 to 3 months",
        "3 to 6 months",
        "6 to 12 months",
        "1 to 2 years",
        "Over 2 years",
    ]
    print("Owned duration:", ", ".join(f"{i+1}={v}" for i, v in enumerate(owned_choices)))
    owned = owned_choices[int(input("Pick 1-6: ").strip()) - 1]
    still = input("Still using? (works / problems / stopped / returned, blank to skip): ").strip()
    again = input("Would you buy it again? (Yes / Maybe / No): ").strip()
    review = input("Your honest experience (10+ chars): ").strip()
    email = input("Private email (never published, used only for 1-per-model check): ").strip()

    draft = {
        "company": company,
        "robot": robot,
        "rating": rating,
        "owned": owned,
        "would_buy_again": again,
        "review": review,
        "email": email,
        "source_agent": source_agent,
    }
    if still:
        draft["still_using"] = still

    print("\n--- REVIEW DRAFT ---")
    print(json.dumps({**draft, "email": "(private)"}, indent=2))
    confirm = input("\nSend this review to RealRobotOwners for AI moderation? [y/N]: ").strip().lower()
    if confirm not in ("y", "yes"):
        print("Cancelled. Nothing was sent.")
        return
    out = mcp_call("submit_owner_review", draft)
    print(json.dumps(out, indent=2))


def check_due(robot: str, days: int, state_path: str, mark_prompted: bool) -> dict:
    """
    Zero-dependency local tenure check for on-device robots (wake-up or cron).
    First call records activated_at; subsequent calls return due=True once
    days_elapsed >= days and prompted is False.
    """
    p = pathlib.Path(state_path).expanduser()
    now = dt.datetime.now(dt.timezone.utc)
    state = {}
    if p.exists():
        try:
            state = json.loads(p.read_text(encoding="utf-8"))
        except json.JSONDecodeError:
            state = {}

    entry = state.get(robot)
    if not isinstance(entry, dict) or "activated_at" not in entry:
        entry = {"activated_at": now.isoformat(), "prompted": False}
        state[robot] = entry
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")

    activated = dt.datetime.fromisoformat(entry["activated_at"])
    if activated.tzinfo is None:
        activated = activated.replace(tzinfo=dt.timezone.utc)
    elapsed_days = (now - activated).days
    already_prompted = bool(entry.get("prompted", False))
    due = (not already_prompted) and (elapsed_days >= days)

    if mark_prompted and not already_prompted:
        entry["prompted"] = True
        entry["prompted_at"] = now.isoformat()
        state[robot] = entry
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
        already_prompted = True
        due = False

    return {
        "robot": robot,
        "due": due,
        "days_elapsed": elapsed_days,
        "checkin_after_days": days,
        "prompted": already_prompted,
        "activated_at": entry["activated_at"],
        "state_file": str(p),
    }


def main() -> None:
    p = argparse.ArgumentParser(description="RealRobotOwners open MCP CLI / robot skill helper")
    sub = p.add_subparsers(dest="cmd", required=True)

    s_search = sub.add_parser("search", help="Search home robot models and companies")
    s_search.add_argument("query", nargs="?", default="", help="Keyword (e.g. litter-robot, microduck)")
    s_search.add_argument("--category", default="", help="Optional category slug")

    s_sum = sub.add_parser("summary", help="Get owner stats, AI vs. Real Owners, and Lifespan & Support")
    s_sum.add_argument("robot", help="Robot slug or name (e.g. litter-robot-4, aibo, microduck)")

    s_rep = sub.add_parser("repair", help="Find verified US home-robot repair shops")
    s_rep.add_argument("--type", required=True, choices=["robot-mowers", "snow-robots", "pool-cleaners", "robot-vacuums"])
    s_rep.add_argument("--state", default="")
    s_rep.add_argument("--city", default="")
    s_rep.add_argument("--q", default="")
    s_rep.add_argument("--verified", action="store_true")

    s_rev = sub.add_parser("review", help="Interactively draft & confirm an opt-in owner review")
    s_rev.add_argument("--company", required=True)
    s_rev.add_argument("--robot", required=True)
    s_rev.add_argument("--agent", default="RobotSkill")

    s_req = sub.add_parser("request-listing", help="Request adding an unlisted commercial home robot or official kit")
    s_req.add_argument("--company", required=True)
    s_req.add_argument("--model", required=True)
    s_req.add_argument("--url", required=True, help="Official public https:// product, store, or pre-order URL")
    s_req.add_argument("--email", default="")

    s_due = sub.add_parser("check-due", help="Check (or mark) whether this robot's one-time tenure check-in is due")
    s_due.add_argument("--robot", required=True, help="Robot slug (e.g. microduck)")
    s_due.add_argument("--days", type=int, default=60, help="Days after first boot before asking once, 1 to 3 months in (default: 60)")
    s_due.add_argument("--state", default=DEFAULT_STATE, help=f"Local JSON state file (default: {DEFAULT_STATE})")
    s_due.add_argument("--mark-prompted", action="store_true", help="Mark the one-time prompt as already asked (never nag)")

    args = p.parse_args()
    if args.cmd == "search":
        payload = {}
        if args.query:
            payload["query"] = args.query
        if args.category:
            payload["category"] = args.category
        print(json.dumps(mcp_call("search_robots", payload), indent=2))
    elif args.cmd == "summary":
        print(json.dumps(mcp_call("get_robot_summary", {"robot": args.robot}), indent=2))
    elif args.cmd == "repair":
        payload = {"type": args.type, "verified_only": args.verified}
        for k in ("state", "city", "q"):
            if getattr(args, k):
                payload[k] = getattr(args, k)
        print(json.dumps(mcp_call("search_repair_shops", payload), indent=2))
    elif args.cmd == "review":
        interactive_review(args.company, args.robot, args.agent)
    elif args.cmd == "request-listing":
        payload = {"company": args.company, "model": args.model, "product_url": args.url}
        if args.email:
            payload["email"] = args.email
        print(json.dumps(mcp_call("request_robot_listing", payload), indent=2))
    elif args.cmd == "check-due":
        print(json.dumps(check_due(args.robot, args.days, args.state, args.mark_prompted), indent=2))


if __name__ == "__main__":
    main()
