import time
import streamlit as st
from config import SESSION

from core.analysis import get_live_deviation_analysis
from core.portfolio import get_clob_client,get_user_positions, place_market_order

def run_dyn_auto_trader(interval_sec: int = 60, max_amount: float = 10.0,
                       min_score: float = 85.0, dry_run: bool = True): ######################not the version actually usable, new trading implementation on its way
    """Haupt-Funktion: dyn.py Scoring → Portfolio-Check → Order"""
    if "last_auto_trade" not in st.session_state:
        st.session_state.last_auto_trade = 0

    now = time.time()
    if now - st.session_state.last_auto_trade < interval_sec:
        return  # noch nicht Zeit

    st.session_state.last_auto_trade = now

    with st.spinner(f"Auto-Trade Cycle (alle {interval_sec}s) – dyn.py wird abgefragt..."):
        analysis, error = get_live_deviation_analysis(selected_slug)
        if error or not analysis:
            st.error(f"dyn.py-Fehler: {error}")
            return

        positions = get_user_positions(WALLET_ADDRESS)
        held_tokens = set(positions.keys())

        actions = []
        top_buckets = analysis["scored_buckets"][:3]   # nur Top 3 prüfen

        for bucket in top_buckets:
            token = bucket.get("token_id")
            score = bucket["score_pct"]
            label = bucket["label"]

            if not token:
                continue

            # === BUY LOGIC ===
            if score >= min_score and token not in held_tokens:
                result = place_market_order(token, "BUY", max_amount, dry_run)
                actions.append(f"🟢 BUY {label} (Score {score}%) → {result}")
                break  # max 1 neue Position pro Cycle

            # === SELL LOGIC (Close Position) ===
            if token in held_tokens and score < 40:
                result = place_market_order(token, "SELL", abs(positions[token]["size"]), dry_run)
                actions.append(f"🔴 SELL {label} (Score {score}%) → {result}")

        # Log anzeigen
        if actions:
            for a in actions:
                st.success(a)
        else:
            st.info("✅ Keine neuen Orders – alle Top-Buckets bereits gehalten oder Score zu niedrig")



@st.cache_resource
def get_clob_client(): ### getting an instance of ClobClient which must be used for all polymarket interactions this is mandatory and not to replace
    if not st.secrets.get('WALLET_ADDRESS') or not WALLET_ADDRESS:
        return None
    client = ClobClient(
        host="https://clob.polymarket.com",
        key=PRIVATE_KEY,
        chain_id=137,
        signature_type=1,
        funder=WALLET_ADDRESS
    )
    client.set_api_creds(client.create_or_derive_api_creds())
    return client

clob = get_clob_client()


