# -*- coding: utf-8 -*-

import re


READY_MIN_IMAGES = 1
READY_MIN_TEXT_LENGTH = 500

REVIEW_MIN_IMAGES = 0
REVIEW_MIN_TEXT_LENGTH = 250


def strip_html(html):
    if not html:
        return ""

    text = re.sub(r"<[^>]+>", " ", html)
    text = re.sub(r"\s+", " ", text)
    return text.strip()


def count_images(html):
    if not html:
        return 0

    return len(re.findall(r"<img\s", html, re.I))


def validate_draft(draft_row):
    reasons = []

    draft_title = str(draft_row.get("draft_title") or "").strip()
    draft_html = str(draft_row.get("draft_html") or "").strip()
    plain_text = str(draft_row.get("plain_text") or "").strip()

    text = strip_html(draft_html)
    combined_text = (plain_text + " " + text).strip()

    text_length = len(combined_text)
    image_count = count_images(draft_html)

    score = 0

    if draft_title:
        score += 20
    else:
        reasons.append("title_missing")

    if text_length >= READY_MIN_TEXT_LENGTH:
        score += 30
    elif text_length >= REVIEW_MIN_TEXT_LENGTH:
        score += 15
        reasons.append("text_short")
    else:
        reasons.append("text_too_short")

    if image_count >= READY_MIN_IMAGES:
        score += 25
    else:
        reasons.append("image_missing")

    if any(k in combined_text for k in ["매매", "전세", "월세", "보증금", "가격", "임대"]):
        score += 10
    else:
        reasons.append("price_info_missing")

    if any(k in combined_text for k in ["공인중개사", "대표", "등록번호", "중개사무소"]):
        score += 10
    else:
        reasons.append("realtor_info_missing")

    if any(k in combined_text for k in ["공인중개사법", "표시", "광고", "포스팅 일시"]):
        score += 5
    else:
        reasons.append("legal_notice_missing")

    if score >= 70 and image_count >= 1 and text_length >= READY_MIN_TEXT_LENGTH:
        status = "ready"
    elif score >= 40 and text_length >= REVIEW_MIN_TEXT_LENGTH:
        status = "review"
    else:
        status = "failed"

    return {
        "status": status,
        "score": score,
        "image_count": image_count,
        "text_length": text_length,
        "reasons": reasons,
    }