using UnityEngine;
using System.IO;
using System.Collections.Generic;
using OperatorSettings;

/// <summary>
/// A8+ 操作員選單截圖工具 v4
/// 
/// 功能：
/// - F12：截圖（自動用 pageTitle 命名，可重複按覆蓋）
/// - F9：重置同名計數
/// - Ctrl + 方向鍵：移動裁切框
/// - Ctrl + Alt + 方向鍵：調整裁切框大小
/// - 即時綠色裁切框預覽
/// - 自動建立「大項目資料夾 / 標題子資料夾」
/// - 設定自動儲存（PlayerPrefs）
/// - 進入操作員選單自動啟用
/// - 三語通用（繁/簡/英）
/// </summary>
public class OperatorScreenshotCapture : MonoBehaviour
{
    [Header("=== 儲存設定 ===")]
    [SerializeField] private string basePath = "C:/Users/tomliu/Desktop/A8+相關/A8+操作員手冊相關/TW/TW_截圖";
    
    [Header("=== 裁切設定（調整時即時顯示綠色邊框）===")]
    [Tooltip("是否啟用裁切（關閉則截完整畫面）")]
    [SerializeField] private bool enableCrop = true;
    [Tooltip("裁切起點 X（從左邊算）")]
    [SerializeField] private int cropX = 225;
    [Tooltip("裁切起點 Y（從上面算）")]
    [SerializeField] private int cropY = 76;
    [Tooltip("裁切寬度")]
    [SerializeField] private int cropWidth = 715;
    [Tooltip("裁切高度")]
    [SerializeField] private int cropHeight = 669;
    [Tooltip("基準解析度寬（Game View 的解析度）")]
    [SerializeField] private int baseWidth = 952;
    [Tooltip("基準解析度高（Game View 的解析度）")]
    [SerializeField] private int baseHeight = 763;
    
    [Header("=== 預覽設定 ===")]
    [Tooltip("在 Game View 上顯示裁切邊框")]
    [SerializeField] private bool showCropPreview = true;
    [Tooltip("邊框顏色")]
    [SerializeField] private Color borderColor = Color.green;
    [Tooltip("邊框寬度(像素)")]
    [SerializeField] private int borderWidth = 2;
    
    [Header("=== 按鍵設定 ===")]
    [Tooltip("截圖（可重複按覆蓋，不前進）")]
    [SerializeField] private KeyCode captureKey = KeyCode.F12;
    [Tooltip("重置同名計數（切到新頁面後按）")]
    [SerializeField] private KeyCode resetCountKey = KeyCode.F9;
    
    [Header("=== 裁切框微調 ===")]
    [Tooltip("每次微調的像素數")]
    [SerializeField] private int adjustStep = 5;
    [Tooltip("快速微調的像素數（Shift加速）")]
    [SerializeField] private int adjustStepFast = 20;
    
    [Header("=== 資料夾設定 ===")]
    [Tooltip("是否在大項目資料夾下再建立標題子資料夾")]
    [SerializeField] private bool createSubFolder = true;
    
    [Header("=== 狀態（自動更新）===")]
    [SerializeField] private string lastPageTitle = "";
    [SerializeField] private int samePageCount = 0;
    [SerializeField] private int totalCaptured = 0;
    
    private Texture2D borderTexture;
    private PageController pageController;
    
    // === 章節對照表 ===
    private Dictionary<string, string> chapterMap = new Dictionary<string, string>();
    private bool hasChapterMap = false;
    
    private void LoadChapterMap()
    {
        string jsonPath = Path.Combine(basePath, "chapter_map.json");
        if (File.Exists(jsonPath))
        {
            string json = File.ReadAllText(jsonPath);
            var matches = System.Text.RegularExpressions.Regex.Matches(json, 
                "\"title\":\\s*\"([^\"]+)\"[^}]*\"folder_name\":\\s*\"([^\"]+)\"");
            foreach (System.Text.RegularExpressions.Match m in matches)
            {
                string title = m.Groups[1].Value;
                string folder = m.Groups[2].Value;
                if (!chapterMap.ContainsKey(title))
                    chapterMap[title] = folder;
            }
            hasChapterMap = true;
            Debug.Log($"✅ 已載入章節對照表（{chapterMap.Count} 個章節）");
        }
        else
        {
            hasChapterMap = false;
            Debug.LogError($"❌ 找不到章節對照表！請先執行：\n" +
                "1. 把 Word 手冊給 general 機器人\n" +
                "2. 它會產出 chapter_map.json 放到截圖資料夾\n" +
                $"3. 期望路徑: {jsonPath}");
        }
    }
    
    // === 大項目對照表（pageLevel 或 prefab 前綴 → 資料夾名）===
    private string GetCategoryFolder(string pageTitle, string pageName)
    {
        // 根據 prefab 名稱的前綴判斷大類
        if (pageName.StartsWith("1_") || pageName.StartsWith("1_"))
            return "1_硬體測試";
        if (pageName.StartsWith("2_"))
            return "2_系統設定";
        if (pageName.StartsWith("3_"))
            return "3_遊戲設定";
        if (pageName.StartsWith("4_"))
            return "4_營收資料";
        if (pageName.StartsWith("5_"))
            return "5_系統重置";
        if (pageName.StartsWith("0_"))
            return "0_首頁";
        return "其他";
    }
    
    // === 即時顯示裁切框 ===
    private void OnGUI()
    {
        if (!showCropPreview || !enableCrop) return;
        
        if (borderTexture == null)
        {
            borderTexture = new Texture2D(1, 1);
            borderTexture.SetPixel(0, 0, borderColor);
            borderTexture.Apply();
        }
        
        if (borderTexture.GetPixel(0, 0) != borderColor)
        {
            borderTexture.SetPixel(0, 0, borderColor);
            borderTexture.Apply();
        }
        
        float scaleX = (float)Screen.width / (float)baseWidth;
        float scaleY = (float)Screen.height / (float)baseHeight;
        
        float drawX = cropX * scaleX;
        float drawY = cropY * scaleY;
        float drawW = cropWidth * scaleX;
        float drawH = cropHeight * scaleY;
        
        // 四條邊框
        GUI.DrawTexture(new Rect(drawX, drawY, drawW, borderWidth), borderTexture);
        GUI.DrawTexture(new Rect(drawX, drawY + drawH - borderWidth, drawW, borderWidth), borderTexture);
        GUI.DrawTexture(new Rect(drawX, drawY, borderWidth, drawH), borderTexture);
        GUI.DrawTexture(new Rect(drawX + drawW - borderWidth, drawY, borderWidth, drawH), borderTexture);
        
        // 資訊
        GUIStyle style = new GUIStyle(GUI.skin.label);
        style.normal.textColor = borderColor;
        style.fontSize = 12;
        GUI.Label(new Rect(drawX + 4, drawY + 4, 300, 18), $"裁切: {cropWidth}x{cropHeight} 位置: ({cropX},{cropY})", style);
        
        // 顯示目前頁面名稱
        if (pageController != null && pageController.currentPage != null)
        {
            string title = pageController.currentPage.pageTitle;
            if (!string.IsNullOrEmpty(title))
            {
                style.fontSize = 14;
                GUI.Label(new Rect(drawX + 4, drawY + drawH - 22, 400, 20), $"📋 {title}", style);
            }
        }
    }
    
    // === 按鍵處理 ===
    private void Update()
    {
        // F12: 截圖
        if (Input.GetKeyDown(captureKey))
        {
            CaptureCurrentPage();
        }
        
        // F9: 重置同名計數
        if (Input.GetKeyDown(resetCountKey))
        {
            samePageCount = 0;
            Debug.Log("🔄 同名計數已重置");
        }
        
        // Ctrl + 方向鍵：移動/調整裁切框
        if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
        {
            bool shift = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
            int step = shift ? adjustStepFast : adjustStep;
            bool changed = false;
            
            if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
            {
                // Ctrl + Alt + 方向鍵 = 調整大小
                if (Input.GetKeyDown(KeyCode.RightArrow)) { cropWidth += step; changed = true; }
                if (Input.GetKeyDown(KeyCode.LeftArrow)) { cropWidth -= step; changed = true; }
                if (Input.GetKeyDown(KeyCode.DownArrow)) { cropHeight += step; changed = true; }
                if (Input.GetKeyDown(KeyCode.UpArrow)) { cropHeight -= step; changed = true; }
            }
            else
            {
                // Ctrl + 方向鍵 = 移動位置
                if (Input.GetKeyDown(KeyCode.RightArrow)) { cropX += step; changed = true; }
                if (Input.GetKeyDown(KeyCode.LeftArrow)) { cropX -= step; changed = true; }
                if (Input.GetKeyDown(KeyCode.DownArrow)) { cropY += step; changed = true; }
                if (Input.GetKeyDown(KeyCode.UpArrow)) { cropY -= step; changed = true; }
            }
            
            if (changed)
            {
                cropX = Mathf.Max(0, cropX);
                cropY = Mathf.Max(0, cropY);
                cropWidth = Mathf.Max(10, cropWidth);
                cropHeight = Mathf.Max(10, cropHeight);
                SaveSettings();
            }
        }
    }
    
    private void CaptureCurrentPage()
    {
        if (pageController == null || pageController.currentPage == null)
        {
            Debug.LogWarning("⚠️ 目前沒有頁面，無法截圖");
            return;
        }
        
        // 讀取當前頁面標題和 prefab 名稱
        string title = pageController.currentPage.pageTitle;
        string pageName = pageController.currentPage.name;
        
        if (string.IsNullOrEmpty(title))
        {
            title = pageName;
            Debug.LogWarning($"⚠️ pageTitle 為空，使用 GameObject 名: {title}");
        }
        
        // 清理檔名
        string cleanTitle = CleanFileName(title);
        
        // 判斷是否同頁面重複截圖
        if (cleanTitle == lastPageTitle)
        {
            samePageCount++;
        }
        else
        {
            lastPageTitle = cleanTitle;
            samePageCount = 0;
        }
        
        // 產生檔名
        string fileName = samePageCount == 0 ? cleanTitle : $"{cleanTitle}_{samePageCount + 1}";
        
        // 決定資料夾路徑
        string categoryFolder = GetCategoryFolder(title, pageName);
        string chapterFolder = hasChapterMap && chapterMap.ContainsKey(cleanTitle) 
            ? chapterMap[cleanTitle] 
            : cleanTitle;
        string folderPath;
        
        if (createSubFolder)
        {
            // 大項目 / 章節編號_標題
            folderPath = Path.Combine(basePath, categoryFolder, chapterFolder);
        }
        else
        {
            folderPath = Path.Combine(basePath, categoryFolder);
        }
        
        StartCoroutine(CaptureAndSave(folderPath, fileName));
    }
    
    // === 截圖核心 ===
    private System.Collections.IEnumerator CaptureAndSave(string folderPath, string fileName)
    {
        yield return new WaitForEndOfFrame();
        
        int screenWidth = Screen.width;
        int screenHeight = Screen.height;
        
        Texture2D screenshot = new Texture2D(screenWidth, screenHeight, TextureFormat.RGB24, false);
        screenshot.ReadPixels(new Rect(0, 0, screenWidth, screenHeight), 0, 0);
        screenshot.Apply();
        
        Texture2D finalImage;
        
        if (enableCrop)
        {
            float scaleX = (float)screenWidth / (float)baseWidth;
            float scaleY = (float)screenHeight / (float)baseHeight;
            
            int actualCropX = Mathf.RoundToInt(cropX * scaleX);
            int actualCropY = Mathf.RoundToInt((baseHeight - cropY - cropHeight) * scaleY);
            int actualCropW = Mathf.RoundToInt(cropWidth * scaleX);
            int actualCropH = Mathf.RoundToInt(cropHeight * scaleY);
            
            actualCropX = Mathf.Clamp(actualCropX, 0, screenWidth - 1);
            actualCropY = Mathf.Clamp(actualCropY, 0, screenHeight - 1);
            actualCropW = Mathf.Min(actualCropW, screenWidth - actualCropX);
            actualCropH = Mathf.Min(actualCropH, screenHeight - actualCropY);
            
            finalImage = new Texture2D(actualCropW, actualCropH, TextureFormat.RGB24, false);
            Color[] pixels = screenshot.GetPixels(actualCropX, actualCropY, actualCropW, actualCropH);
            finalImage.SetPixels(pixels);
            finalImage.Apply();
            Destroy(screenshot);
        }
        else
        {
            finalImage = screenshot;
        }
        
        // 建立資料夾
        if (!Directory.Exists(folderPath))
            Directory.CreateDirectory(folderPath);
        
        // 存檔
        byte[] bytes = finalImage.EncodeToPNG();
        string filePath = Path.Combine(folderPath, $"{fileName}.png");
        File.WriteAllBytes(filePath, bytes);
        Destroy(finalImage);
        
        totalCaptured++;
        Debug.Log($"📸 [{totalCaptured}] 已存: {folderPath}/{fileName}.png ({bytes.Length / 1024}KB)");
    }
    
    // === 生命週期 ===
    private void Awake()
    {
        LoadSettings();
        LoadChapterMap();
        pageController = FindObjectOfType<PageController>();
        if (pageController == null)
            Debug.LogError("❌ 找不到 PageController！");
    }
    
    private void OnDestroy()
    {
        SaveSettings();
    }
    
    private void OnApplicationQuit()
    {
        SaveSettings();
    }
    
    // === 設定儲存/載入 ===
    private void SaveSettings()
    {
        PlayerPrefs.SetInt("SSCrop_X", cropX);
        PlayerPrefs.SetInt("SSCrop_Y", cropY);
        PlayerPrefs.SetInt("SSCrop_W", cropWidth);
        PlayerPrefs.SetInt("SSCrop_H", cropHeight);
        PlayerPrefs.SetInt("SSCrop_BaseW", baseWidth);
        PlayerPrefs.SetInt("SSCrop_BaseH", baseHeight);
        PlayerPrefs.SetInt("SSCrop_Enabled", enableCrop ? 1 : 0);
        PlayerPrefs.SetString("SSCrop_Path", basePath);
        PlayerPrefs.Save();
    }
    
    private void LoadSettings()
    {
        if (PlayerPrefs.HasKey("SSCrop_X"))
        {
            cropX = PlayerPrefs.GetInt("SSCrop_X");
            cropY = PlayerPrefs.GetInt("SSCrop_Y");
            cropWidth = PlayerPrefs.GetInt("SSCrop_W");
            cropHeight = PlayerPrefs.GetInt("SSCrop_H");
            baseWidth = PlayerPrefs.GetInt("SSCrop_BaseW");
            baseHeight = PlayerPrefs.GetInt("SSCrop_BaseH");
            enableCrop = PlayerPrefs.GetInt("SSCrop_Enabled") == 1;
            basePath = PlayerPrefs.GetString("SSCrop_Path");
            Debug.Log($"✅ 已載入儲存的裁切設定: ({cropX},{cropY}) {cropWidth}x{cropHeight}");
        }
    }
    
    // === 輔助 ===
    private string CleanFileName(string name)
    {
        char[] invalid = Path.GetInvalidFileNameChars();
        foreach (char c in invalid)
            name = name.Replace(c, '_');
        return name.Trim();
    }
    
    [ContextMenu("重置所有計數")]
    public void ResetAll()
    {
        samePageCount = 0;
        totalCaptured = 0;
        lastPageTitle = "";
        Debug.Log("已重置所有計數");
    }
    
    [ContextMenu("儲存目前設定")]
    public void ForceSave()
    {
        SaveSettings();
        Debug.Log("✅ 設定已儲存");
    }
    
    [ContextMenu("清除儲存的設定")]
    public void ClearSavedSettings()
    {
        PlayerPrefs.DeleteKey("SSCrop_X");
        PlayerPrefs.DeleteKey("SSCrop_Y");
        PlayerPrefs.DeleteKey("SSCrop_W");
        PlayerPrefs.DeleteKey("SSCrop_H");
        PlayerPrefs.DeleteKey("SSCrop_BaseW");
        PlayerPrefs.DeleteKey("SSCrop_BaseH");
        PlayerPrefs.DeleteKey("SSCrop_Enabled");
        PlayerPrefs.DeleteKey("SSCrop_Path");
        PlayerPrefs.Save();
        Debug.Log("🗑️ 已清除儲存的設定");
    }
}
