using System;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System.Text.RegularExpressions;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using OpenQA.Selenium.Chromium;
using UniMarc.SearchModel;
using System.Runtime.CompilerServices;
using AR;

namespace BokBonCheck
{
    public class GochangLibSearcher : ILibrarySearcher
    {
        public string AreaCode { get; set; } = string.Empty;
        public string SiteName { get; protected set; }
        public string SiteUrl => "https://libsearch.gochang.go.kr:8443/book/bookAdvancedSearch";
        public bool HttpApiMode { get; set; } = false;

        public int No { get; set; }

        private ChromiumDriver _driver;

        public GochangLibSearcher(int no, string areaCode, string areaName)
        {
            this.No = no;
            this.AreaCode = areaCode;
            this.SiteName = $"고창군립({areaName})";
        }

        public void StopDriver()
        {
            if (_driver != null)
            {
                _driver.Quit();
                _driver.Dispose();
                _driver = null;
            }
        }

        public async Task StartDriver(bool showdriver = false)
        {
            if (_driver == null)
            {
                try
                {
                    if (SeleniumHelper.IsReady == false) await SeleniumHelper.Download();
                    _driver = await SeleniumHelper.CreateDriver(ShowBrowser: showdriver);
                    Console.WriteLine("GochangLibSearcher Driver 초기화 완료");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"GochangLibSearcher Driver 초기화 실패: {ex.Message}");
                    throw new InvalidOperationException($"GochangLibSearcher Driver 초기화에 실패했습니다: {ex.Message}", ex);
                }
            }
        }

        virtual protected bool SelectLibrary(WebDriverWait wait)
        {
            try
            {
                if (!string.IsNullOrEmpty(AreaCode))
                {
                    var libSelect = wait.Until(d => d.FindElement(By.Id("MANAGE_CODE")));
                    var selectElement = new SelectElement(libSelect);
                    selectElement.SelectByValue(AreaCode);
                    Thread.Sleep(300);
                    Console.WriteLine($"{AreaCode} 도서관으로 선택됨");
                }
                else
                {
                    Console.WriteLine("전체 도서관으로 검색");
                }

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"도서관 선택 실패: {ex.Message}");
                return false;
            }
        }

        public async Task<BookSearchResult> SearchAsync(string searchTerm)
        {
            var result = new BookSearchResult
            {
                SiteName = SiteName,
                SearchTerm = searchTerm,
                SearchTime = DateTime.Now
            };

            try
            {
                if (_driver == null)
                {
                    await StartDriver();
                }

                var cururl = _driver.Url;
                if (cururl.Equals(SiteUrl) == false)
                    _driver.Navigate().GoToUrl(SiteUrl);

                var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(15));

                if (SelectLibrary(wait) == false)
                {
                    result.ErrorMessage = "도서관선택실패";
                    result.BookCount = -1;
                    result.IsSuccess = false;
                    return result;
                }

                try
                {
                    var titleInput = wait.Until(d => d.FindElement(By.Id("title")));
                    titleInput.Clear();
                    titleInput.SendKeys(searchTerm);
                }
                catch (Exception ex)
                {
                    result.ErrorMessage = $"검색어입력실패({ex.Message})";
                    result.BookCount = -1;
                    result.IsSuccess = false;
                    return result;
                }

                try
                {
                    var jsExecutor = (IJavaScriptExecutor)_driver;
                    jsExecutor.ExecuteScript("fn_openBookAdvancedSearch();");
                }
                catch (Exception ex)
                {
                    result.ErrorMessage = $"검색실행실패({ex.Message})";
                    result.BookCount = -1;
                    result.IsSuccess = false;
                    return result;
                }

                await WaitForPageChange(new WebDriverWait(_driver, TimeSpan.FromSeconds(15)));

                // SearchAsync에서 PageSource 가져오기
                var htmlContent = _driver.PageSource;
                var resultCount = ExtractBookCount(htmlContent, out string ermsg, out string resultHtml);
                result.Resulthtml = resultHtml;
                if (resultCount == -1)
                {
                    result.BookCount = 0;
                    result.IsSuccess = false;
                    result.ErrorMessage = ermsg;
                }
                else
                {
                    result.BookCount = resultCount;
                    result.IsSuccess = true;
                    result.ErrorMessage = ermsg;
                }

            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                result.BookCount = 0;
            }

            return result;
        }

        private int ExtractBookCount(string htmlContent, out string errmessage, out string resulthtml)
        {
            errmessage = string.Empty;
            resulthtml = string.Empty;

            try
            {
                var noResultPatterns = new[]
                {
                    @"검색된 도서가 없습니다",
                    @"검색결과가 없습니다",
                    @"검색된 자료가 없습니다"
                };

                foreach (var pattern in noResultPatterns)
                {
                    if (htmlContent.Contains(pattern))
                    {
                        errmessage = "검색결과없음";
                        // 검색결과 없음 메시지를 포함한 HTML 조각 추출
                        var index = htmlContent.IndexOf(pattern);
                        if (index >= 0)
                        {
                            var startIndex = Math.Max(0, index - 100);
                            var endIndex = Math.Min(htmlContent.Length, index + pattern.Length + 100);
                            resulthtml = htmlContent.Substring(startIndex, endIndex - startIndex);

                            // 상위 태그 찾기 시도
                            try
                            {
                                var match = System.Text.RegularExpressions.Regex.Match(htmlContent, pattern);
                                if (match.Success)
                                {
                                    resulthtml = ExtractResultContext(htmlContent, match);
                                }
                            }
                            catch
                            {
                                // 실패시 기본 추출 결과 사용
                            }
                        }
                        else
                        {
                            resulthtml = pattern;
                        }
                        return 0;
                    }
                }

                var htmlPatterns = new[]
                {
                    @"<span[^>]*class=""bluecolor""[^>]*>총\s*(\d+)건</span>",
                    @"총\s*<span[^>]*class=""bluecolor""[^>]*>(\d+)</span>건",
                    @"총\s*(\d+)건"
                };

                foreach (var pattern in htmlPatterns)
                {
                    var match = Regex.Match(htmlContent, pattern, RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        if (int.TryParse(match.Groups[1].Value, out int count))
                        {
                            // 매칭된 부분과 상위 태그 추출하여 resulthtml에 저장
                            resulthtml = ExtractResultContext(htmlContent, match);

                            if (count == 0)
                            {
                                errmessage = "검색결과없음";
                                return 0;
                            }
                            errmessage = $"검색성공({count}권)";
                            return count;
                        }
                    }
                }

                errmessage = "결과수량을찾을수없음";
                resulthtml = "결과수량을찾을수없음";
                return -1;

            }
            catch (Exception ex)
            {
                errmessage = ex.Message;
                resulthtml = "ExtractBookCount 오류: " + ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 매칭된 결과와 그 상위 태그를 추출
        /// </summary>
        private string ExtractResultContext(string htmlContent, Match match)
        {
            try
            {
                var matchIndex = match.Index;
                var matchLength = match.Length;

                // 매칭된 위치 앞쪽에서 상위 태그 시작 찾기
                var startSearchIndex = Math.Max(0, matchIndex - 200); // 매칭 위치 200자 전부터 검색
                var searchText = htmlContent.Substring(startSearchIndex, matchIndex - startSearchIndex + matchLength + Math.Min(200, htmlContent.Length - matchIndex - matchLength));

                // 상위 태그 패턴들 (div, p, h1-h6, span 등)
                var tagPatterns = new[] { @"<(div|p|h[1-6]|span|section|article)[^>]*>", @"<[^>]+>" };

                string resultContext = match.Value; // 기본값은 매칭된 부분만

                foreach (var tagPattern in tagPatterns)
                {
                    // 매칭된 부분 앞에서 가장 가까운 태그 시작 찾기
                    var tagMatches = Regex.Matches(searchText, tagPattern, RegexOptions.IgnoreCase);

                    for (int i = tagMatches.Count - 1; i >= 0; i--)
                    {
                        var tagMatch = tagMatches[i];
                        if (tagMatch.Index < (matchIndex - startSearchIndex))
                        {
                            // 태그 이름 추출
                            var tagName = Regex.Match(tagMatch.Value, @"<(\w+)", RegexOptions.IgnoreCase).Groups[1].Value;

                            // 닫는 태그 찾기
                            var closeTagPattern = $@"</{tagName}[^>]*>";
                            var closeMatch = Regex.Match(searchText, closeTagPattern, RegexOptions.IgnoreCase);

                            if (closeMatch.Success && closeMatch.Index > (matchIndex - startSearchIndex))
                            {
                                // 상위 태그와 그 내용을 포함하여 반환
                                var startIdx = tagMatch.Index;
                                var endIdx = closeMatch.Index + closeMatch.Length;
                                resultContext = searchText.Substring(startIdx, Math.Min(endIdx - startIdx, 500)); // 최대 500자
                                return resultContext;
                            }
                        }
                    }
                }

                // 상위 태그를 찾지 못한 경우, 매칭 전후 50자씩 포함
                var contextStart = Math.Max(0, matchIndex - 50);
                var contextEnd = Math.Min(htmlContent.Length, matchIndex + matchLength + 50);
                resultContext = htmlContent.Substring(contextStart, contextEnd - contextStart);

                return resultContext;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ExtractResultContext 오류: {ex.Message}");
                return match.Value; // 오류 시 매칭된 부분만 반환
            }
        }

        public async Task WaitForPageChange(WebDriverWait wait)
        {
            try
            {
                await Task.Delay(500);

                wait.Until(d =>
                {
                    var readyState = ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState");
                    return readyState.Equals("complete");
                });

                wait.Until(d =>
                {
                    try
                    {
                        var pageSource = d.PageSource;
                        return pageSource.Contains("검색결과입니다") || 
                               pageSource.Contains("총") ||
                               pageSource.Contains("건") ||
                               pageSource.Contains("검색된 도서가 없습니다");
                    }
                    catch
                    {
                        return false;
                    }
                });

            }
            catch (Exception ex)
            {
                await Task.Delay(3000);
                Console.WriteLine($"페이지 변경 감지 실패: {ex.Message}");
            }
        }
    }
}