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):
    """'1,000 / 100' -> '10,000,000 / 1,000,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):
    """매경(mk) 부동산 공통 로그인 함수"""
    print(f"\n[매경] 🔑 '{user_id}' 계정 접속 시도 중...")
    try:
        driver.get("https://landad.mk.co.kr/member2/login.php")
        
        id_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "mid")))
        pw_input = driver.find_element(By.ID, "pwd")
        
        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) 
        
        try:
            alert = driver.switch_to.alert
            print(f"⚠️ [매경] 로그인 알럿 발생: {alert.text}")
            alert.accept()
            return False
        except:
            pass 
            
        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://landad.mk.co.kr/memul/memulRegList.php?s_proc=proc4")
            time.sleep(2)
            
            try:
                # 테이블 로딩 대기
                WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".tbstyle2 tbody")))
                soup = BeautifulSoup(driver.page_source, 'html.parser')
                rows = soup.select('.tbstyle2 tbody tr')
                
                for row in rows:
                    tds = row.find_all('td')
                    if len(tds) < 8: continue # 데이터가 없는 빈 줄 방어
                    
                    # 1. 네이버 번호 추출 (class="NAVER" 콕 집어서 추출)
                    naver_link = row.select_one("a.NAVER")
                    naver_id = naver_link.text.strip() if naver_link else "없음"
                        
                    # 2. 매물종류 (건물-<br>숙박/콘도 같은 경우 줄바꿈 없애고 한 줄로)
                    type_td = row.select_one("td.type")
                    prop_type = type_td.get_text(separator="", strip=True) if type_td else ""
                    
                    # 3. 주소 조합 (li 태그들 중 썸네일과 빈칸 제외하고 텍스트만 싹 모아서 띄어쓰기로 연결)
                    loc_lis = row.select("td.location li")
                    address_parts = []
                    for li in loc_lis:
                        if "thumb" not in li.get("class", []) and li.text.strip():
                            address_parts.append(li.text.strip())
                    address = " ".join(address_parts)
                    
                    # 4. 거래유형 & 5. 매물가 (만원 -> 원 변환)
                    price_td = row.select_one("td.prices")
                    trade_type = ""
                    formatted_price = ""
                    if price_td:
                        p_tags = price_td.find_all("p")
                        if len(p_tags) >= 2:
                            trade_type = p_tags[0].text.strip()
                            raw_price = p_tags[1].text.strip()
                            formatted_price = convert_price_to_full(raw_price)
                    
                    extracted_data.append({
                        "platform": "mk", # 심플하게 mk로 고정!
                        "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):
    """매경 재등록 (추후 구현)"""
    pass