"""
Radar — Opportunity Discovery & Scoring Engine.
Scans target subreddits, matches keywords, scores posts, and queues opportunities.
"""

import re
from config import (
    HIGH_INTENT_KEYWORDS, MEDIUM_INTENT_KEYWORDS, LOW_INTENT_KEYWORDS,
    SCORING, ALL_SUBS,
)
from reddit_client import get_new_posts, get_rising_posts, search_subreddit
from storage import save_opportunity, is_already_found, has_commented_on

# Import competitors from config if defined, otherwise use empty list
try:
    from config import BRAND_COMPETITORS
except ImportError:
    BRAND_COMPETITORS = []


def scan_subreddits(sub_names=None, mode="new", limit=15):
    if sub_names is None:
        sub_names = [s["name"] for s in ALL_SUBS]

    all_opportunities = []

    for sub_name in sub_names:
        print(f"  📡 Scanning r/{sub_name} ({mode})...")

        if mode == "rising":
            posts = get_rising_posts(sub_name, limit=limit)
        elif mode == "keyword":
            posts = _keyword_search(sub_name, limit=limit)
        else:
            posts = get_new_posts(sub_name, limit=limit)

        for post in posts:
            if is_already_found(post["post_id"]) or has_commented_on(post["post_id"]):
                continue

            opp = score_opportunity(post)
            if opp["opportunity_score"] > 0:
                save_opportunity(opp)
                all_opportunities.append(opp)

    all_opportunities.sort(key=lambda x: x["opportunity_score"], reverse=True)
    print(f"  ✅ Found {len(all_opportunities)} new opportunities")
    return all_opportunities


def _keyword_search(sub_name, limit=15):
    posts = []
    seen = set()
    search_terms = [
        "PTO tracking", "onboarding", "employee handbook",
        "HR software", "time off", "employee directory",
    ]
    for term in search_terms:
        results = search_subreddit(sub_name, term, limit=5)
        for p in results:
            if p["post_id"] not in seen:
                seen.add(p["post_id"])
                posts.append(p)
            if len(posts) >= limit:
                break
    return posts[:limit]


def score_opportunity(post):
    score = 0.0
    matched_keywords = []
    intent_level = "low"
    brand_mention_worthy = False

    text = f"{post['title']} {post.get('selftext', '')}".lower()

    # Keyword matching
    high_matches = _match_keywords(text, HIGH_INTENT_KEYWORDS)
    med_matches = _match_keywords(text, MEDIUM_INTENT_KEYWORDS)
    low_matches = _match_keywords(text, LOW_INTENT_KEYWORDS)

    if high_matches:
        score += SCORING["high_intent_keyword"] * len(high_matches)
        matched_keywords.extend(high_matches)
        intent_level = "high"
        brand_mention_worthy = True
    if med_matches:
        score += SCORING["medium_intent_keyword"] * len(med_matches)
        matched_keywords.extend(med_matches)
        if intent_level != "high":
            intent_level = "medium"
    if low_matches:
        score += SCORING["low_intent_keyword"] * len(low_matches)
        matched_keywords.extend(low_matches)

    # Post characteristics
    if _is_question(post["title"]):
        score += SCORING["is_question"]

    if post["num_comments"] < 10:
        score += SCORING["low_comment_count"]
    elif post["num_comments"] > 50:
        score += SCORING["high_comment_count"]

    if post.get("upvote_ratio", 0) > 0.85 and post.get("score", 0) > 5:
        score += SCORING["rising_post"]

    age_hours = post.get("age_hours", 99)
    if age_hours < 4:
        score += SCORING["new_post"]
    elif age_hours > 24:
        score += SCORING["old_post"]

    # Competitor mentions
    for comp in BRAND_COMPETITORS:
        if comp.lower() in text:
            score += SCORING["competitor_thread"]
            brand_mention_worthy = True
            matched_keywords.append(f"competitor:{comp}")

    # Subreddit tier
    sub_config = _get_sub_tier(post["subreddit"])
    if sub_config:
        tier = sub_config.get("tier", 3)
        score += SCORING.get(f"tier_{tier}_sub", 0)
        if not sub_config.get("brand_ok", False):
            brand_mention_worthy = False

    return {
        **post,
        "opportunity_score": round(max(score, 0), 1),
        "intent_level": intent_level,
        "matched_keywords": matched_keywords,
        "brand_mention_worthy": brand_mention_worthy,
    }


def _match_keywords(text, keywords):
    matched = []
    for kw in keywords:
        if kw.lower() in text:
            matched.append(kw)
    return matched


def _is_question(title):
    question_patterns = [
        r"\?$", r"^how ", r"^what ", r"^why ", r"^when ",
        r"^where ", r"^who ", r"^which ", r"^should ",
        r"^can ", r"^does ", r"^do you ", r"^is there ",
        r"^anyone ", r"^has anyone ", r"^looking for ",
        r"^recommend", r"^suggestion", r"^advice ",
        r"^help ", r"^need help",
    ]
    title_lower = title.lower().strip()
    return any(re.search(p, title_lower) for p in question_patterns)


def _get_sub_tier(sub_name):
    for s in ALL_SUBS:
        if s["name"].lower() == sub_name.lower():
            return s
    return None
