"""
core/youtube_channel.py
- Channel data extraction & analysis
- Competitor spying (advanced)
- Uses multi-key rotation
- Improved hashtag extraction
"""

import re
from collections import Counter
from datetime import datetime, timedelta, timezone
from core.youtube_keys import execute


# =====================================================
# Helpers
# =====================================================
def _format_num(n) -> str:
    try:
        n = int(n)
        if n >= 1_000_000_000:
            return f"{n/1_000_000_000:.2f}B"
        if n >= 1_000_000:
            return f"{n/1_000_000:.2f}M"
        if n >= 1_000:
            return f"{n/1_000:.1f}K"
        return str(n)
    except Exception:
        return str(n)


def _extract_channel_id(url_or_id: str) -> dict:
    if not url_or_id:
        return {"type": "id", "value": ""}
    s = url_or_id.strip()

    if re.fullmatch(r"UC[A-Za-z0-9_-]{22}", s):
        return {"type": "id", "value": s}

    m = re.search(r"youtube\.com/channel/(UC[A-Za-z0-9_-]{22})", s)
    if m:
        return {"type": "id", "value": m.group(1)}

    m = re.search(r"youtube\.com/@([A-Za-z0-9._-]+)", s)
    if m:
        return {"type": "handle", "value": m.group(1)}

    m = re.search(r"youtube\.com/(?:c|user)/([A-Za-z0-9._-]+)", s)
    if m:
        return {"type": "username", "value": m.group(1)}

    if s.startswith("@"):
        return {"type": "handle", "value": s[1:]}

    return {"type": "username", "value": s}


# ⭐ Hashtag regex (improved)
HASHTAG_RE = re.compile(r"#([A-Za-z0-9_\u1780-\u17FF]{2,})")


def _extract_hashtags(text: str) -> list[str]:
    """Extract hashtags from any text. Returns lowercase list."""
    if not text:
        return []
    return [h.lower() for h in HASHTAG_RE.findall(text)]


def generate_hashtags_from_tags(tags: list[str], max_count: int = 15) -> list[str]:
    """Generate hashtag suggestions from video tags (as fallback)."""
    if not tags:
        return []
    hashtags = []
    seen = set()
    for t in tags:
        clean = re.sub(r"[^A-Za-z0-9\u1780-\u17FF]", "", t.title().replace(" ", ""))
        if not clean or len(clean) < 3:
            continue
        h = f"#{clean}"
        if h.lower() in seen:
            continue
        seen.add(h.lower())
        hashtags.append(h)
        if len(hashtags) >= max_count:
            break
    return hashtags


# =====================================================
# Resolve channel
# =====================================================
def resolve_channel(url_or_id: str) -> dict | None:
    ident = _extract_channel_id(url_or_id)
    if not ident["value"]:
        return None

    params = {"part": "snippet,statistics,contentDetails,brandingSettings,status"}
    if ident["type"] == "id":
        params["id"] = ident["value"]
    elif ident["type"] == "handle":
        params["forHandle"] = ident["value"]
    else:
        params["forUsername"] = ident["value"]

    def _req(service):
        return service.channels().list(**params)

    try:
        resp = execute(_req)
        items = resp.get("items", [])
        if items:
            return _parse_channel(items[0])
    except Exception:
        pass

    if ident["type"] in ("handle", "username"):
        q = ident["value"]

        def _search(service):
            return service.search().list(
                part="snippet", q=q, type="channel", maxResults=1
            )
        try:
            resp = execute(_search)
            items = resp.get("items", [])
            if items:
                cid = items[0]["id"]["channelId"]
                return resolve_channel(cid)
        except Exception:
            pass

    return None


def _parse_channel(c: dict) -> dict:
    sn = c.get("snippet", {})
    st = c.get("statistics", {})
    cd = c.get("contentDetails", {})
    bs = c.get("brandingSettings", {}).get("image", {})
    brand = c.get("brandingSettings", {}).get("channel", {})

    subs = int(st.get("subscriberCount", 0) or 0)
    views = int(st.get("viewCount", 0) or 0)
    videos = int(st.get("videoCount", 0) or 0)

    avg_views = round(views / videos) if videos else 0
    eng_rate = round((views / (subs * videos) * 100), 2) if subs and videos else 0

    return {
        "id": c["id"],
        "title": sn.get("title", ""),
        "description": sn.get("description", ""),
        "custom_url": sn.get("customUrl", ""),
        "published_at": sn.get("publishedAt", ""),
        "country": sn.get("country", ""),
        "default_language": sn.get("defaultLanguage", ""),
        "thumbnail": sn.get("thumbnails", {}).get("high", {}).get("url", ""),
        "banner": bs.get("bannerExternalUrl", ""),
        "subs": subs,
        "subs_fmt": _format_num(subs),
        "views": views,
        "views_fmt": _format_num(views),
        "videos": videos,
        "videos_fmt": _format_num(videos),
        "avg_views": avg_views,
        "avg_views_fmt": _format_num(avg_views),
        "engagement_rate": eng_rate,
        "uploads_playlist": cd.get("relatedPlaylists", {}).get("uploads", ""),
        "hidden_subs": st.get("hiddenSubscriberCount", False),
        "keywords_raw": brand.get("keywords", ""),
    }


# =====================================================
# Get recent uploads
# =====================================================
def get_recent_videos(channel_id: str, uploads_playlist: str,
                      max_results: int = 50) -> list[dict]:
    if not uploads_playlist:
        return []

    video_ids = []

    def _pl(service):
        return service.playlistItems().list(
            part="contentDetails",
            playlistId=uploads_playlist,
            maxResults=min(max_results, 50),
        )
    try:
        resp = execute(_pl)
        for it in resp.get("items", []):
            vid = it.get("contentDetails", {}).get("videoId")
            if vid:
                video_ids.append(vid)
    except Exception as e:
        print(f"playlistItems error: {e}")
        return []

    if not video_ids:
        return []

    def _vids(service):
        return service.videos().list(
            part="snippet,statistics,contentDetails",
            id=",".join(video_ids),
            maxResults=50,
        )
    try:
        resp = execute(_vids)
    except Exception as e:
        print(f"videos.list error: {e}")
        return []

    out = []
    for v in resp.get("items", []):
        sn = v.get("snippet", {})
        st = v.get("statistics", {})
        cd = v.get("contentDetails", {})

        views = int(st.get("viewCount", 0) or 0)
        likes = int(st.get("likeCount", 0) or 0)
        comments = int(st.get("commentCount", 0) or 0)

        desc = sn.get("description", "") or ""
        title = sn.get("title", "") or ""

        out.append({
            "id": v["id"],
            "title": title,
            "published_at": sn.get("publishedAt", ""),
            "thumbnail": sn.get("thumbnails", {}).get("medium", {}).get("url", ""),
            "thumbnails": sn.get("thumbnails", {}),
            "tags": sn.get("tags", []),
            "description": desc,
            "category_id": sn.get("categoryId", ""),
            "default_language": sn.get("defaultLanguage", ""),
            "views": views,
            "views_fmt": _format_num(views),
            "likes": likes,
            "likes_fmt": _format_num(likes),
            "comments": comments,
            "comments_fmt": _format_num(comments),
            # ⭐ Pre-extracted hashtags (from Description + Title)
            "desc_hashtags": _extract_hashtags(desc),
            "title_hashtags": _extract_hashtags(title),
        })
    return out


# =====================================================
# Channel Analytics
# =====================================================
def analyze_channel(channel: dict, videos: list[dict]) -> dict:
    if not videos:
        return {"total_analyzed": 0}

    top_by_views = sorted(videos, key=lambda v: v["views"], reverse=True)[:10]
    top_by_engagement = sorted(
        videos, key=lambda v: (v["likes"] + v["comments"]) / max(v["views"], 1),
        reverse=True
    )[:10]

    dates = []
    for v in videos:
        try:
            dates.append(datetime.fromisoformat(v["published_at"].replace("Z", "+00:00")))
        except Exception:
            pass

    freq_days = None
    if len(dates) >= 2:
        dates.sort(reverse=True)
        span_days = (dates[0] - dates[-1]).days
        if span_days > 0:
            freq_days = round(span_days / (len(dates) - 1), 1)

    day_counter = Counter()
    hour_counter = Counter()
    for dt in dates:
        day_counter[dt.strftime("%A")] += 1
        hour_counter[dt.hour] += 1

    tag_counter = Counter()
    for v in videos:
        for t in v.get("tags", []):
            tag_counter[t.lower()] += 1

    total_views = sum(v["views"] for v in videos)
    avg_views = round(total_views / len(videos)) if videos else 0
    total_likes = sum(v["likes"] for v in videos)
    total_comments = sum(v["comments"] for v in videos)

    eng_rates = []
    for v in videos:
        if v["views"] > 0:
            eng_rates.append((v["likes"] + v["comments"]) / v["views"] * 100)
    avg_eng = round(sum(eng_rates) / len(eng_rates), 2) if eng_rates else 0

    return {
        "total_analyzed": len(videos),
        "total_views": total_views,
        "total_views_fmt": _format_num(total_views),
        "avg_views": avg_views,
        "avg_views_fmt": _format_num(avg_views),
        "total_likes": total_likes,
        "total_comments": total_comments,
        "avg_engagement": avg_eng,
        "upload_freq_days": freq_days,
        "top_by_views": top_by_views,
        "top_by_engagement": top_by_engagement,
        "top_days": day_counter.most_common(7),
        "top_hours": hour_counter.most_common(24),
        "top_tags": tag_counter.most_common(20),
    }


# =====================================================
# Competitor Spy
# =====================================================
def spy_competitor(channel: dict, videos: list[dict], days: int = 30) -> dict:
    cutoff = datetime.now(timezone.utc) - timedelta(days=days)

    # Recent videos
    recent = []
    for v in videos:
        try:
            dt = datetime.fromisoformat(v["published_at"].replace("Z", "+00:00"))
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            if dt >= cutoff:
                recent.append(v)
        except Exception:
            pass

    # Best performers
    best = sorted(videos, key=lambda v: v["views"], reverse=True)[:10]

    # Tags
    tag_counter = Counter()
    for v in videos:
        for t in v.get("tags", []):
            tag_counter[t.lower()] += 1

    # Title words
    word_counter = Counter()
    for v in videos:
        for w in re.findall(r"\b\w{4,}\b", v["title"].lower()):
            word_counter[w] += 1

    # Schedule UTC + Local
    day_counter_utc = Counter()
    hour_counter_utc = Counter()
    day_counter_local = Counter()
    hour_counter_local = Counter()

    for v in videos:
        try:
            dt_utc = datetime.fromisoformat(v["published_at"].replace("Z", "+00:00"))
            if dt_utc.tzinfo is None:
                dt_utc = dt_utc.replace(tzinfo=timezone.utc)
            dt_local = dt_utc.astimezone()
            day_counter_utc[dt_utc.strftime("%A")] += 1
            hour_counter_utc[dt_utc.hour] += 1
            day_counter_local[dt_local.strftime("%A")] += 1
            hour_counter_local[dt_local.hour] += 1
        except Exception:
            pass

    # ============================================
    # HASHTAGS — real extraction
    # ============================================
    hashtag_counter = Counter()
    hashtag_per_video = {}

    for v in videos:
        dh = v.get("desc_hashtags", [])
        th = v.get("title_hashtags", [])

        # Fallback — extract fresh with improved regex
        if not dh:
            dh = _extract_hashtags(v.get("description", ""))
        if not th:
            th = _extract_hashtags(v.get("title", ""))

        all_h = list(set(dh + th))
        hashtag_per_video[v["id"]] = all_h

        for h in all_h:
            hashtag_counter[h] += 1

    videos_with_hashtags = sum(1 for hs in hashtag_per_video.values() if hs)

    # Title hashtags (all, unique)
    title_hashtags_all = []
    for v in videos:
        for h in v.get("title_hashtags", []):
            title_hashtags_all.append(f"#{h}")

    # Hashtag suggestions from tags (as extra)
    top_tags_list = [t for t, _ in tag_counter.most_common(30)]
    tags_hashtag_suggestions = generate_hashtags_from_tags(top_tags_list, max_count=20)

    # Category breakdown
    category_counter = Counter()
    for v in videos:
        cid = v.get("category_id", "")
        if cid:
            category_counter[cid] += 1

    # Thumbnails
    thumbnails = []
    for v in videos:
        if v.get("thumbnail"):
            thumbnails.append({
                "title": v["title"],
                "url": v["thumbnail"],
                "video_id": v["id"],
                "views": v["views"],
            })

    # Descriptions + links
    desc_lengths = []
    link_counter = Counter()
    for v in videos:
        d = v.get("description", "") or ""
        desc_lengths.append(len(d))
        for url in re.findall(r"https?://[^\s]+", d):
            domain = re.sub(r"https?://(www\.)?", "", url).split("/")[0]
            link_counter[domain] += 1

    avg_desc_len = round(sum(desc_lengths) / len(desc_lengths)) if desc_lengths else 0

    # Frequency
    freq = None
    valid_dates = []
    for v in videos:
        try:
            valid_dates.append(datetime.fromisoformat(v["published_at"].replace("Z", "+00:00")))
        except Exception:
            pass
    if len(valid_dates) >= 2:
        valid_dates.sort(reverse=True)
        span = (valid_dates[0] - valid_dates[-1]).days
        if span > 0:
            freq = round(span / (len(valid_dates) - 1), 1)

    # Channel keywords
    channel_keywords_list = []
    kw_raw = channel.get("keywords_raw", "") or ""
    if kw_raw:
        try:
            matches = re.findall(r'"([^"]+)"|(\S+)', kw_raw)
            for a, b in matches:
                val = (a or b).strip()
                if len(val) > 2:
                    channel_keywords_list.append(val)
        except Exception:
            channel_keywords_list = [k.strip() for k in kw_raw.split() if len(k.strip()) > 2]

    # Local timezone
    try:
        local_tz_name = datetime.now().astimezone().tzname() or "Local"
    except Exception:
        local_tz_name = "Local"

    return {
        "days": days,
        "recent_videos": recent,
        "recent_count": len(recent),
        "best_performers": best,
        "top_tags": tag_counter.most_common(25),
        "top_title_words": word_counter.most_common(20),
        "top_days_utc": day_counter_utc.most_common(7),
        "top_hours_utc": hour_counter_utc.most_common(24),
        "top_days_local": day_counter_local.most_common(7),
        "top_hours_local": hour_counter_local.most_common(24),
        "local_tz_name": local_tz_name,
        # Hashtags
        "top_hashtags": hashtag_counter.most_common(25),
        "title_hashtags": title_hashtags_all,
        "hashtag_per_video": hashtag_per_video,
        "videos_with_hashtags": videos_with_hashtags,
        "tags_hashtag_suggestions": tags_hashtag_suggestions,
        # Category
        "category_breakdown": category_counter.most_common(),
        # Others
        "thumbnails": thumbnails,
        "top_link_domains": link_counter.most_common(15),
        "avg_desc_length": avg_desc_len,
        "channel_keywords": channel_keywords_list,
        "upload_frequency_days": freq,
    }