#!/usr/bin/env python3
"""Smoke test Packlink PRO.

Uso:
  export PACKLINK_API_KEY=...
  export PACKLINK_BASE_URL=https://api.packlink.com/v1
  python scripts/test_packlink_connection.py
"""

from __future__ import annotations

import asyncio
import json
import os
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))
os.chdir(PROJECT_ROOT)

# Permite que o ficheiro seja importado por pytest sem exigir .env real.
os.environ.setdefault("OPENROUTER_API_KEY", "dummy")
os.environ.setdefault("DATABASE_URL", "postgresql+psycopg://clientflow:password@127.0.0.1:5432/clientflow")

from app.packlink_client import PacklinkClient


def normalize_packlink_zip(country: str, zip_code: str, *, for_quote: bool = True) -> str:
    country = str(country or "").upper().strip()
    zip_code = str(zip_code or "").strip()
    if country == "PT" and for_quote:
        import re
        match = re.search(r"\d{4}", zip_code)
        if match:
            return match.group(0)
    return zip_code


def default_package() -> dict:
    return {
        "height": int(float(os.getenv("PACKLINK_DEFAULT_PACKAGE_HEIGHT", "10"))),
        "width": int(float(os.getenv("PACKLINK_DEFAULT_PACKAGE_WIDTH", "20"))),
        "length": int(float(os.getenv("PACKLINK_DEFAULT_PACKAGE_LENGTH", "30"))),
        "weight": float(os.getenv("PACKLINK_DEFAULT_PACKAGE_WEIGHT", "2")),
    }


def dump(title: str, value) -> None:
    print(f"\n=== {title} ===")
    print(json.dumps(value, ensure_ascii=False, indent=2, default=str)[:5000])


async def main() -> int:
    if not os.getenv("PACKLINK_API_KEY"):
        print("ERRO: PACKLINK_API_KEY em falta")
        return 2

    client = PacklinkClient()
    account = await client.get_client()
    dump("Conta", account)

    warehouses = await client.get_warehouses()
    dump("Armazéns", warehouses[:3])

    parcels = await client.get_parcels()
    dump("Volumes", parcels[:3])

    from_zip = normalize_packlink_zip("PT", os.getenv("PACKLINK_TEST_FROM_ZIP", "3650-219"), for_quote=True)
    to_zip = normalize_packlink_zip("PT", os.getenv("PACKLINK_TEST_TO_ZIP", "4000-001"), for_quote=True)
    services = await client.quote_services(
        from_country="PT",
        from_zip=from_zip,
        to_country="PT",
        to_zip=to_zip,
        source=os.getenv("PACKLINK_SOURCE", "PRO"),
        packages=[default_package()],
    )

    simple = [
        {
            "id": s.get("id"),
            "carrier": s.get("carrier_name"),
            "service": s.get("name"),
            "price": (s.get("price") or {}).get("total_price") or s.get("base_price"),
            "currency": s.get("currency") or (s.get("price") or {}).get("currency"),
            "dropoff": s.get("dropoff"),
            "parcelshop": s.get("delivery_to_parcelshop"),
        }
        for s in services
    ]
    dump("Serviços", simple)

    service_id = os.getenv("PACKLINK_DEFAULT_SERVICE_ID", "20571")
    details = await client.get_service_details(service_id)
    dump(f"Detalhes serviço {service_id}", details)
    return 0


if __name__ == "__main__":
    raise SystemExit(asyncio.run(main()))
