# -*- coding: utf-8 -*-

import os
import sys
import time
import webbrowser
from pathlib import Path

import pymysql

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(CURRENT_DIR)

if ROOT_DIR not in sys.path:
    sys.path.append(ROOT_DIR)

from db import get_conn


PUBLISH_READY_DIR = os.path.join(
    ROOT_DIR,
    "storage",
    "publish_ready"
)

NAVER_BLOG_WRITE_URL = (
    "https://blog.naver.com/PostWriteForm.naver"
)


class NaverBlogPublishAssistant:

    def __init__(self):

        os.makedirs(
            PUBLISH_READY_DIR,
            exist_ok=True
        )

    # ---------------------------------------------------------
    # QUEUE
    # ---------------------------------------------------------

    def get_pending_queue(self):

        conn = get_conn()

        try:

            sql = """
            SELECT

                q.id,
                q.draft_id,
                q.article_no,
                q.publish_title,
                q.clipboard_html,

                d.clipboard_html AS draft_clipboard_html

            FROM blog_publish_queue q

            LEFT JOIN blog_article_drafts d
            ON CONVERT(q.article_no USING utf8mb4)
               COLLATE utf8mb4_unicode_ci
            =
               CONVERT(d.article_no USING utf8mb4)
               COLLATE utf8mb4_unicode_ci

            WHERE q.queue_status = 'pending'

            ORDER BY q.id ASC
            LIMIT 1
            """

            with conn.cursor(
                pymysql.cursors.DictCursor
            ) as cur:

                cur.execute(sql)

                row = cur.fetchone()

            return row

        finally:

            conn.close()

    def update_queue_status(
        self,
        queue_id,
        status
    ):

        conn = get_conn()

        try:

            sets = [
                "queue_status = %s",
                "updated_at = NOW()",
            ]

            params = [status]

            if status == "processing":

                sets.append(
                    "started_at = NOW()"
                )

            if status == "published":

                sets.append(
                    "finished_at = NOW()"
                )

            sql = f"""
            UPDATE blog_publish_queue
            SET {", ".join(sets)}
            WHERE id = %s
            """

            params.append(queue_id)

            with conn.cursor() as cur:

                cur.execute(sql, params)

            conn.commit()

        finally:

            conn.close()

    # ---------------------------------------------------------
    # FILE
    # ---------------------------------------------------------

    def save_html_file(
        self,
        article_no,
        title,
        html
    ):

        safe_title = (
            title
            .replace("/", "_")
            .replace("\\", "_")
            .replace(":", "_")
            .replace("*", "_")
            .replace("?", "_")
            .replace('"', "_")
            .replace("<", "_")
            .replace(">", "_")
            .replace("|", "_")
        )

        filename = (
            f"{article_no}_{safe_title}.html"
        )

        file_path = os.path.join(
            PUBLISH_READY_DIR,
            filename
        )

        template = f"""<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>{title}</title>
<style>
body {{
    background:#f5f5f5;
    margin:0;
    padding:30px;
    font-family:
        "Pretendard",
        "Malgun Gothic",
        sans-serif;
}}

.publish-wrap {{
    max-width:960px;
    margin:0 auto;
    background:#ffffff;
    padding:40px;
    border-radius:20px;
    box-shadow:
        0 10px 40px rgba(0,0,0,0.08);
}}
</style>
</head>
<body>

<div class="publish-wrap">

{html}

</div>

</body>
</html>
"""

        with open(
            file_path,
            "w",
            encoding="utf-8"
        ) as f:

            f.write(template)

        return file_path

    # ---------------------------------------------------------
    # OPEN
    # ---------------------------------------------------------

    def open_naver_blog(self):

        try:

            webbrowser.open(
                NAVER_BLOG_WRITE_URL
            )

            print(
                "[NAVER BLOG OPEN]"
            )

        except Exception as e:

            print(
                "[OPEN ERROR]",
                str(e)
            )

    # ---------------------------------------------------------
    # RUN
    # ---------------------------------------------------------

    def run(self):

        print("=" * 80)
        print(
            "[START] naver_blog_publish_assistant"
        )
        print("=" * 80)

        queue = self.get_pending_queue()

        if not queue:

            print(
                "[QUEUE] pending empty"
            )

            return

        queue_id = queue["id"]

        article_no = (
            queue.get("article_no")
            or ""
        )

        title = (
            queue.get("publish_title")
            or f"article_{article_no}"
        )

        html = (
            queue.get("clipboard_html")
            or queue.get("draft_clipboard_html")
            or ""
        )

        if not html:

            print(
                "[ERROR] clipboard_html empty"
            )

            return

        print("-" * 80)
        print("[QUEUE ID]", queue_id)
        print("[ARTICLE NO]", article_no)
        print("[TITLE]", title)

        self.update_queue_status(
            queue_id,
            "processing"
        )

        print(
            "[QUEUE STATUS] processing"
        )

        file_path = self.save_html_file(
            article_no,
            title,
            html
        )

        print(
            "[HTML FILE]",
            file_path
        )

        self.open_naver_blog()

        print("-" * 80)
        print(
            "[READY]"
        )
        print(
            "1. 네이버 블로그 글쓰기 페이지 확인"
        )
        print(
            "2. 생성된 HTML 파일 브라우저 확인"
        )
        print(
            "3. HTML 복사 후 네이버 에디터 붙여넣기"
        )
        print(
            "4. 발행 완료 후 publish_queue_manager.php 에서 상태 변경"
        )

        print("=" * 80)
        print("[DONE]")
        print("=" * 80)


def main():

    worker = (
        NaverBlogPublishAssistant()
    )

    worker.run()


if __name__ == "__main__":
    main()
