# -*- coding: utf-8 -*-
"""MaemulHOME v1.0-only routes for the existing Shorts AI API.

Install as: D:/honghee/blog_api/v1/shorts_v1_routes.py
"""

from __future__ import annotations

import re
from typing import Any, Dict

import requests
from flask import jsonify, request


BUILD = "20260826-r1"


def _text(value: Any, limit: int = 0) -> str:
    value = str(value or "").replace("\r\n", "\n").replace("\r", "\n").strip()
    return value[:limit] if limit > 0 else value


def _property_type(title: str, content: str) -> str:
    source = f"{title} {content[:1500]}"
    rules = (
        ("아파트분양권", "아파트분양권"),
        ("분양권", "분양권"),
        ("오피스텔", "오피스텔"),
        ("아파트", "아파트"),
        ("단독", "단독주택"),
        ("다가구", "다가구주택"),
        ("빌라", "빌라"),
        ("연립", "연립주택"),
        ("상가", "상가"),
        ("공장", "공장"),
        ("토지", "토지"),
    )
    for needle, result in rules:
        if needle in source:
            return result
    return "부동산 매물"


def _prompt(data: Dict[str, Any]) -> str:
    title = _text(data.get("title") or data.get("post_title"), 500)
    content = _text(data.get("content") or data.get("post_summary"), 14000)
    article_no = _text(data.get("article_no"), 50)
    source_url = _text(data.get("source_url") or data.get("post_url"), 700)
    property_type = _property_type(title, content)
    return f"""
너는 네이버 부동산 블로그 원문을 45초 세로형 숏츠 대본으로 바꾸는 전문 작가다.

절대 원칙:
1. 아래 원본에 있는 정보만 사용한다.
2. 제목의 단지명, 동, 매물종류, 거래유형, 가격을 바꾸지 않는다.
3. 다른 지역, 다른 단지, 다른 매물의 정보를 절대 섞지 않는다.
4. 원본에 없는 방 수, 욕실 수, 면적, 교통, 학군, 수익, 개발 가능성을 만들지 않는다.
5. 허위·과장·확정 수익 표현을 사용하지 않는다.
6. 첫 문장은 핵심 매력이나 가격을 자연스럽게 소개한다.
7. 마지막은 현재 매물 확인과 중개사무소 상담을 자연스럽게 안내한다.
8. 260~380자의 자연스러운 한국어 구어체로 작성한다.
9. 장면, 자막, 나레이션, BGM, 시간표시, 마크다운, 해시태그, 설명 라벨을 출력하지 않는다.
10. 최종 대본 문장만 출력한다.

검증 기준:
- 매물번호: {article_no}
- 정확한 제목: {title}
- 매물종류: {property_type}
- 원문 URL: {source_url}

원본 내용:
{content}
""".strip()


def register_v1_routes(app: Any, legacy: Any) -> None:
    if "v1_generate_script" in app.view_functions:
        return

    @app.route("/v1/health", methods=["GET"], endpoint="v1_health")
    def v1_health():
        return jsonify({"ok": True, "message": "v1 shorts routes running", "build": BUILD})

    @app.route("/v1/generate-script", methods=["POST"], endpoint="v1_generate_script")
    def v1_generate_script():
        if not legacy.check_api_key(request):
            return legacy.unauthorized_response()
        data = request.get_json(silent=True) or {}
        title = _text(data.get("title") or data.get("post_title"), 500)
        content = _text(data.get("content") or data.get("post_summary"), 14000)
        if not title:
            return jsonify({"ok": False, "error": "v1 숏츠 원본 제목이 없습니다."}), 400
        if not content:
            return jsonify({"ok": False, "error": "v1 숏츠 원본 본문이 없습니다."}), 400
        try:
            response = requests.post(
                legacy.OLLAMA_URL,
                json={"model": legacy.MODEL_NAME, "prompt": _prompt(data), "stream": False},
                timeout=240,
            )
            response.raise_for_status()
            raw = _text((response.json() or {}).get("response"))
            script = legacy.clean_script_text(raw)
            script = legacy.sanitize_realestate_script_for_type(
                script,
                property_type=_property_type(title, content),
                title=title,
            )
            if not script:
                raise RuntimeError("Ollama가 빈 대본을 반환했습니다.")
            return jsonify({
                "ok": True,
                "api_version": "v1",
                "build": BUILD,
                "shorts_title": title,
                "script": script,
                "model": legacy.MODEL_NAME,
            })
        except requests.exceptions.ConnectionError:
            return jsonify({"ok": False, "error": "Ollama 서버에 연결할 수 없습니다."}), 500
        except requests.exceptions.Timeout:
            return jsonify({"ok": False, "error": "Ollama 응답 시간이 초과되었습니다."}), 500
        except Exception as exc:
            return jsonify({"ok": False, "error": str(exc)}), 500

    @app.route("/v1/render-video", methods=["POST"], endpoint="v1_render_video")
    def v1_render_video():
        # 실제 렌더링 엔진은 검증된 기존 함수를 재사용한다. v1 Worker가
        # render_key=v1_<id>를 전달하므로 파일명은 기존 프로젝트와 충돌하지 않는다.
        return legacy.render_video()
