def has_local_keyword(keywords):
    local_tokens = [
        "동탄", "화성", "수원", "용인", "성남", "서울", "부산", "인천",
        "대구", "광주", "대전", "울산", "세종", "제주",
        "아파트", "오피스텔", "빌라", "주택",
        "전세", "월세", "매매", "분양", "급매", "임대",
        "단지", "역세권", "학군", "상가", "부동산"
    ]

    keyword_texts = [str(x.get("keyword", "")).strip() for x in keywords]
    joined = " ".join(keyword_texts)

    return any(token in joined for token in local_tokens)


def build_consulting_comments(
    analysis,
    posts,
    search_exposure=None,
    trends=None,
    collect_status="ok",
    trend_status="ok"
):
    comments = []
    actions = []

    total_posts = int(analysis.get("total_posts", 0) or 0)
    recent_30d = int(analysis.get("recent_30d_posts", 0) or 0)
    recent_7d = int(analysis.get("recent_7d_posts", 0) or 0)
    avg_gap = float(analysis.get("avg_post_interval_days", 0) or 0)

    activity_score = float(analysis.get("activity_score", 0) or 0)
    consistency_score = float(analysis.get("consistency_score", 0) or 0)
    exposure_score = float(analysis.get("exposure_score", 0) or 0)
    trend_score = float(analysis.get("trend_score", 0) or 0)
    final_score = float(analysis.get("final_score", 0) or 0)

    top_keywords = analysis.get("top_keywords", []) or []

    keyword_count = len(top_keywords)
    top1_count = int(top_keywords[0]["count"]) if keyword_count >= 1 and "count" in top_keywords[0] else 0
    top2_count = int(top_keywords[1]["count"]) if keyword_count >= 2 and "count" in top_keywords[1] else 0

    if collect_status != "ok":
        comments.append("게시글 수집 상태가 정상적이지 않아 일부 분석 결과의 신뢰도가 낮을 수 있습니다.")
        actions.append("먼저 블로그 수집 상태를 정상화한 뒤 다시 분석하는 것이 좋습니다.")

    if total_posts == 0:
        comments.append("수집된 게시글이 없어 운영 상태를 충분히 판단하기 어렵습니다.")
        actions.append("블로그 공개 상태와 게시글 수집 경로를 먼저 점검하세요.")
        return {
            "summary": "현재는 게시글 데이터 부족으로 정밀 진단이 어려운 상태입니다.",
            "comments": comments,
            "actions": actions
        }

    # 활동량 진단
    if recent_30d <= 1:
        comments.append("최근 30일 발행량이 매우 낮아 블로그 활성도가 떨어질 가능성이 큽니다.")
        actions.append("최소 주 1~2회 이상 꾸준히 글을 발행하는 패턴을 만드는 것이 좋습니다.")
    elif recent_30d <= 4:
        comments.append("최근 30일 활동량은 낮은 편이라 노출 누적 효과가 약할 수 있습니다.")
        actions.append("최근 30일 기준 발행 횟수를 지금보다 조금 더 늘리는 전략이 필요합니다.")
    elif recent_30d >= 12:
        comments.append("최근 30일 활동량은 양호한 편으로, 기본적인 운영 성실도는 확보되어 있습니다.")

    if recent_7d == 0:
        comments.append("최근 7일 내 새 글이 없어 최신성 측면에서는 다소 약한 흐름입니다.")
        actions.append("이번 주 안에 최신 주제 글을 1건 이상 보강하는 것이 좋습니다.")

    # 발행 간격 진단
    if avg_gap >= 10:
        comments.append("글 발행 간격이 긴 편이라 검색 누적 흐름이 끊길 수 있습니다.")
        actions.append("발행 간격을 줄여 일정한 업로드 리듬을 만드는 것이 좋습니다.")
    elif avg_gap > 0 and avg_gap <= 4:
        comments.append("글 발행 간격이 비교적 안정적이라 운영 리듬은 괜찮은 편입니다.")

    # 키워드 다양성 진단
    if keyword_count <= 3:
        comments.append("상위 키워드 수가 적어 주제 확장성이 약한 편입니다.")
        actions.append("핵심 주제는 유지하되 연관 키워드를 추가해 콘텐츠 폭을 넓혀보세요.")
    elif keyword_count >= 8:
        comments.append("상위 키워드 구성이 비교적 다양한 편이라 주제 확장성은 괜찮습니다.")

    # 키워드 편중 진단
    if keyword_count >= 1 and top1_count >= (top2_count * 2 + 3):
        comments.append("특정 키워드에 편중된 경향이 있어 주제 다양성이 부족할 수 있습니다.")
        actions.append("기존 대표 키워드와 함께 세부 하위 키워드를 분산 배치하는 것이 좋습니다.")

    # 지역/실검색 키워드
    if not has_local_keyword(top_keywords):
        comments.append("지역명 또는 실수요 검색 키워드 비중이 낮아 지역 기반 유입 확보에 약할 수 있습니다.")
        actions.append("지역명, 단지명, 거래유형 같은 실검색 키워드를 제목과 본문에 보강하세요.")
    else:
        comments.append("지역 또는 실수요 키워드가 일부 포함되어 있어 검색 유입 기반은 어느 정도 확보되어 있습니다.")

    # 검색 노출 진단
    if exposure_score < 30:
        comments.append("검색 노출 점수가 낮아 현재 글들이 외부 검색 유입을 충분히 받지 못할 가능성이 있습니다.")
        actions.append("제목 구조를 단순 정보형에서 검색 의도형 제목으로 바꾸는 전략이 필요합니다.")
    elif exposure_score >= 60:
        comments.append("검색 노출 점수는 비교적 양호한 편으로, 제목과 주제 선택은 어느 정도 맞고 있습니다.")

    # 트렌드 진단
    if trend_status != "ok":
        comments.append("트렌드 데이터는 현재 정상 수집되지 않아 보조 분석이 제한된 상태입니다.")
    elif trend_score < 20:
        comments.append("현재 사용 중인 키워드가 최근 검색 흐름과 강하게 맞물리지 않을 가능성이 있습니다.")
        actions.append("최근 검색 반응이 있는 키워드를 일부 섞어 주제 선정을 조정해보세요.")
    elif trend_score >= 50:
        comments.append("현재 키워드 흐름은 최근 검색 추세와 비교적 잘 맞는 편입니다.")

    # 점수 기반 종합 의견
    if final_score >= 80:
        summary = "현재 블로그는 활동성과 운영 방향이 전반적으로 우수한 편입니다."
    elif final_score >= 60:
        summary = "현재 블로그는 기본 운영은 괜찮지만, 발행량과 키워드 전략을 다듬으면 더 좋아질 수 있습니다."
    else:
        summary = "현재 블로그는 활동량과 키워드 운영 측면에서 보완이 필요한 상태입니다."

    # 추가 정리 문구
    if activity_score < 40:
        actions.append("최근 발행량 부족이 전체 점수 하락의 핵심 원인이므로 콘텐츠 생산량부터 보강하세요.")

    if consistency_score < 40:
        actions.append("핵심 키워드를 일정하게 반복 사용해 주제 일관성을 높이는 것이 좋습니다.")

    # 중복 제거
    dedup_comments = []
    seen_comments = set()
    for item in comments:
        if item not in seen_comments:
            seen_comments.add(item)
            dedup_comments.append(item)

    dedup_actions = []
    seen_actions = set()
    for item in actions:
        if item not in seen_actions:
            seen_actions.add(item)
            dedup_actions.append(item)

    if not dedup_actions:
        dedup_actions.append("현재 강점을 유지하면서 주제 일관성과 발행 리듬을 꾸준히 이어가는 것이 좋습니다.")

    return {
        "summary": summary,
        "comments": dedup_comments[:6],
        "actions": dedup_actions[:5]
    }