"""
Ingestion orchestrator — Premium ETL เฟส 1
==========================================
รัน connector ทั้ง 5 แพลตฟอร์ม → รวม orders + inventory ที่ normalize แล้ว
จัดการ partial failure: แพลตฟอร์มเดียวล้ม → log + ทำต่อ (ไม่ abort) — เป็นรากฐานของ HTTP 207 ในเฟส 3

เฟสนี้ "ส่งออก" เป็น JSON (ยังไม่เข้า Postgres — นั่นเฟส 2)
รันเทส:  SAMPLE_MODE=1 python extract_all.py
"""
from __future__ import annotations

import os
import json
import logging

from connectors import CONNECTORS

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("ingestion")


def run_ingestion() -> dict:
    all_orders, all_inventory, per_platform, errors = [], [], [], []

    for cls in CONNECTORS:
        result = cls().extract()                    # แต่ละตัวจับ exception ในตัวแล้ว
        per_platform.append(result.summary())
        if result.ok:
            all_orders.extend(r.to_dict() for r in result.orders)
            all_inventory.extend(r.to_dict() for r in result.inventory)
        else:
            errors.append(f"{result.platform}: {result.error}")

    ok_count = sum(1 for p in per_platform if p["ok"])
    payload = {
        "orders": all_orders,
        "inventory": all_inventory,
        "_meta": {
            "platforms_ok": ok_count,
            "platforms_total": len(CONNECTORS),
            "orders": len(all_orders),
            "inventory": len(all_inventory),
            "errors": errors,
            "per_platform": per_platform,
        },
    }
    log.info("ingestion done: %s/%s platforms ok, %s orders, %s inventory, %s errors",
             ok_count, len(CONNECTORS), len(all_orders), len(all_inventory), len(errors))
    return payload


if __name__ == "__main__":
    out = run_ingestion()
    # เฟส 1 ส่งออกเป็นไฟล์ JSON (เฟส 2 จะอ่านไฟล์นี้ไป UPSERT เข้า Postgres)
    path = os.environ.get("OUT", "sample_output.json")
    with open(path, "w", encoding="utf-8") as f:
        json.dump(out, f, ensure_ascii=False, indent=2)
    print(json.dumps(out["_meta"], ensure_ascii=False, indent=2))
