import streamlit as st
import pandas as pd
import os
import textwrap

# 페이지 설정
st.set_page_config(page_title="경매 스나이퍼", page_icon="🎯", layout="centered")

TARGET_FILE = "data/targets.csv"

# --- CSS: 콤팩트 디자인 ---
st.markdown("""
<style>
    .block-container {
        padding-top: 1rem !important;
        padding-bottom: 3rem !important;
        padding-left: 0.5rem !important;
        padding-right: 0.5rem !important;
    }
    .auction-card {
        background-color: #ffffff;
        padding: 12px;
        border-radius: 8px;
        margin-bottom: 8px;
        border: 1px solid #e0e0e0;
        border-left: 4px solid #ff4b4b;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    }
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 4px;
        font-size: 12px;
        color: #666;
    }
    .card-status { font-weight: bold; color: #ff4b4b; }
    .card-title { font-size: 15px; font-weight: bold; color: #222; margin-bottom: 2px; }
    .card-info { font-size: 13px; color: #444; margin-bottom: 1px; }
    .card-price { font-size: 14px; font-weight: bold; color: #0068c9; margin-top: 4px; margin-bottom: 8px; }
    .btn-row { display: flex; gap: 6px; width: 100%; }
    .custom-btn {
        flex: 1; padding: 8px 0; text-align: center; text-decoration: none;
        border-radius: 6px; font-size: 13px; font-weight: bold; color: white !important; display: block;
    }
    .custom-btn:hover { opacity: 0.9; }
    .btn-auction { background-color: #ff4b4b; }
    .btn-market { background-color: #5d3fd3; }
    .category-badge {
        font-size: 11px; background-color: #eee; padding: 2px 6px; border-radius: 4px; color: #555;
    }
</style>
""", unsafe_allow_html=True)

# 타이틀
c1, c2 = st.columns([5, 1])
with c1: st.title("🎯 경매 스나이퍼")
with c2: 
    if st.button("🔄"): st.rerun()

if os.path.exists(TARGET_FILE):
    try:
        df = pd.read_csv(TARGET_FILE)
        
        # 데이터 전처리 (결측치 및 타입)
        if "market_link" not in df.columns: df["market_link"] = ""
        if "category" not in df.columns: df["category"] = "미분류"
        
        df["market_link"] = df["market_link"].fillna("").astype(str)
        df["category"] = df["category"].fillna("미분류").astype(str)
        
        # [지역 추출] address의 첫 단어 (서울, 경기 등)
        df['sido'] = df['address'].apply(lambda x: x.split()[0] if isinstance(x, str) and len(x.split()) > 0 else "기타")

        if not df.empty:
            # ==================================================
            # [필터 UI] 2단 필터 (지역 -> 종류)
            # ==================================================
            f_col1, f_col2 = st.columns(2)
            
            with f_col1:
                sido_list = ["전체 지역"] + sorted(df['sido'].unique().tolist())
                sel_sido = st.selectbox("지역", sido_list, label_visibility="collapsed")
            
            # 1차 필터링
            if sel_sido != "전체 지역":
                filtered_df = df[df['sido'] == sel_sido]
            else:
                filtered_df = df
            
            with f_col2:
                # 필터링된 데이터 기반으로 카테고리 목록 갱신
                cat_list = ["전체 종류"] + sorted(filtered_df['category'].unique().tolist())
                sel_cat = st.selectbox("종류", cat_list, label_visibility="collapsed")
            
            # 2차 필터링
            if sel_cat != "전체 종류":
                final_df = filtered_df[filtered_df['category'] == sel_cat]
            else:
                final_df = filtered_df
            
            # 결과 표시
            st.caption(f"검색 결과: {len(final_df)}건")

            for index, row in final_df.iterrows():
                # 값 추출
                case_no = row.get('case_no', '-')
                status = row.get('status', '-')
                addr = row.get('address', '-')
                price = row.get('price_info', '-')
                area = row.get('area_info', '-')
                date = row.get('auction_date', '-')
                category = row.get('category', '미분류')
                
                link_a = row.get('link', '#')
                link_m = row.get('market_link')
                
                # 아이콘 및 라벨 결정
                btn_label = "🔎 보기"
                if "hogangnono" in link_m: btn_label = "🏠 호갱"
                elif "m.land.naver" in link_m: btn_label = "🏘️ 부동"
                elif "map.naver" in link_m: btn_label = "🗺️ 지도"
                
                # 시세 링크 없으면 기본값
                if not link_m or link_m == "nan" or link_m == "":
                    link_m = f"https://hogangnono.com/search?q={addr.split()[0]}"

                html_code = textwrap.dedent(f"""
                    <div class="auction-card">
                        <div class="card-header">
                            <div>
                                <span class="card-status">{status}</span>
                                <span class="category-badge">{category}</span>
                            </div>
                            <span>{date}</span>
                        </div>
                        <div class="card-title">{case_no}</div>
                        <div class="card-info">📍 {addr}</div>
                        <div class="card-info">📐 {area}</div>
                        <div class="card-price">💰 {price}</div>
                        <div class="btn-row">
                            <a href="{link_a}" target="_blank" class="custom-btn btn-auction">🔗 경매</a>
                            <a href="{link_m}" target="_blank" class="custom-btn btn-market">{btn_label}</a>
                        </div>
                    </div>
                """)
                st.markdown(html_code, unsafe_allow_html=True)
        else:
            st.info("데이터가 없습니다.")
            
    except Exception as e:
        st.error(f"오류 발생: {e}")
else:
    st.warning("데이터 파일이 없습니다.")