# -*- coding: utf-8 -*-
"""
STEP106-05 V2 resolver quick test

목적:
- 어디서 실행해도 프로젝트 루트(D:/honghee/blog_api)를 sys.path에 추가한다.
- 기존 services/naver_search_complex_resolver.py는 import하지 않는다.
- V2 전용 services/naver_search_complex_resolver_v2.py만 테스트한다.

사용 예:
  python tools/test_step106_04_v2_complex_resolver.py --query "산울6단지세종리첸시아파밀리에(주상복합) 605동 · 매매 · 7억 9,000" --region "세종시"

HTML 파일로 테스트:
  python tools/test_step106_04_v2_complex_resolver.py --html search_card.html --query "산울6단지세종리첸시아파밀리에(주상복합) 605동 · 매매 · 7억 9,000" --region "세종시"
"""

import argparse
import json
import os
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from services.naver_search_complex_resolver_v2 import (
    parse_naver_search_complex_card_html,
    merge_with_listing_fallback,
    resolve_complex_address,
)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--html", default="", help="네이버 검색 단지카드 HTML 파일. 없으면 실제 네이버 검색을 실행한다.")
    parser.add_argument("--query", required=True)
    parser.add_argument("--region", default="")
    parser.add_argument("--listing-json", default="", help="검색 실패 fallback 테스트용 기존 매물 수집 JSON 파일")
    parser.add_argument("--save", action="store_true", help="blog_complex_address_cache 저장까지 실행")
    parser.add_argument("--headless", action="store_true")
    args = parser.parse_args()

    listing_data = {}
    if args.listing_json:
        listing_data = json.loads(Path(args.listing_json).read_text(encoding="utf-8"))

    if args.html:
        html = Path(args.html).read_text(encoding="utf-8")
        search_result = parse_naver_search_complex_card_html(html, query=args.query, region_hint=args.region)
        result = merge_with_listing_fallback(search_result, listing_data=listing_data, region_hint=args.region)
    else:
        result = resolve_complex_address(
            args.query,
            region_hint=args.region,
            listing_data=listing_data,
            headless=args.headless,
        )

    print(json.dumps(result.__dict__, ensure_ascii=False, indent=2))

    if args.save:
        from services.naver_search_complex_resolver_v2 import get_db_conn_from_env, upsert_complex_address_cache

        conn = get_db_conn_from_env()
        try:
            saved = upsert_complex_address_cache(conn, args.region, args.query, result)
            print("[CACHE SAVE RESULT]")
            print(json.dumps(saved, ensure_ascii=False, indent=2))
        finally:
            conn.close()


if __name__ == "__main__":
    main()
