# -*- coding: utf-8 -*-

import json
import random
import requests

from config import (
    ENABLE_OLLAMA,
    OLLAMA_API_URL,
    OLLAMA_MODEL,
)


def build_property_prompt(article_detail):

    article_name = article_detail.get("article_title") or ""
    article_desc = article_detail.get("article_desc") or ""
    trade_type = article_detail.get("trade_type", "")
    real_estate_type = article_detail.get("real_estate_type", "")
    price_text = article_detail.get("price_text", "")
    floor_info = article_detail.get("floor_info", "")
    area_info = article_detail.get("area_info", "")
    address = article_detail.get("address", "")
    road_address = article_detail.get("road_address", "")
    parking_info = article_detail.get("parking_info", "")
    direction = article_detail.get("direction", "")
    building_usage = article_detail.get("building_usage") or ""

    realtor_info = article_detail.get("realtor_info", {})
    prices = article_detail.get("market_prices", [])
    schools = article_detail.get("schools", [])

    price_lines = []

    for p in prices[:8]:

        line = []

        if p.get("deal_type"):
            line.append(str(p.get("deal_type")))

        if p.get("price_text"):
            line.append(str(p.get("price_text")))

        if p.get("floor_info"):
            line.append(str(p.get("floor_info")))

        if line:
            price_lines.append(" / ".join(line))

    school_lines = []

    for s in schools[:8]:

        name = s.get("school_name") or ""
        dist = s.get("distance") or ""

        if name:
            school_lines.append(f"{name} {dist}")

    feeling_style = random.choice([
        "차분하고 신뢰감 있는 중개사 말투",
        "실제 방문한 느낌의 현장 설명 스타일",
        "고급스럽고 자연스러운 부동산 매거진 스타일",
        "지역 중개 전문가 느낌",
        "실거주 관점 설명 스타일",
        "프리미엄 부동산 에디터 스타일",
        "현장 중심 리뷰 스타일",
        "고객 상담 기반 설명 스타일",
    ])

    return f"""
너는 네이버 부동산 전문 블로그 작가다.

절대 AI처럼 쓰지 말 것.

매우 중요:
- 실제 공인중개사가 현장 방문 후 작성한 느낌
- 같은 표현 반복 금지
- 문장 길이 다양하게
- 기계적 나열 금지
- 생활 관점 설명 포함
- 투자 관점 설명 포함
- 실거주 관점 설명 포함
- 현장 분위기 표현
- 공간감 표현
- 채광/동선/주변 느낌 표현
- 과장 광고 금지
- 없는 정보 상상 금지
- 자연스러운 블로그 문체
- 사람 냄새 나는 문장
- 문단 간 연결감 만들 것

문체 스타일:
{feeling_style}

매물 정보:

[기본정보]
- 매물명: {article_name}
- 설명: {article_desc}
- 거래유형: {trade_type}
- 부동산유형: {real_estate_type}
- 가격: {price_text}
- 층수: {floor_info}
- 면적: {area_info}
- 주소: {address}
- 도로명주소: {road_address}
- 주차: {parking_info}
- 방향: {direction}
- 용도: {building_usage}

[중개사정보]
- 중개사무소: {realtor_info.get("office_name", "")}
- 대표자: {realtor_info.get("representative_name", "")}

[실거래 및 시세]
{chr(10).join(price_lines)}

[학군정보]
{chr(10).join(school_lines)}

반드시 아래 JSON 형식만 출력해라.

{{
  "intro": "도입 문단 (5~8문장)",
  "location": "입지 및 생활권 설명 (6~10문장)",
  "space": "실내 구조 및 공간 설명 (6~10문장)",
  "point": "추천 포인트 및 장점 설명 (5~8문장)",
  "price": "가격 및 실거래 흐름 해석 (5~8문장)",
  "school": "학군 및 생활환경 설명 (4~6문장)",
  "investment": "투자 관점 설명 (4~6문장)",
  "caution": "확인 포인트 및 체크사항 (3~5문장)",
  "realtor": "중개사 안내 및 상담 유도 (3~5문장)",
  "closing": "마무리 문단 (4~6문장)"
}}
""".strip()


def fallback_sections(article_detail):

    title = article_detail.get("article_title") or "추천 매물"

    return {
        "intro": f"{title} 매물을 소개드립니다. 현장에서 확인했을 때 공간감과 구조가 안정적으로 느껴지는 매물입니다.",
        "location": "주변 생활 인프라와 이동 동선을 함께 고려해보면 실거주 관점에서도 검토해볼 수 있는 위치입니다.",
        "space": "실내 구조와 채광 방향 등을 함께 확인해보면 공간 활용 측면에서도 장점이 있습니다.",
        "point": "현재 조건 기준으로 비교해보면 충분히 관심 있게 볼 수 있는 매물로 판단됩니다.",
        "price": "가격 조건 역시 최근 시장 흐름과 함께 비교해보며 검토하시면 좋습니다.",
        "school": "생활권과 주변 교육환경도 함께 체크해보시면 좋겠습니다.",
        "investment": "향후 시장 흐름과 입지 조건까지 함께 고려해보며 검토하시면 좋겠습니다.",
        "caution": "실제 계약 전에는 현장 확인과 함께 세부 조건을 다시 체크해보시는 것을 추천드립니다.",
        "realtor": "자세한 상담은 등록 중개사무소를 통해 확인 가능합니다.",
        "closing": "관심 있으신 분들은 직접 현장 확인과 함께 자세한 상담을 받아보시길 추천드립니다.",
    }


def generate_ai_sections(article_detail):

    if not ENABLE_OLLAMA:
        return fallback_sections(article_detail)

    prompt = build_property_prompt(article_detail)

    try:

        res = requests.post(
            OLLAMA_API_URL,
            json={
                "model": OLLAMA_MODEL,
                "prompt": prompt,
                "stream": False,
                "options": {
                    "temperature": 0.92,
                    "top_p": 0.95,
                    "repeat_penalty": 1.18,
                    "num_predict": 1800,
                }
            },
            timeout=300
        )

        if res.status_code != 200:
            return fallback_sections(article_detail)

        data = res.json()

        text = data.get("response", "").strip()

        if not text:
            return fallback_sections(article_detail)

        start = text.find("{")
        end = text.rfind("}")

        if start == -1 or end == -1:
            return fallback_sections(article_detail)

        parsed = json.loads(text[start:end + 1])

        return {
            "intro": parsed.get("intro", ""),
            "location": parsed.get("location", ""),
            "space": parsed.get("space", ""),
            "point": parsed.get("point", ""),
            "price": parsed.get("price", ""),
            "school": parsed.get("school", ""),
            "investment": parsed.get("investment", ""),
            "caution": parsed.get("caution", ""),
            "realtor": parsed.get("realtor", ""),
            "closing": parsed.get("closing", ""),
        }

    except Exception as e:

        print("[OLLAMA ERROR]", str(e))

        return fallback_sections(article_detail)