import os
from pathlib import Path

import mysql.connector
from dotenv import load_dotenv
from mysql.connector import Error


load_dotenv(Path(__file__).resolve().parents[1] / ".env")

DB_CONFIG = {
    "host": os.environ["DB_HOST"],
    "port": int(os.environ.get("DB_PORT", "3306")),
    "user": os.environ["DB_USER"],
    "password": os.environ["DB_PASSWORD"],
    "database": os.environ["DB_NAME"],
}

CREATE_MODERATION_LOGS_SQL = """
CREATE TABLE IF NOT EXISTS babynote_content_moderation_logs (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    content_type VARCHAR(30) NOT NULL COMMENT '조치 대상 타입 (diary, diary_comment)',
    content_id VARCHAR(36) NOT NULL COMMENT '조치 당시 대상 ID',
    owner_user_id VARCHAR(36) NOT NULL COMMENT '조치 대상 작성자 ID',
    diary_id VARCHAR(36) NULL COMMENT '관련 일기 ID',
    action VARCHAR(30) NOT NULL COMMENT '조치 종류 (make_private, make_public, delete)',
    reason VARCHAR(1000) NOT NULL COMMENT '관리자 입력 조치 사유',
    previous_state JSON NULL COMMENT '조치 이전 상태 스냅샷',
    admin_user_id VARCHAR(36) NULL COMMENT '조치 관리자 ID',
    admin_name VARCHAR(100) NULL COMMENT '조치 관리자명',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_moderation_content (content_type, content_id),
    INDEX idx_moderation_owner (owner_user_id, created_at),
    INDEX idx_moderation_diary (diary_id, created_at),
    INDEX idx_moderation_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='아가노트 일기·댓글 운영 조치 감사 로그'
"""

NOTIFICATION_COLUMNS = [
    (
        "moderation_log_id",
        "ADD COLUMN moderation_log_id BIGINT NULL COMMENT '관련 콘텐츠 운영 조치 로그 ID' AFTER together_care_occurrence_date",
    ),
    (
        "moderation_content_type",
        "ADD COLUMN moderation_content_type VARCHAR(30) NULL COMMENT '운영 조치 대상 타입' AFTER moderation_log_id",
    ),
    (
        "moderation_content_id",
        "ADD COLUMN moderation_content_id VARCHAR(36) NULL COMMENT '운영 조치 대상 ID' AFTER moderation_content_type",
    ),
    (
        "moderation_action",
        "ADD COLUMN moderation_action VARCHAR(30) NULL COMMENT '운영 조치 종류' AFTER moderation_content_id",
    ),
    (
        "moderation_reason",
        "ADD COLUMN moderation_reason TEXT NULL COMMENT '운영 조치 사유' AFTER moderation_action",
    ),
]

MODERATION_TERMS_ARTICLE = """
<h2>제10조 (게시물 운영 및 이용 제한)</h2>
<ol>
  <li>회원은 타인의 권리 또는 사생활을 침해하거나, 명예를 훼손하거나, 아동의 안전을 해치거나, 불법·음란·혐오·괴롭힘·도배·사칭에 해당하는 콘텐츠를 게시해서는 안 됩니다.</li>
  <li>회사는 신고 또는 자체 확인을 통해 운영 정책 위반 가능성이 있는 일기나 댓글을 확인한 경우 필요한 범위에서 공개 범위를 비공개로 변경하거나, 게시물 또는 댓글을 삭제하거나, 서비스 이용을 제한할 수 있습니다.</li>
  <li>회사는 긴급한 아동 안전 보호, 법령 준수 또는 중대한 피해 방지가 필요한 경우 사전 통지 없이 조치할 수 있으며, 조치 후 그 사유를 서비스 알림 등 합리적인 방법으로 안내합니다.</li>
  <li>회원은 운영 조치에 이의가 있는 경우 고객센터를 통해 재검토를 요청할 수 있습니다.</li>
  <li>본 조항에 따른 운영 조치는 회원이 보유한 게시물의 저작권 귀속에 영향을 주지 않습니다.</li>
</ol>

<h2>제11조 (면책조항)</h2>
""".strip()


def execute_ignoring(cursor, sql, ignored_errno):
    try:
        cursor.execute(sql)
    except Error as error:
        if error.errno not in ignored_errno:
            raise


def migrate_policy_index(cursor):
    cursor.execute(
        "SHOW INDEX FROM app_policies WHERE Key_name = 'unique_app_policy_lang'"
    )
    if cursor.fetchall():
        cursor.execute("ALTER TABLE app_policies DROP INDEX unique_app_policy_lang")

    execute_ignoring(
        cursor,
        "ALTER TABLE app_policies "
        "ADD UNIQUE KEY unique_app_policy_lang_version "
        "(app_name, policy_type, language_code, version)",
        {1061},
    )


def seed_moderation_terms(cursor):
    cursor.execute(
        "SELECT content FROM app_policies "
        "WHERE app_name = 'babynote' AND policy_type = 'terms' "
        "AND language_code = 'ko' AND version = '1.0' LIMIT 1"
    )
    row = cursor.fetchone()
    if not row:
        print("WARN: BabyNote Korean terms v1.0 not found; skipped terms v1.1 seed")
        return

    content = row[0]
    content = content.replace(
        "시행일자:</strong> 2025년 10월 28일",
        "시행일자:</strong> 2026년 9월 7일",
    )
    content = content.replace("버전:</strong> 1.0", "버전:</strong> 1.1")
    content = content.replace(
        "<h2>제10조 (면책조항)</h2>", MODERATION_TERMS_ARTICLE
    )
    content = content.replace(
        "<h2>제11조 (분쟁 해결)</h2>", "<h2>제12조 (분쟁 해결)</h2>"
    )
    content = content.replace(
        "이 약관은 2025년 10월 28일부터 시행됩니다.",
        "이 약관은 2026년 9월 7일부터 시행됩니다.",
    )

    cursor.execute(
        "INSERT INTO app_policies "
        "(app_name, policy_type, language_code, title, content, version, effective_date) "
        "VALUES ('babynote', 'terms', 'ko', '아가노트 이용약관', %s, '1.1', '2026-09-07') "
        "ON DUPLICATE KEY UPDATE content = VALUES(content), "
        "effective_date = VALUES(effective_date), updated_at = CURRENT_TIMESTAMP",
        (content,),
    )


def run():
    connection = mysql.connector.connect(**DB_CONFIG)
    cursor = connection.cursor()
    try:
        cursor.execute(CREATE_MODERATION_LOGS_SQL)
        for _, column_sql in NOTIFICATION_COLUMNS:
            execute_ignoring(
                cursor,
                f"ALTER TABLE notifications {column_sql}",
                {1060},
            )
        execute_ignoring(
            cursor,
            "ALTER TABLE notifications "
            "ADD INDEX idx_moderation_log_id (moderation_log_id)",
            {1061},
        )
        migrate_policy_index(cursor)
        seed_moderation_terms(cursor)
        connection.commit()
        print("OK: BabyNote content moderation schema and terms v1.1 applied")
    except Exception:
        connection.rollback()
        raise
    finally:
        cursor.close()
        connection.close()


if __name__ == "__main__":
    run()
