# -*- coding: utf-8 -*-
"""DB 접속 및 공통 헬퍼"""
import pymysql
import yaml
import os
import json
from datetime import datetime, date

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

_config = None
def get_config():
    global _config
    if _config is None:
        with open(os.path.join(BASE_DIR, "config.yaml"), encoding="utf-8") as f:
            _config = yaml.safe_load(f)
    return _config

def get_conn():
    c = get_config()["db"]
    return pymysql.connect(
        host=c["host"], port=c.get("port", 3306), user=c["user"],
        password=c["password"], database=c["database"],
        charset=c.get("charset", "utf8mb4"),
        cursorclass=pymysql.cursors.DictCursor, autocommit=True,
    )

def log_stage(stage, status, items=0, error=None, started_at=None):
    """pipeline_logs 기록"""
    with get_conn() as conn, conn.cursor() as cur:
        cur.execute(
            """INSERT INTO pipeline_logs
               (run_date, stage, status, items_processed, started_at, finished_at, error_msg)
               VALUES (%s,%s,%s,%s,%s,NOW(),%s)""",
            (date.today(), stage, status, items,
             started_at or datetime.now(), (error or "")[:2000] or None),
        )

def upsert_item(conn, item: dict):
    """auction_items UPSERT. item: dict with keys matching columns"""
    with conn.cursor() as cur:
        cur.execute(
            """INSERT INTO auction_items
               (case_no, court, item_no, property_type, address, region_code,
                appraisal_price, min_bid_price, fail_count, sale_date,
                area_land, area_building, note, photo_url, status,
                first_crawled_at, last_updated_at)
               VALUES (%(case_no)s,%(court)s,%(item_no)s,%(property_type)s,%(address)s,
                       %(region_code)s,%(appraisal_price)s,%(min_bid_price)s,%(fail_count)s,
                       %(sale_date)s,%(area_land)s,%(area_building)s,%(note)s,%(photo_url)s,
                       'active',NOW(),NOW())
               ON DUPLICATE KEY UPDATE
                 min_bid_price=VALUES(min_bid_price), fail_count=VALUES(fail_count),
                 sale_date=VALUES(sale_date), note=VALUES(note),
                 status='active', last_updated_at=NOW(), id=LAST_INSERT_ID(id)""",
            item,
        )
        return cur.lastrowid

def save_document(conn, item_id, doc_type, raw_text):
    with conn.cursor() as cur:
        cur.execute("DELETE FROM item_documents WHERE item_id=%s AND doc_type=%s",
                    (item_id, doc_type))
        cur.execute(
            "INSERT INTO item_documents (item_id, doc_type, raw_text, crawled_at) "
            "VALUES (%s,%s,%s,NOW())", (item_id, doc_type, raw_text))

def json_default(o):
    if isinstance(o, (datetime, date)):
        return o.isoformat()
    raise TypeError
