"""匯出 SQLite 資料為 JSON，供 dashboard.html 使用"""
import sys
sys.stdout.reconfigure(encoding='utf-8')

import json
import os
import sqlite3

from database import DB_PATH


def export_json(output_path: str = "data/newhouse.json"):
    if not os.path.exists(DB_PATH):
        print(f"資料庫不存在: {DB_PATH}")
        return

    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute(
        "SELECT * FROM projects ORDER BY region, district, name"
    ).fetchall()
    conn.close()

    data = [dict(r) for r in rows]
    # 移除 raw_json 欄位（太大）
    for d in data:
        d.pop("raw_json", None)

    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    print(f"匯出 {len(data)} 筆到 {output_path}")


if __name__ == "__main__":
    export_json()
