# -*- coding: utf-8 -*-

import os
import sys
import argparse
from datetime import datetime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from db import get_conn


STORAGE_BASE = os.path.join(BASE_DIR, "storage", "realestate")


def ensure_dir(path):
    os.makedirs(path, exist_ok=True)


def get_font(size=28):
    try:
        from PIL import ImageFont

        candidates = [
            "C:/Windows/Fonts/malgun.ttf",
            "C:/Windows/Fonts/malgunbd.ttf",
            "C:/Windows/Fonts/NanumGothic.ttf",
        ]

        for path in candidates:
            if os.path.exists(path):
                return ImageFont.truetype(path, size)

        return ImageFont.load_default()

    except Exception:
        return None


def create_info_card(output_path, title, lines):
    from PIL import Image, ImageDraw

    width = 1000
    height = 620

    img = Image.new("RGB", (width, height), "#f8fafc")
    draw = ImageDraw.Draw(img)

    title_font = get_font(42)
    body_font = get_font(28)
    small_font = get_font(22)

    # background
    draw.rounded_rectangle(
        [40, 40, width - 40, height - 40],
        radius=32,
        fill="#ffffff",
        outline="#d1d5db",
        width=2,
    )

    draw.text((80, 82), title, fill="#111827", font=title_font)

    y = 165

    for line in lines:
        if not line:
            continue

        draw.text((90, y), f"• {line}", fill="#374151", font=body_font)
        y += 48

    draw.line((80, height - 105, width - 80, height - 105), fill="#e5e7eb", width=2)
    draw.text(
        (80, height - 82),
        "※ 실제 방문 전 주소와 상담 가능 여부를 반드시 확인해 주세요.",
        fill="#6b7280",
        font=small_font,
    )

    img.save(output_path, quality=92)


def fetch_article_detail(conn, realtor_id, article_no):
    with conn.cursor() as cur:
        cur.execute("""
            SELECT
                d.article_no,
                d.article_title,
                d.complex_name,
                d.trade_type,
                d.real_estate_type,
                d.price_text,
                d.address,
                d.road_address,
                d.floor_info,
                d.area_info,
                d.parking_info,

                r.id AS realtor_id,
                r.office_name,
                r.representative_name,
                r.office_phone,
                r.mobile_phone,
                r.naver_realtor_id

            FROM blog_realestate_article_details d

            LEFT JOIN blog_realtors r
                ON r.id = %s

            WHERE d.article_no = %s

            ORDER BY d.id DESC
            LIMIT 1
        """, (
            realtor_id,
            str(article_no),
        ))

        return cur.fetchone()


def upsert_extra_image(
    conn,
    realtor_id,
    article_no,
    image_title,
    image_caption,
    image_source,
    local_path,
    sort_order,
):
    with conn.cursor() as cur:
        cur.execute("""
            INSERT INTO blog_article_extra_images
            (
                realtor_id,
                article_no,
                image_title,
                image_caption,
                image_source,
                local_path,
                public_url,
                original_url,
                is_approved,
                sort_order,
                created_at,
                updated_at
            )
            VALUES
            (
                %s,
                %s,
                %s,
                %s,
                %s,
                %s,
                NULL,
                NULL,
                1,
                %s,
                NOW(),
                NOW()
            )
        """, (
            realtor_id,
            str(article_no),
            image_title,
            image_caption,
            image_source,
            local_path,
            sort_order,
        ))

    conn.commit()


def delete_existing_auto_extra_images(conn, realtor_id, article_no):
    with conn.cursor() as cur:
        cur.execute("""
            DELETE FROM blog_article_extra_images
            WHERE realtor_id = %s
              AND article_no = %s
              AND image_source IN ('auto_location_card', 'auto_office_card')
        """, (
            realtor_id,
            str(article_no),
        ))

    conn.commit()


def generate_for_article(conn, realtor_id, article_no, force=False):
    detail = fetch_article_detail(conn, realtor_id, article_no)

    if not detail:
        print(f"[NO DETAIL] {article_no}")
        return

    if force:
        delete_existing_auto_extra_images(conn, realtor_id, article_no)

    article_dir = os.path.join(STORAGE_BASE, str(article_no), "extra")
    ensure_dir(article_dir)

    title = detail.get("article_title") or detail.get("complex_name") or "매물 위치 안내"
    address = detail.get("road_address") or detail.get("address") or ""
    office_name = detail.get("office_name") or ""
    office_phone = detail.get("office_phone") or detail.get("mobile_phone") or ""

    # 1. 매물 위치 안내 카드
    location_path = os.path.join(article_dir, "extra_location_card.png")

    create_info_card(
        location_path,
        "매물 위치 안내",
        [
            f"매물명: {title}",
            f"주소: {address}",
            f"거래유형: {detail.get('trade_type') or '-'}",
            f"가격: {detail.get('price_text') or '-'}",
            f"면적: {detail.get('area_info') or '-'}",
            f"층수: {detail.get('floor_info') or '-'}",
        ],
    )

    upsert_extra_image(
        conn=conn,
        realtor_id=realtor_id,
        article_no=article_no,
        image_title="매물 위치 안내",
        image_caption="매물 주소와 핵심 정보를 요약한 위치 안내 이미지입니다.",
        image_source="auto_location_card",
        local_path=location_path,
        sort_order=10,
    )

    print(f"[EXTRA SAVED] {location_path}")

    # 2. 중개사 오시는 길 카드
    office_path = os.path.join(article_dir, "extra_office_card.png")

    create_info_card(
        office_path,
        "중개사무소 오시는 길",
        [
            f"중개사무소: {office_name}",
            f"대표자: {detail.get('representative_name') or '-'}",
            f"연락처: {office_phone or '-'}",
            f"단체아이디: {detail.get('naver_realtor_id') or '-'}",
            "상담 전 방문 가능 시간을 확인해 주세요.",
        ],
    )

    upsert_extra_image(
        conn=conn,
        realtor_id=realtor_id,
        article_no=article_no,
        image_title="중개사무소 오시는 길",
        image_caption="중개사무소 상담 안내 이미지입니다.",
        image_source="auto_office_card",
        local_path=office_path,
        sort_order=20,
    )

    print(f"[EXTRA SAVED] {office_path}")


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("--realtor-id", type=int, required=True)
    parser.add_argument("--article-no", type=str, required=True)
    parser.add_argument("--force", action="store_true")

    args = parser.parse_args()

    conn = get_conn()

    try:
        print("=" * 80)
        print("[START] generate_extra_image_candidates")
        print("TIME:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        print("=" * 80)

        generate_for_article(
            conn=conn,
            realtor_id=args.realtor_id,
            article_no=args.article_no,
            force=args.force,
        )

        print("=" * 80)
        print("[DONE] generate_extra_image_candidates")
        print("=" * 80)

    finally:
        conn.close()


if __name__ == "__main__":
    main()