#!/usr/bin/env python3
"""
JARVIS CLI — Reddit Growth Engine (No Auth Required)
=====================================================
Uses public Reddit JSON endpoints. No API key needed.

Usage:
    python cli.py scan [--mode new|rising|keyword|deep] [--subs sub1,sub2] [--limit N]
    python cli.py opportunities [--limit N]
    python cli.py thread <post_id> [--brief]
    python cli.py karma [--user USERNAME]
    python cli.py stats [--all]
    python cli.py health
    python cli.py mission
    python cli.py history [--limit N]
    python cli.py posted <post_id> "<comment_text>" [--brand]
    python cli.py skip <post_id>
    python cli.py search <subreddit> <query> [--limit N]
    python cli.py comments [--user USERNAME] [--limit N]
"""

import argparse
import json
import sys
from datetime import datetime, timedelta


def cmd_scan(args):
    from radar import scan_subreddits
    from config import TIER_1_SUBS, TIER_2_SUBS, TIER_3_SUBS, TIER_4_SUBS, ALL_SUBS

    mode = args.mode or "new"
    limit = args.limit or 10

    if args.subs:
        sub_names = [s.strip() for s in args.subs.split(",")]
    elif mode == "deep":
        sub_names = [s["name"] for s in ALL_SUBS]
    else:
        sub_names = [s["name"] for s in TIER_1_SUBS + TIER_2_SUBS]

    print(f"Scanning {len(sub_names)} subreddits ({mode} mode)...\n")

    if mode == "deep":
        opps_new = scan_subreddits(sub_names, mode="new", limit=limit)
        opps_rising = scan_subreddits(sub_names, mode="rising", limit=limit)
        opps = opps_new + opps_rising
        opps.sort(key=lambda x: x["opportunity_score"], reverse=True)
    else:
        opps = scan_subreddits(sub_names, mode=mode, limit=limit)

    print(f"\n{'='*80}")
    print(f"FOUND {len(opps)} NEW OPPORTUNITIES")
    print(f"{'='*80}\n")
    _print_opportunities(opps[:20])


def cmd_opportunities(args):
    from storage import get_opportunities

    limit = args.limit or 15
    opps = get_opportunities(status="new", limit=limit)

    if not opps:
        print("No opportunities queued. Run 'python cli.py scan' first.")
        return

    print(f"TOP {len(opps)} OPPORTUNITIES")
    print(f"{'='*80}\n")
    _print_opportunities(opps)


def cmd_thread(args):
    from reddit_client import get_post_with_comments
    from storage import is_already_found, has_commented_on
    from config import ALL_SUBS

    post_id = args.post_id

    if args.brief:
        post = get_post_with_comments(post_id, comment_limit=0)
        if not post:
            print(f"ERROR: Could not fetch post {post_id}")
            return
        print(f"SUBREDDIT: r/{post['subreddit']}")
        print(f"TITLE: {post['title']}")
        print(f"AUTHOR: u/{post['author']}")
        print(f"SCORE: {post['score']} | COMMENTS: {post['num_comments']}")
        print(f"URL: {post['url']}")
        print(f"\nPOST BODY:\n{post['selftext'][:3000] if post['selftext'] else '(no body)'}")
        return

    post = get_post_with_comments(post_id, comment_limit=30)
    if not post:
        print(f"ERROR: Could not fetch post {post_id}")
        return

    print(f"{'='*80}")
    print(f"THREAD: r/{post['subreddit']}")
    print(f"{'='*80}")
    print(f"TITLE: {post['title']}")
    print(f"AUTHOR: u/{post['author']}")
    print(f"SCORE: {post['score']} | UPVOTE RATIO: {post.get('upvote_ratio', '?')}")
    print(f"COMMENTS: {post['num_comments']} | AGE: {post.get('age_hours', '?')} hours")
    print(f"URL: {post['url']}")
    print(f"FLAIR: {post.get('link_flair_text', 'none')}")

    if post.get("selftext"):
        print(f"\n{'─'*40}")
        print(f"POST BODY:")
        print(f"{'─'*40}")
        print(post["selftext"][:3000])

    comments = post.get("comments", [])
    if comments:
        print(f"\n{'─'*40}")
        print(f"COMMENTS ({len(comments)} shown):")
        print(f"{'─'*40}")
        for c in comments:
            op_tag = " [OP]" if c.get("is_op") else ""
            print(f"\n  [{c['score']} pts] u/{c['author']}{op_tag}:")
            body = c["body"][:500]
            if len(c["body"]) > 500:
                body += "..."
            for line in body.split("\n"):
                print(f"    {line}")

    print(f"\n{'─'*40}")
    print(f"STATUS:")
    print(f"  Already tracked: {'Yes' if is_already_found(post_id) else 'No'}")
    print(f"  Already commented: {'Yes' if has_commented_on(post_id) else 'No'}")

    for s in ALL_SUBS:
        if s["name"].lower() == post["subreddit"].lower():
            print(f"  Sub tier: {s['tier']}")
            print(f"  Sub tone: {s.get('tone', '?')}")
            print(f"  Brand OK: {'Yes' if s.get('brand_ok') else 'No'}")
            break


def cmd_search(args):
    from reddit_client import search_subreddit

    posts = search_subreddit(args.subreddit, args.query, limit=args.limit or 10)
    print(f"SEARCH: '{args.query}' in r/{args.subreddit}")
    print(f"{'='*80}\n")

    if not posts:
        print("No results found.")
        return

    for i, p in enumerate(posts):
        print(f"  {i+1}. [{p['score']}pts | {p['num_comments']}c | {p.get('age_hours', '?')}h] "
              f"r/{p['subreddit']}")
        print(f"     {p['title'][:75]}")
        print(f"     ID: {p['post_id']} | {p['url']}")
        print()


def cmd_karma(args):
    from reddit_client import get_user_about
    from config import REDDIT_USERNAME, COACH

    username = args.user or REDDIT_USERNAME
    info = get_user_about(username)

    if "error" in info and info.get("total_karma", 0) == 0:
        print(f"ERROR: {info['error']}")
        return

    print(f"ACCOUNT: u/{info.get('username', username)}")
    print(f"{'='*40}")
    print(f"  Comment Karma:  {info['comment_karma']}")
    print(f"  Link Karma:     {info['link_karma']}")
    print(f"  Total Karma:    {info['total_karma']}")
    print(f"  Account Age:    {info['account_age_days']} days")

    day = info["account_age_days"]
    if day <= 7:
        target_key = f"karma_target_day_{min(day, 7)}"
        target = COACH.get(target_key, 0)
        if target:
            status = "✅ ON TRACK" if info["total_karma"] >= target else "⚠️  BEHIND"
            print(f"  Day {day} Target:  {target} karma — {status}")


def cmd_comments(args):
    from reddit_client import get_user_comments
    from config import REDDIT_USERNAME

    username = args.user or REDDIT_USERNAME
    limit = args.limit or 15
    comments = get_user_comments(username, limit=limit)

    if not comments:
        print(f"No public comments found for u/{username}.")
        return

    print(f"RECENT COMMENTS by u/{username}")
    print(f"{'='*80}\n")

    for c in comments:
        print(f"  r/{c['subreddit']} | {c['score']} pts")
        print(f"  Re: {c.get('post_title', '?')[:60]}")
        print(f"  \"{c['body'][:120]}{'...' if len(c['body']) > 120 else ''}\"")
        print(f"  {c['permalink']}")
        print()


def cmd_stats(args):
    from storage import get_today_stats, get_all_time_stats
    from config import DAILY_LIMITS

    if args.all:
        stats = get_all_time_stats()
        print(f"ALL-TIME STATS")
        print(f"{'='*40}")
        print(f"  Total Comments:   {stats['total_comments']}")
        print(f"  Brand Mentions:   {stats['brand_mentions']}")
        print(f"  Helpful Ratio:    {stats['helpful_ratio']:.1f}:1")
        print()

        breakdown = stats.get("sub_breakdown", [])
        if breakdown:
            print(f"  SUBREDDIT BREAKDOWN:")
            print(f"  {'Sub':<25} {'Comments':>8}  {'Last Active':>12}")
            print(f"  {'─'*50}")
            for s in breakdown:
                last = s.get("last_active", "?")[:10] if s.get("last_active") else "?"
                print(f"  r/{s['subreddit']:<23} {s['cnt']:>8}  {last:>12}")
    else:
        stats = get_today_stats()
        remaining = DAILY_LIMITS["max_comments_total"] - stats["total_comments"]
        brand_remaining = DAILY_LIMITS["max_brand_mentions"] - stats["brand_mentions"]

        print(f"TODAY'S STATS ({stats['date']})")
        print(f"{'='*40}")
        print(f"  Comments:         {stats['total_comments']}/{DAILY_LIMITS['max_comments_total']} ({remaining} remaining)")
        print(f"  Brand Mentions:   {stats['brand_mentions']}/{DAILY_LIMITS['max_brand_mentions']} ({brand_remaining} remaining)")
        print(f"  Helpful Ratio:    {stats['helpful_ratio']:.1f}:1")
        print(f"  Subs Active:      {', '.join('r/' + s for s in stats['subs_active']) or 'none'}")


def cmd_health(args):
    from reddit_client import get_user_about
    from storage import get_today_stats, get_all_time_stats, get_sub_last_activity
    from config import COACH, DAILY_LIMITS, REDDIT_USERNAME

    karma = get_user_about(REDDIT_USERNAME)
    today = get_today_stats()
    all_time = get_all_time_stats()
    sub_activity = get_sub_last_activity()

    score = 100
    warnings = []
    recommendations = []

    day = karma.get("account_age_days", 0)
    total_karma = karma.get("total_karma", 0)

    if day <= 7:
        target = COACH.get(f"karma_target_day_{min(day, 7)}", 0)
        if target and total_karma < target:
            warnings.append(f"Karma behind: {total_karma} vs {target} target for Day {day}")
            score -= 15
        elif target:
            recommendations.append(f"Karma on track: {total_karma} (target: {target})")

    if all_time["brand_mentions"] > 0:
        ratio = all_time["helpful_ratio"]
        if ratio < 8:
            warnings.append(f"Ratio too low: {ratio:.1f}:1 — stop brand mentions until 8:1")
            score -= 25
        else:
            recommendations.append(f"Healthy ratio: {ratio:.1f}:1")

    breakdown = all_time.get("sub_breakdown", [])
    total = max(all_time.get("total_comments", 1), 1)
    if breakdown:
        top_pct = breakdown[0]["cnt"] / total
        if top_pct > COACH["diversification_warning"]:
            warnings.append(f"Over-concentrated: {top_pct:.0%} in r/{breakdown[0]['subreddit']} — diversify")
            score -= 10

    now = datetime.now()
    for sub, info in sub_activity.items():
        if info.get("last_active"):
            try:
                last = datetime.fromisoformat(info["last_active"])
                days_since = (now - last).days
                if days_since >= COACH["stale_sub_days"]:
                    warnings.append(f"Stale: r/{sub} — last active {days_since} days ago")
                    score -= 5
            except:
                pass

    if today["total_comments"] > 15:
        warnings.append(f"High volume today ({today['total_comments']} comments) — pace yourself")
        score -= 10

    if day < 3:
        recommendations.append("Account < 3 days: Stick to Tier 3 subs only")
    elif day < 7:
        recommendations.append("Account < 7 days: Can enter Tier 1-2 but tread carefully")

    score = max(0, min(100, score))

    print(f"PROFILE HEALTH")
    print(f"{'='*40}")
    print(f"  Health Score:    {score}/100")
    print(f"  Karma:           {total_karma} (Day {day})")
    print(f"  Total Comments:  {all_time['total_comments']}")
    print(f"  Brand Mentions:  {all_time['brand_mentions']}")

    if warnings:
        print(f"\n  WARNINGS:")
        for w in warnings:
            print(f"  ⚠️  {w}")

    if recommendations:
        print(f"\n  RECOMMENDATIONS:")
        for r in recommendations:
            print(f"  💡 {r}")


def cmd_mission(args):
    from reddit_client import get_user_about
    from storage import get_today_stats, get_all_time_stats, get_sub_last_activity
    from config import (COACH, DAILY_LIMITS, REDDIT_USERNAME,
                        TIER_1_SUBS, TIER_2_SUBS, TIER_3_SUBS, TIER_4_SUBS)

    karma = get_user_about(REDDIT_USERNAME)
    today = get_today_stats()
    all_time = get_all_time_stats()

    day = karma.get("account_age_days", 0)
    total_karma = karma.get("total_karma", 0)
    remaining = DAILY_LIMITS["max_comments_total"] - today["total_comments"]

    if day <= 2:
        phase = "Phase 1: Karma Sprint"
        tasks = [
            f"Target: {COACH.get('karma_target_day_1', 80)}+ karma",
            "Leave 15-20 comments in Tier 3 subs",
            "r/AskReddit — sort by Rising, hit work/career threads",
            "r/NoStupidQuestions — answer 5 questions",
            "r/LifeProTips — 3 workplace tips",
            "Reply to EVERY response tonight",
        ]
        focus = [s["name"] for s in TIER_3_SUBS]
        avoid = [s["name"] for s in TIER_1_SUBS + TIER_2_SUBS]
        brand_ok = False

    elif day <= 4:
        phase = "Phase 2: Bridge to Professional"
        tasks = [
            "6 professional + 6 general comments",
            "r/managers + r/Productivity — 3 each",
            "r/AskReddit — 6 comments (karma maintenance)",
            "Start LURKING r/smallbusiness + r/AskHR",
            "Reply to all overnight responses",
        ]
        focus = [s["name"] for s in TIER_2_SUBS + TIER_3_SUBS]
        avoid = [s["name"] for s in TIER_1_SUBS]
        brand_ok = False

    elif day <= 6:
        phase = "Phase 3: Enter Target Subs"
        tasks = [
            "r/smallbusiness — 3 detailed comments (5-7 sentences)",
            "r/AskHR — 2 expert answers",
            "r/humanresources — 1-2 careful comments",
            "r/managers + r/Entrepreneur — 2 each",
            "Set up keyword alerts if not done",
            "NO brand mentions yet",
        ]
        focus = [s["name"] for s in TIER_1_SUBS + TIER_2_SUBS]
        avoid = []
        brand_ok = False

    else:
        phase = "Phase 4: Brand Entry"
        ratio = all_time.get("helpful_ratio", 0)
        can_mention = ratio >= 8 or all_time.get("brand_mentions", 0) == 0

        if can_mention and today["brand_mentions"] == 0:
            tasks = [
                "Check keyword alerts for opportunities",
                "5-8 helpful comments across target subs",
                "IF natural opportunity: 1 brand mention with disclosure",
                "Focus on recommendation-ask threads",
                "Reply to all responses",
            ]
            brand_ok = True
        else:
            tasks = [
                f"Ratio: {ratio:.0f}:1 — {'healthy' if ratio >= 8 else 'need more helpful comments'}",
                "8-10 pure value comments",
                "Diversify across subs",
                "No brand mentions today",
            ]
            brand_ok = False

        focus = [s["name"] for s in TIER_1_SUBS + TIER_2_SUBS + TIER_4_SUBS]
        avoid = []

    sub_activity = get_sub_last_activity()
    now = datetime.now()
    stale = []
    for sub, info in sub_activity.items():
        if info.get("last_active"):
            try:
                last = datetime.fromisoformat(info["last_active"])
                if (now - last).days >= COACH["stale_sub_days"]:
                    stale.append(f"r/{sub} ({(now-last).days}d)")
            except:
                pass

    print(f"DAILY MISSION")
    print(f"{'='*40}")
    print(f"  Day:              {day}")
    print(f"  Phase:            {phase}")
    print(f"  Karma:            {total_karma}")
    print(f"  Comments Left:    {remaining}/{DAILY_LIMITS['max_comments_total']}")
    print(f"  Brand Mention OK: {'Yes (1 max)' if brand_ok else 'No'}")

    print(f"\n  TASKS:")
    for t in tasks:
        print(f"    → {t}")

    print(f"\n  FOCUS SUBS: {', '.join('r/' + s for s in focus[:8])}")
    if avoid:
        print(f"  AVOID: {', '.join('r/' + s for s in avoid)}")
    if stale:
        print(f"  STALE (re-engage): {', '.join(stale)}")


def cmd_history(args):
    from storage import get_recent_comments

    limit = args.limit or 10
    comments = get_recent_comments(limit=limit)

    if not comments:
        print("No comments recorded yet.")
        return

    print(f"RECENT COMMENTS (last {len(comments)})")
    print(f"{'='*80}\n")

    for c in comments:
        brand = " [BRAND]" if c.get("is_brand_mention") else ""
        ts = c.get("posted_at", "?")[:16] if c.get("posted_at") else "?"
        print(f"  r/{c['subreddit']}{brand} — {ts}")
        print(f"  Post: {c.get('post_title', '?')[:60]}")
        text_preview = c.get("comment_text", "")[:120]
        print(f"  \"{text_preview}{'...' if len(c.get('comment_text', '')) > 120 else ''}\"")
        print()


def cmd_posted(args):
    from storage import save_comment, mark_comment_posted, get_today_stats, get_db
    from config import DAILY_LIMITS

    stats = get_today_stats()
    if stats["total_comments"] >= DAILY_LIMITS["max_comments_total"]:
        print(f"⚠️  Daily limit reached ({DAILY_LIMITS['max_comments_total']} comments). Recording anyway.")

    if args.brand and stats["brand_mentions"] >= DAILY_LIMITS["max_brand_mentions"]:
        print(f"⚠️  Brand mention limit reached today. Recording anyway.")

    conn = get_db()
    opp = conn.execute("SELECT * FROM opportunities WHERE post_id = ?", (args.post_id,)).fetchone()
    conn.close()

    subreddit = dict(opp)["subreddit"] if opp else args.subreddit or "unknown"
    title = dict(opp)["title"] if opp else "unknown"
    url = dict(opp)["url"] if opp else ""

    save_comment(
        post_id=args.post_id,
        subreddit=subreddit,
        post_title=title,
        post_url=url,
        comment_text=args.comment_text,
        is_brand_mention=args.brand,
        status="posted"
    )
    mark_comment_posted(args.post_id)

    brand_tag = " [BRAND MENTION]" if args.brand else ""
    print(f"✅ Recorded: r/{subreddit}{brand_tag}")
    print(f"   Post: {title[:60]}")

    stats = get_today_stats()
    remaining = DAILY_LIMITS["max_comments_total"] - stats["total_comments"]
    print(f"   Today: {stats['total_comments']} comments, {remaining} remaining, ratio {stats['helpful_ratio']:.0f}:1")


def cmd_skip(args):
    from storage import update_opportunity_status
    update_opportunity_status(args.post_id, "skipped")
    print(f"✅ Skipped: {args.post_id}")


def _print_opportunities(opps):
    if not opps:
        print("  (none)")
        return

    print(f"  {'#':<3} {'Score':>5}  {'Sub':<20} {'Intent':<7} {'Brand':>5} {'Age':>5} {'💬':>4}  Title")
    print(f"  {'─'*90}")

    for i, opp in enumerate(opps):
        brand = "YES" if opp.get("brand_mention_worthy") else "—"
        age = f"{opp.get('age_hours', '?')}h" if isinstance(opp.get("age_hours"), (int, float)) else "?"
        title = opp.get("title", "")[:45]
        keywords = opp.get("matched_keywords", [])
        if isinstance(keywords, str):
            try:
                keywords = json.loads(keywords)
            except:
                keywords = []
        kw_str = f" [{', '.join(keywords[:2])}]" if keywords else ""

        print(f"  {i+1:<3} {opp.get('opportunity_score', 0):>5.0f}  "
              f"r/{opp.get('subreddit', ''):<18} {opp.get('intent_level', '?'):<7} "
              f"{brand:>5} {age:>5} {opp.get('num_comments', '?'):>4}  "
              f"{title}")
        if kw_str:
            print(f"  {'':>36}{kw_str}")

    print(f"\n  POST IDs:")
    for i, opp in enumerate(opps):
        print(f"    {i+1}. {opp.get('post_id', '?')}  (r/{opp.get('subreddit', '')})")


def main():
    parser = argparse.ArgumentParser(description="JARVIS — Reddit Growth Engine")
    subparsers = parser.add_subparsers(dest="command", help="Command to run")

    p_scan = subparsers.add_parser("scan", help="Scan subreddits for opportunities")
    p_scan.add_argument("--mode", choices=["new", "rising", "keyword", "deep"], default="new")
    p_scan.add_argument("--subs", help="Comma-separated subreddit names")
    p_scan.add_argument("--limit", type=int, default=10)

    p_opps = subparsers.add_parser("opportunities", help="Show queued opportunities")
    p_opps.add_argument("--limit", type=int, default=15)

    p_thread = subparsers.add_parser("thread", help="Fetch thread for analysis")
    p_thread.add_argument("post_id", help="Reddit post ID")
    p_thread.add_argument("--brief", action="store_true")

    p_search = subparsers.add_parser("search", help="Search a subreddit")
    p_search.add_argument("subreddit")
    p_search.add_argument("query")
    p_search.add_argument("--limit", type=int, default=10)

    p_karma = subparsers.add_parser("karma", help="Show karma and account info")
    p_karma.add_argument("--user", help="Username (defaults to config)")

    p_comments = subparsers.add_parser("comments", help="View user's public comments")
    p_comments.add_argument("--user", help="Username (defaults to config)")
    p_comments.add_argument("--limit", type=int, default=15)

    p_stats = subparsers.add_parser("stats", help="Show comment stats")
    p_stats.add_argument("--all", action="store_true")

    subparsers.add_parser("health", help="Profile health check")
    subparsers.add_parser("mission", help="Daily action plan")

    p_hist = subparsers.add_parser("history", help="Recent comments")
    p_hist.add_argument("--limit", type=int, default=10)

    p_posted = subparsers.add_parser("posted", help="Record a posted comment")
    p_posted.add_argument("post_id")
    p_posted.add_argument("comment_text")
    p_posted.add_argument("--brand", action="store_true")
    p_posted.add_argument("--subreddit", default="unknown")

    p_skip = subparsers.add_parser("skip", help="Skip an opportunity")
    p_skip.add_argument("post_id")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        return

    commands = {
        "scan": cmd_scan,
        "opportunities": cmd_opportunities,
        "thread": cmd_thread,
        "search": cmd_search,
        "karma": cmd_karma,
        "comments": cmd_comments,
        "stats": cmd_stats,
        "health": cmd_health,
        "mission": cmd_mission,
        "history": cmd_history,
        "posted": cmd_posted,
        "skip": cmd_skip,
    }

    fn = commands.get(args.command)
    if fn:
        try:
            fn(args)
        except Exception as e:
            print(f"ERROR: {e}")
            import traceback
            traceback.print_exc()
            sys.exit(1)


if __name__ == "__main__":
    main()
