import openpyxl
import os

# --- 서버 경로 설정 ---
# 템플릿 파일이 있는 디렉토리 경로 (서버 경로)
TEMPLATE_DIR = "/home/air/sos/templates/" 
TEMPLATE_FILENAME = "20251112_A.xlsx"

# 확인할 셀 주소 목록
CELLS_TO_CHECK = [
    'Q3', 'Z3', 'P4', 'F14', 'Z11', 'AO20', 'D31', 'A18', 'A45', 'A47'
]

def check_merged_cells():
    """
    지정된 엑셀 템플릿을 열고, 목록에 있는 셀들이 병합된 셀인지,
    그리고 대표 주소인지 확인합니다.
    """
    template_path = os.path.join(TEMPLATE_DIR, TEMPLATE_FILENAME)

    if not os.path.exists(template_path):
        print(f"오류: 템플릿 파일을 찾을 수 없습니다. 경로를 확인해주세요: {template_path}")
        return

    try:
        # openpyxl 라이브러리가 없다면 'pip install openpyxl' 명령어로 설치해주세요.
        workbook = openpyxl.load_workbook(template_path)
        sheet = workbook.active
        
        print(f"--- '{TEMPLATE_FILENAME}' 파일의 셀 병합 상태 확인 ---")

        # 모든 병합된 셀 범위를 가져옵니다.
        merged_ranges = sheet.merged_cells.ranges

        for cell_addr in CELLS_TO_CHECK:
            is_part_of_merge = False
            for merged_range in merged_ranges:
                if cell_addr in merged_range:
                    is_part_of_merge = True
                    # 병합된 범위의 시작 셀(대표 주소)을 가져옵니다.
                    top_left_addr = merged_range.coord.split(':')[0]
                    
                    if cell_addr == top_left_addr:
                        print(f"✅ 셀 '{cell_addr}': 병합된 셀의 '대표 주소'가 맞습니다. (범위: {merged_range.coord})")
                    else:
                        print(f"❌ 셀 '{cell_addr}': 병합된 셀의 일부이지만, 대표 주소가 아닙니다! 이 범위의 대표 주소는 '{top_left_addr}' 입니다. (범위: {merged_range.coord})")
                    break
            
            if not is_part_of_merge:
                print(f"✅ 셀 '{cell_addr}': 병합되지 않은 일반 셀입니다.")

    except Exception as e:
        print(f"스크립트 실행 중 오류가 발생했습니다: {e}")

if __name__ == "__main__":
    check_merged_cells()
