import time
import re
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

def convert_price_to_full(price_text):
    """한경의 '100,000' (만원) 같은 텍스트를 원 단위로 변환"""
    if not price_text: return ""
    
    parts = price_text.split('/')
    result = []
    for part in parts:
        clean_num = re.sub(r'[^0-9]', '', part)
        if clean_num:
            full_num = int(clean_num) * 10000 
            result.append(f"{full_num:,}") 
        else:
            result.append("0")
    return " / ".join(result)

def login(driver, user_id, user_pw):
    print(f"\n[한경] 🔑 '{user_id}' 계정 접속 시도 중...")
    try:
        driver.get("https://realestate.hankyung.com/mmc/auth/login")
        
        id_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "loginId")))
        pw_input = driver.find_element(By.NAME, "loginPw")
        
        id_input.clear()
        id_input.send_keys(user_id)
        time.sleep(0.5) 
        
        pw_input.clear()
        pw_input.send_keys(user_pw)
        time.sleep(0.5)
        
        pw_input.send_keys(Keys.ENTER)
        time.sleep(2) 
        
        if "login" not in driver.current_url.lower():
            print("✅ [한경] 로그인 성공!")
            return True
        else:
            print("⚠️ [한경] 로그인 실패 (아이디/비번 확인 필요)")
            return False
            
    except Exception as e:
        print(f"❌ [한경] 로그인 에러 발생: {e}")
        return False

def crawl(user_id, user_pw):
    """한경 서비스중(등록) 매물 실제 수집 로직"""
    print(f"\n[한경] 🤖 '{user_id}' 계정 수집 프로세스 가동...")
    
    options = uc.ChromeOptions()
    options.add_argument('--window-size=1920,1080')
    options.add_argument('--log-level=3') 
    options.add_argument('--disable-logging')
    
    driver = uc.Chrome(options=options, version_main=147)
    extracted_data = []
    
    try:
        if login(driver, user_id, user_pw):
            print(" 👉 [수집] 등록된 매물 리스트로 이동합니다...")
            # 🎯 대표님이 알려주신 수집 URL
            driver.get("https://realestate.hankyung.com/mmc/listings/registered")
            time.sleep(2)
            
            # 조회 내역이 없는 경우 예외 처리
            try:
                empty_msg = driver.find_elements(By.CSS_SELECTOR, ".no-table")
                if empty_msg and "조회 내역이 없습니다" in empty_msg[0].text:
                    print(" ⚠️ 등록된 매물이 없습니다. 빈 리스트를 반환합니다.")
                    return extracted_data
            except: pass

            try:
                # 테이블 로딩 대기
                WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".list-wrap tbody")))
                soup = BeautifulSoup(driver.page_source, 'html.parser')
                rows = soup.select('.list-wrap tbody tr')
                
                for row in rows:
                    tds = row.find_all('td')
                    if len(tds) < 8: continue
                    
                    # 1. 네이버 번호 추출 (네이버 아이콘이 있는 <a> 태그 내부의 숫자)
                    naver_link = row.select_one("a[href*='land.naver.com']")
                    naver_id = "없음"
                    if naver_link:
                        num_span = naver_link.select_one(".container__number")
                        naver_id = num_span.text.strip() if num_span else "없음"
                        
                    # 2. 매물종류 추출
                    prop_type = tds[2].text.strip() if len(tds) > 2 else ""
                    
                    # 3. 주소 조합 (소재지 + 상세주소)
                    loc_base = tds[3].text.strip().replace("\n", " ") if len(tds) > 3 else ""
                    loc_detail = tds[4].text.strip().replace("\n", " ") if len(tds) > 4 else ""
                    address = f"{loc_base} {loc_detail}".strip()
                    
                    # 4. 거래유형
                    trade_type = tds[6].text.strip() if len(tds) > 6 else ""
                    
                    # 5. 매물가 (만원 -> 원 변환)
                    raw_price = tds[7].text.strip() if len(tds) > 7 else ""
                    formatted_price = convert_price_to_full(raw_price)
                    
                    extracted_data.append({
                        "platform": "hankyung",
                        "naver_id": naver_id,
                        "prop_type": prop_type,
                        "address": address,
                        "trade_type": trade_type,
                        "price": formatted_price
                    })
                    
                print(f"✅ [한경] 현재 등록된 {len(extracted_data)}개의 매물을 정상적으로 수집했습니다!")
                
            except Exception as e:
                print(f" ⚠️ 매물 테이블을 파싱하는 중 오류가 발생했습니다: {e}")
                
    except Exception as e:
        print(f"🚨 [한경] 수집 중 치명적 오류: {e}")
        
    finally:
        time.sleep(0.5)
        driver.quit()
        
    return extracted_data

def refresh_listing(driver, article_id, naver_id):
    """한경 끌어올리기 가짜 실행 (Dry-Run) 모드"""
    print(f"\n🔄 [한경] 매물번호 {article_id} 끌어올리기 (노출종료->재등록) 시뮬레이션 시작...")
    
    try:
        # 1. (나중 구현부) registered URL에서 노출종료 버튼 클릭
        print(" ⏸️ 1단계: 기존 노출 종료 처리 완료 (가짜 실행)")
        time.sleep(1)
        
        # 2. (나중 구현부) expire URL로 이동하여 재등록 버튼 클릭
        print(f" ✅ 2단계: 매물 {article_id} 성공적으로 재등록(끌어올리기) 완료! (가짜 실행)")
        time.sleep(1)
        
        return True # 가짜 성공 신호 전송 -> app.py가 받아서 DB에 반영

    except Exception as e:
        print(f" ❌ [한경] 재등록 시뮬레이션 실패: {e}")
        return False