# -*- coding: utf-8 -*-

import random

try:
    from .human_typing import human_type_text
    from .human_profile import (
        get_human_profile,
        get_typing_config,
        detect_property_type_from_context,
        build_profile_tail_comment,
    )
except Exception:
    from human_typing import human_type_text
    from human_profile import (
        get_human_profile,
        get_typing_config,
        detect_property_type_from_context,
        build_profile_tail_comment,
    )


def _safe_get(row, key, default=""):
    if not row:
        return default

    try:
        if isinstance(row, dict):
            return row.get(key, default)
        return getattr(row, key, default)
    except Exception:
        return default


def _build_context(draft=None, queue=None):
    draft = draft or {}
    queue = queue or {}

    title = (
        _safe_get(draft, "draft_title")
        or _safe_get(queue, "publish_title")
        or _safe_get(queue, "article_no")
        or "오늘 소개드린 매물"
    )

    return {
        "title": str(title or "").strip(),
        "office_name": str(_safe_get(draft, "office_name") or _safe_get(queue, "office_name") or "").strip(),
        "trade_type": str(_safe_get(draft, "trade_type") or "").strip(),
        "property_type": str(_safe_get(draft, "real_estate_type") or _safe_get(draft, "property_type") or "").strip(),
        "price": str(_safe_get(draft, "price_text") or "").strip(),
        "region": str(_safe_get(draft, "address") or "").strip(),
    }


def build_human_tail_comment(draft=None, queue=None, realtor_id=None, profile_id=None):
    profile = get_human_profile(realtor_id=realtor_id, profile_id=profile_id)
    property_type = detect_property_type_from_context(draft=draft, queue=queue)
    context = _build_context(draft=draft, queue=queue)

    comment = build_profile_tail_comment(
        realtor_id=realtor_id,
        profile=profile,
        property_type=property_type,
        context=context,
    )

    if comment:
        print(
            "[TAIL PROFILE]",
            f"profile={profile.get('profile_id')}",
            f"name={profile.get('name')}",
            f"property_type={property_type}",
            f"len={len(comment)}",
        )
        return comment

    return "방문 전에는 현재 매물 가능 여부와 조건 변동 여부를 먼저 확인해 주세요. 실제 현장에서 구조와 주변 환경을 함께 보시면 판단에 도움이 됩니다."


def type_tail_comment_after_body(page, frame=None, draft=None, queue=None, realtor_id=None, profile_id=None):
    rid = realtor_id or _safe_get(queue, "realtor_id")
    comment = build_human_tail_comment(
        draft=draft,
        queue=queue,
        realtor_id=rid,
        profile_id=profile_id,
    )

    if not comment:
        print("[TAIL COMMENT SKIP] empty")
        return False

    profile = get_human_profile(realtor_id=rid, profile_id=profile_id)
    typing_cfg = get_typing_config(profile)

    print("[TAIL COMMENT START]", f"len={len(comment)}")

    try:
        page.keyboard.press("End")
        page.wait_for_timeout(random.randint(400, 900))
        page.keyboard.press("Enter")
        page.keyboard.press("Enter")
        page.wait_for_timeout(random.randint(500, 1300))

        typed = human_type_text(
            page=page,
            text=comment,
            min_delay_ms=typing_cfg.get("min_delay_ms", 35),
            max_delay_ms=typing_cfg.get("max_delay_ms", 125),
            pause_chance=typing_cfg.get("pause_chance", 0.055),
        )

        page.wait_for_timeout(random.randint(800, 1800))

        print("[TAIL COMMENT DONE]", f"len={len(comment)}", f"typed={typed}")
        return True

    except Exception as e:
        print("[TAIL COMMENT ERROR]", str(e))
        return False
