from concurrent.futures import ThreadPoolExecutor, wait
import time

from .core import (
    get_user_info,
    get_user_groups,
    get_owned_groups,
    username_to_id,
    get_user_rap,
    get_full_body_thumbnail,
    get_last_location,
    get_friends_count,
    is_email_verified,
    is_premium,
    get_followers_count,
    get_following_count
)

state = {}
_cache = {}
_cache_ttl = 60.0
_executor = ThreadPoolExecutor(max_workers=10)

def init():
    state["ready"] = True

def search(username):
    if not state.get("ready"):
        raise RuntimeError("not initialized")

    key = str(username).lower().strip()
    now = time.time()
    cached = _cache.get(key)
    if cached and now - cached["ts"] < _cache_ttl:
        return cached["data"]

    fut_userdata = _executor.submit(get_user_info, username)
    fut_userid = _executor.submit(username_to_id, username)
    fut_groups = _executor.submit(get_user_groups, username)
    fut_owned = _executor.submit(get_owned_groups, username)
    fut_avatar = _executor.submit(get_full_body_thumbnail, username)
    fut_lastlocation = _executor.submit(get_last_location, username)
    fut_friends = _executor.submit(get_friends_count, username)
    fut_email = _executor.submit(is_email_verified, username)
    fut_premium = _executor.submit(is_premium, username)
    fut_followers = _executor.submit(get_followers_count, username)
    fut_following = _executor.submit(get_following_count, username)

    userdata = fut_userdata.result()
    if not userdata:
        return {"error": "user not found"}

    userid = fut_userid.result()
    if not userid:
        return {"error": "could not resolve user id"}

    fut_rap = _executor.submit(get_user_rap, userid)

    groups = fut_groups.result() or []
    owned = fut_owned.result() or []
    rap = fut_rap.result()
    avatar = fut_avatar.result()
    lastlocation = fut_lastlocation.result()
    friends = fut_friends.result()
    email = fut_email.result()
    premium = fut_premium.result()
    followers = fut_followers.result()
    following = fut_following.result()

    result = {
        **userdata,
        "groupsjoined": len(groups),
        "groupsowned": len(owned),
        "rap": rap,
        "avatar": avatar,
        "lastlocation": lastlocation,
        "friendscount": friends,
        "followerscount": followers,
        "followingcount": following,
        "emailverified": email,
        "premium": premium
    }

    _cache[key] = {"ts": now, "data": result}
    return result
