#!/usr/bin/env python3
"""
xlsx의 StatusPoint DescriptorState0~7 → hc900.tag_metadata 로드
실행: python3 scripts/load_state_labels.py [--controller C1]
태그명은 Experion ItemName 원형 대소문자 유지 (ToLower 금지).
"""
import openpyxl
import psycopg2
import argparse
from pathlib import Path

XLSX_PATH = Path(__file__).parent.parent / "docs" / "Sinam_Tag_all.xlsx"
DB_DSN = "host=localhost port=5432 dbname=iiot_platform user=postgres password=postgres"

parser = argparse.ArgumentParser(description='Load StatusPoint state labels into tag_metadata')
parser.add_argument('--controller', default='HC1', help='Controller ID (default: HC1)')
args = parser.parse_args()

wb = openpyxl.load_workbook(XLSX_PATH, read_only=True, data_only=True)
ws = wb['Sheet1']
rows = list(ws.iter_rows(values_only=True))
headers = rows[1]
col = {h: i for i, h in enumerate(headers) if h}

conn = psycopg2.connect(DB_DSN)
cur = conn.cursor()

inserted = 0
for row in rows[2:]:
    name = str(row[col['ItemName']] or '').strip()
    cls  = str(row[col['Class']]    or '').strip()
    if cls != 'StatusPoint' or not name:
        continue

    # 원형(ItemName) 유지 — 소문자 변환 금지
    base_tag = name

    for i in range(8):
        key = f'DescriptorState{i}'
        if key not in col:
            continue
        val = row[col[key]]
        if val is None or val == '':
            continue
        cur.execute("""
            INSERT INTO hc900.tag_metadata (base_tag, attribute, value, controller_id)
            VALUES (%s, %s, %s, %s)
            ON CONFLICT (base_tag, attribute) DO UPDATE SET value = EXCLUDED.value, loaded_at = NOW()
        """, (base_tag, f'state{i}', str(val), args.controller))
        inserted += 1

conn.commit()
cur.close()
conn.close()
print(f"완료: {inserted}개 상태 레이블 저장 (controller={args.controller})")
