from __future__ import annotations

import json
import os
import urllib.parse
import urllib.request
from pump_scanner import fetch_new_coins, score_coin

BASE58 = frozenset("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")


def valid_mint(mint: str) -> bool:
    return isinstance(mint, str) and 32 <= len(mint) <= 44 and all(char in BASE58 for char in mint)


def x_search(query: str) -> dict:
    token = os.getenv("X_BEARER_TOKEN")
    if not token:
        return {"configured": False, "posts": [], "message": "X API is not configured"}
    params = urllib.parse.urlencode({"query": f"({query}) -is:retweet", "max_results": 10, "tweet.fields": "created_at,public_metrics,author_id"})
    request = urllib.request.Request(
        f"https://api.x.com/2/tweets/search/recent?{params}",
        headers={"Authorization": f"Bearer {token}", "User-Agent": "pump-research-dashboard/1.0"},
    )
    try:
        with urllib.request.urlopen(request, timeout=15) as response:
            payload = json.loads(response.read().decode())
        return {"configured": True, "posts": payload.get("data", []), "message": None}
    except Exception as exc:
        return {"configured": True, "posts": [], "message": str(exc)}


def proposal_for_mint(mint: str) -> dict:
    if not valid_mint(mint):
        return {"eligible": False, "mint": mint, "reasons": ["invalid Solana mint address format"]}
    matches = [coin for coin in fetch_new_coins(100) if coin.get("mint") == mint]
    if not matches:
        return {"eligible": False, "mint": mint, "reasons": ["mint was not found in the current pump.fun feed"]}
    coin = matches[0]
    reasons = list(coin["risk_flags"])
    reasons.extend([
        "live liquidity and price-impact check is not available",
        "sellability simulation is not available",
        "holder concentration and creator-wallet analysis is not available",
    ])
    social = x_search(f'"{mint}" OR "${coin["symbol"]}"')
    return {
        "eligible": False,
        "mint": mint,
        "coin": coin,
        "x": {"configured": social["configured"], "post_count": len(social["posts"]), "message": social["message"]},
        "reasons": reasons,
        "action": "No transaction created. Complete on-chain risk checks before any trade review.",
    }
