"""
Gemini 3.8 Flash Antigravity Agent Bridge for Path of Exile 2
Tier 2 AI Orchestration Engine (Sub-second Multimodal Vision & Autonomous Gameplay)
"""

import logging
import os
from typing import Any, Dict, Optional, Union

from pydantic import BaseModel, Field

try:
    from google import genai
    from google.genai import types
    GENAI_AVAILABLE = True
except ImportError:
    GENAI_AVAILABLE = False


logger = logging.getLogger("GeminiAgentBridge")


class ItemAppraisalResult(BaseModel):
    item_name: str = Field(description="Tên của trang bị hoặc vật phẩm")
    rarity: str = Field(description="Normal, Magic, Rare, Unique, Currency")
    item_type: str = Field(description="Loại trang bị (Weapon, Body Armor, Ring, Amulet, Gem, Currency...)")
    tier_score: float = Field(description="Điểm sức mạnh tổng thể (0.0 đến 100.0)")
    estimated_chaos_value: float = Field(description="Ước tính giá trị thị trường theo Chaos Orb")
    is_upgrade: bool = Field(description="Trang bị này có tốt hơn đồ hiện tại không?")
    action: str = Field(
        description="Quyết định: EQUIP_UPGRADE (tự mặc vào), STASH_FOR_TRADE (cất hòm bán), VENDOR_GOLD (bán lấy vàng), SALVAGE (rã đồ)"
    )
    reasoning: str = Field(description="Phân tích ngắn gọn lý do đưa ra quyết định")


class MacroDecisionResult(BaseModel):
    strategy: str = Field(
        default="MAINTAIN_COMBAT",
        description="Chiến lược vĩ mô cấp cao: CLEAR_MAP, DEFENSIVE_RETREAT, OPEN_PORTAL_TOWN, LOOT_PRIORITY, MAINTAIN_COMBAT"
    )
    priority: str = Field(
        default="SURVIVAL",
        description="Ưu tiên hàng đầu: SURVIVAL, EXP, CURRENCY_FARM, BOSS_KILL"
    )
    suggested_action: str = Field(
        default="",
        description="Hành động cụ thể đề xuất cho State Machine"
    )
    reasoning: str = Field(
        default="",
        description="Lý do ngắn gọn đưa ra quyết định chiến lược vĩ mô"
    )


class TradeWhisperAnalysis(BaseModel):
    is_valid_trade: bool = Field(description="Có phải là tin nhắn mua bán trao đổi hợp lệ không")
    buyer_name: str = Field(default="", description="Tên nhân vật người mua")
    item_requested: str = Field(default="", description="Món đồ người mua yêu cầu")
    offered_currency: str = Field(default="", description="Loại tiền tệ (divine, chaos, exalted, mirror...)")
    offered_amount: float = Field(default=0.0, description="Số lượng tiền đề xuất")
    is_fair_market_price: bool = Field(default=True, description="Giá có khớp với định giá thị trường không")
    auto_reply_message: str = Field(default="", description="Câu trả lời chat game chuẩn ngôn ngữ game thủ")


class GameActionCommand(BaseModel):
    action_type: str = Field(
        description="Hành động điều khiển game: MOVE_TO, CAST_SKILL, USE_FLASK, LOOT_ITEM, EMERGENCY_LOGOUT, PORTAL_TOWN"
    )
    target_x: float = Field(default=0.0, description="Tọa độ X thế giới")
    target_y: float = Field(default=0.0, description="Tọa độ Y thế giới")
    skill_slot: str = Field(default="", description="Phím tắt chiêu thức (Q, W, E, R, T, M1, M2)")
    flask_slot: int = Field(default=0, description="Slot bình thuốc (1-5)")
    reasoning: str = Field(default="", description="Lý giải nguyên nhân kỹ thuật của hành động")


class GeminiAgentBridge:
    def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None):
        self.api_key = api_key or os.getenv("GEMINI_API_KEY", "")
        # Mặc định kết nối thẳng tới Gemini 3.8 Flash siêu tốc
        self.model = model or os.getenv("GEMINI_MODEL", "gemini-3.8-flash")
        self.fallback_model = "gemini-3.7-flash"
        self.client: Optional[Any] = None

        if GENAI_AVAILABLE and self.api_key:
            try:
                self.client = genai.Client(api_key=self.api_key)
                logger.info(f"[GeminiAgent] Đã kết nối Google GenAI SDK với Model: {self.model}")
            except Exception as e:
                logger.error(f"[GeminiAgent] Lỗi khởi tạo GenAI Client: {e}")
                self.client = None
        else:
            if not GENAI_AVAILABLE:
                logger.warning("[GeminiAgent] Thư viện google-genai chưa được nạp.")
            if not self.api_key:
                logger.info("[GeminiAgent] Chưa thiết lập GEMINI_API_KEY. Vui lòng thêm key vào biến môi trường.")

    def is_ready(self) -> bool:
        return self.client is not None

    def appraise_item_image(self, image_data: Union[str, bytes]) -> Optional[ItemAppraisalResult]:
        """
        Thẩm định thị giác Tooltip trang bị POE2 bằng Gemini 3.8 Flash (Multimodal Vision).
        Trả về kết quả phân tích chỉ số và quyết định hành động tự động.
        """
        if not self.is_ready() or self.client is None:
            logger.warning("[GeminiAgent] Client chưa sẵn sàng để thẩm định ảnh.")
            return None

        prompt = (
            "Bạn là Chuyên gia Thẩm định Trang bị & Định giá Kinh tế số 1 của Path of Exile 2 (v0.5.5). "
            "Hãy phân tích ảnh chụp màn hình Tooltip trang bị này. Đọc kỹ các dòng thuộc tính (Affixes), "
            "các bậc mod (Tier), chỉ số sát thương, giáp, kháng và slot ngọc. "
            "Đưa ra ước tính giá trị thị trường và ra quyết định hành động tối ưu nhất cho người chơi."
        )

        try:
            # Chuẩn bị ảnh
            if isinstance(image_data, str):
                with open(image_data, "rb") as f:
                    raw_bytes = f.read()
            else:
                raw_bytes = image_data

            part = types.Part.from_bytes(data=raw_bytes, mime_type="image/png")

            # Gọi Gemini 3.8 Flash với Structured Outputs
            response = self.client.models.generate_content(
                model=self.model,
                contents=[part, prompt],
                config=types.GenerateContentConfig(
                    response_mime_type="application/json",
                    response_schema=ItemAppraisalResult,
                    temperature=0.1,
                ),
            )

            if response.text:
                result = ItemAppraisalResult.model_validate_json(response.text)
                logger.info(f"[Gemini 3.8 Flash] Thẩm định '{result.item_name}': {result.action} (~{result.estimated_chaos_value}c)")
                return result

        except Exception as e:
            logger.error(f"[GeminiAgent] Lỗi thẩm định thị giác: {e}")
            # Thử lại với fallback model nếu 3.8 gặp rate limit
            try:
                if self.client is not None:
                    response = self.client.models.generate_content(
                        model=self.fallback_model,
                        contents=[part, prompt],
                        config=types.GenerateContentConfig(
                            response_mime_type="application/json",
                            response_schema=ItemAppraisalResult,
                            temperature=0.1,
                        ),
                    )
                    if response.text:
                        return ItemAppraisalResult.model_validate_json(response.text)
            except Exception as e2:
                logger.error(f"[GeminiAgent] Fallback model cũng gặp lỗi: {e2}")

        return None

    def generate_whisper_reply(self, sender: str, message: str, game_state_summary: str = "đang đánh quái trong map") -> str:
        """
        Cơ chế Chống Ban: Tự động trả lời tin nhắn @Whisper bằng ngôn ngữ tự nhiên game thủ chuẩn xác 100%.
        """
        if not self.is_ready() or self.client is None:
            return "dang ban chut, ti rep nhe"

        prompt = (
            f"Bạn là người chơi game Path of Exile 2 đang tập trung cày game. "
            f"Trạng thái hiện tại của bạn: {game_state_summary}. "
            f"Một người chơi khác tên '{sender}' vừa nhắn tin thì thầm cho bạn: '{message}'. "
            f"Hãy trả lời một câu cực kỳ ngắn gọn (dưới 15 từ), viết kiểu chat game thông thường "
            f"(không dấu hoặc có dấu tự nhiên, thân thiện, không giống văn phong AI, tỏ vẻ bận một chút nếu đang combat)."
        )

        try:
            response = self.client.models.generate_content(
                model=self.model,
                contents=prompt,
                config=types.GenerateContentConfig(
                    temperature=0.7,
                    max_output_tokens=50,
                ),
            )
            reply = response.text.strip().strip('"').strip("'")
            return str(reply)
        except Exception as e:
            logger.error(f"[GeminiAgent] Lỗi sinh phản hồi whisper: {e}")
            return "dang ban clear map ti rep nhe"

    def plan_macro_strategy(self, telemetry: Dict[str, Any]) -> Dict[str, Any]:
        """
        Ra quyết định vĩ mô cấp cao (Macro State Machine) dựa trên dữ liệu thời gian thực từ C++ Core.
        Tận dụng Gemini 3.8 Flash SDK với Pydantic Structured Outputs.
        """
        if not self.is_ready() or self.client is None:
            return {"strategy": "MAINTAIN_COMBAT", "priority": "SURVIVAL"}

        hp_pct = (telemetry.get("hp", 100) / max(telemetry.get("max_hp", 100), 1)) * 100
        area_name = telemetry.get("area_name", "Unknown Area")
        entities_count = telemetry.get("entity_count", 0)

        prompt = (
            f"Trạng thái hiện tại trong POE2: Khu vực '{area_name}', Máu {hp_pct:.1f}%, Số thực thể xung quanh: {entities_count}. "
            f"Hãy đưa ra quyết định chiến lược vĩ mô tối ưu nhất (CLEAR_MAP, DEFENSIVE_RETREAT, OPEN_PORTAL_TOWN, LOOT_PRIORITY, MAINTAIN_COMBAT)."
        )

        try:
            response = self.client.models.generate_content(
                model=self.model,
                contents=prompt,
                config=types.GenerateContentConfig(
                    response_mime_type="application/json",
                    response_schema=MacroDecisionResult,
                    temperature=0.1,
                ),
            )
            if response.text:
                result = MacroDecisionResult.model_validate_json(response.text)
                res_dict = result.model_dump()
                res_dict["hp_pct"] = hp_pct
                return res_dict
        except Exception as e:
            logger.error(f"[GeminiAgent] Lỗi lập kế hoạch vĩ mô qua Structured Output: {e}")

        return {"strategy": "MAINTAIN_COMBAT", "priority": "SURVIVAL", "hp_pct": hp_pct}

    def analyze_trade_whisper(self, raw_whisper_text: str) -> Optional[TradeWhisperAnalysis]:
        """
        Phân tích tin nhắn giao dịch mua bán bằng Gemini 3.8 Flash Pydantic Structured Outputs.
        Thay thế hoàn toàn regex parsing không an toàn và chống prompt injection.
        """
        if not self.is_ready() or self.client is None:
            return None

        prompt = (
            f"Phân tích tin nhắn chat game sau đây để xác định có phải giao dịch mua bán hợp lệ không: '{raw_whisper_text}'. "
            "Trích xuất tên người mua, vật phẩm muốn mua, loại tiền tệ và số lượng. "
            "So sánh với thị trường và đề xuất câu trả lời chuẩn xác, lịch sự theo ngôn ngữ game thủ."
        )

        try:
            response = self.client.models.generate_content(
                model=self.model,
                contents=prompt,
                config=types.GenerateContentConfig(
                    response_mime_type="application/json",
                    response_schema=TradeWhisperAnalysis,
                    temperature=0.1,
                ),
            )
            if response.text:
                return TradeWhisperAnalysis.model_validate_json(response.text)
        except Exception as e:
            logger.error(f"[GeminiAgent] Lỗi phân tích trade whisper: {e}")

        return None
