#!/usr/bin/env python3
"""
Moltgrowth CLI — Moltbook growth automation for agents.

Commands:
  status [account]   — karma, posts, comments
  post               — create post (--title, --content, --submolt, --account)
  comment            — add comment (post_id, --content, --account)
  upvote             — upvote post (post_id, --account)
  engage             — run engagement cycle (--account, --dry-run)
  feed               — list hot/new posts (--sort, --limit)
"""
import argparse
import sys

from . import __version__
from .api import comment as api_comment, feed as api_feed, me as api_me, post as api_post, upvote as api_upvote
from .config import load_config, get_api_key, get_track_file
from .engage import run_cycle


def cmd_status(args, cfg):
    account = args.account or "trenches"
    key = get_api_key(cfg, account)
    data = api_me(key)
    agent = data.get("agent", data)
    karma = agent.get("karma", "?")
    stats = agent.get("stats", {})
    posts = stats.get("posts", "?")
    comments = stats.get("comments", "?")
    name = agent.get("name", agent.get("username", "?"))
    print(f"{account} ({name}): karma={karma} posts={posts} comments={comments}")


def cmd_post(args, cfg):
    account = args.account or "trenches"
    key = get_api_key(cfg, account)
    if not args.title or not args.content:
        sys.exit("Usage: moltgrowth post --title TITLE --content CONTENT [--account X]")
    result = api_post(key, args.title, args.content, args.submolt)
    if result.get("success") and result.get("post"):
        pid = result["post"].get("id", result["post"].get("post_id", "?"))
        print(f"Posted: {pid}")
    else:
        print(f"Failed: {result.get('error', result)}")
        sys.exit(1)


def cmd_comment(args, cfg):
    account = args.account or "trenches"
    key = get_api_key(cfg, account)
    pid = getattr(args, "post_id", None)
    if not pid or not args.content:
        sys.exit("Usage: moltgrowth comment POST_ID --content TEXT [--account X]")
    result = api_comment(key, pid, args.content)
    if result.get("success"):
        print("Commented")
    else:
        print(f"Failed: {result.get('error', result)}")
        sys.exit(1)


def cmd_upvote(args, cfg):
    account = args.account or "trenches"
    key = get_api_key(cfg, account)
    pid = getattr(args, "post_id", None)
    if not pid:
        sys.exit("Usage: moltgrowth upvote POST_ID [--account X]")
    api_upvote(key, pid)
    print("Upvoted")


def cmd_engage(args, cfg):
    account = args.account or "trenches"
    if account not in cfg.get("accounts", {}):
        # Try both
        for a in ["trenches", "dgh"]:
            if a in cfg.get("accounts", {}):
                run_cycle(cfg, a, dry_run=args.dry_run)
        return
    run_cycle(cfg, account, dry_run=args.dry_run)


def cmd_engage_all(args, cfg):
    """Run engage for both trenches and dgh."""
    for a in ["trenches", "dgh"]:
        if a in cfg.get("accounts", {}):
            run_cycle(cfg, a, dry_run=args.dry_run)


def cmd_feed(args, cfg):
    account = args.account or "trenches"
    key = get_api_key(cfg, account)
    posts = api_feed(key, sort=args.sort, limit=args.limit)
    for p in posts:
        pid = p.get("id", p.get("post_id", "?"))
        title = (p.get("title") or p.get("content", ""))[:60]
        ups = p.get("upvotes", p.get("score", "?"))
        print(f"{pid}  [+{ups}] {title}")


def main():
    p = argparse.ArgumentParser(description="Moltgrowth — Moltbook growth CLI")
    p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
    sub = p.add_subparsers(dest="cmd", required=True)

    # status
    s = sub.add_parser("status", help="Show karma and stats")
    s.add_argument("--account", "-a", default="trenches", help="Account name")
    s.set_defaults(func=cmd_status)

    # post
    s = sub.add_parser("post", help="Create post")
    s.add_argument("--title", "-t", required=True)
    s.add_argument("--content", "-c", required=True)
    s.add_argument("--submolt", "-s", default="general")
    s.add_argument("--account", "-a", default="trenches")
    s.set_defaults(func=cmd_post)

    # comment
    s = sub.add_parser("comment", help="Add comment")
    s.add_argument("post_id", nargs="?", help="Post UUID")
    s.add_argument("--content", "-c", required=True, help="Comment text")
    s.add_argument("--account", "-a", default="trenches")
    s.set_defaults(func=cmd_comment)

    # upvote
    s = sub.add_parser("upvote", help="Upvote post")
    s.add_argument("post_id", nargs="?", help="Post UUID")
    s.add_argument("--account", "-a", default="trenches")
    s.set_defaults(func=cmd_upvote)

    # engage
    s = sub.add_parser("engage", help="Run engagement cycle (comment + upvote)")
    s.add_argument("--account", "-a", default=None, help="Account (default: both)")
    s.add_argument("--dry-run", action="store_true", help="Show what would be done")
    s.set_defaults(func=lambda a, c: cmd_engage_all(a, c) if a.account is None else cmd_engage(a, c))

    # feed
    s = sub.add_parser("feed", help="List hot/new posts")
    s.add_argument("--sort", default="hot", choices=["hot", "new"])
    s.add_argument("--limit", type=int, default=25)
    s.add_argument("--account", "-a", default="trenches")
    s.set_defaults(func=cmd_feed)

    args = p.parse_args()
    cfg = load_config()
    args.func(args, cfg)


if __name__ == "__main__":
    main()
