#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
from datetime import datetime
from typing import Any, Dict

import requests

API_ROOT = "https://open.feishu.cn/open-apis"


def build_auth_parser(description: str) -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("--app-id", required=True)
    parser.add_argument("--app-secret", required=True)
    return parser


def tenant_access_token(app_id: str, app_secret: str) -> str:
    response = requests.post(
        f"{API_ROOT}/auth/v3/tenant_access_token/internal",
        json={"app_id": str(app_id), "app_secret": str(app_secret)},
        timeout=30,
    )
    response.raise_for_status()
    payload = response.json() if response.content else {}
    token = str(payload.get("tenant_access_token") or "").strip()
    if not token:
        raise RuntimeError(json.dumps(payload, ensure_ascii=False))
    return token


def auth_headers(token: str) -> Dict[str, str]:
    return {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json; charset=utf-8",
    }


def api_request(method: str, url: str, *, token: str, **kwargs) -> Any:
    response = requests.request(
        method,
        url,
        headers=auth_headers(token),
        timeout=30,
        **kwargs,
    )
    try:
        payload = response.json() if response.content else {}
    except Exception:
        payload = {"raw_text": response.text}
    if response.status_code >= 300:
        dump(
            {
                "status": "error",
                "http_status": response.status_code,
                "url": url,
                "payload": payload,
            }
        )
        raise SystemExit(1)
    return payload


def normalize_feishu_event_time(raw: str, default_timezone: str = "Asia/Shanghai") -> Dict[str, str]:
    text = str(raw or "").strip()
    if not text:
        raise ValueError("time value is required")
    if text.isdigit():
        return {"timestamp": text, "timezone": default_timezone}
    parsed = datetime.fromisoformat(text)
    timezone_name = default_timezone
    if parsed.tzinfo is not None:
        tzname = parsed.tzname()
        if tzname and tzname not in {"UTC+08:00", "UTC+0800"}:
            timezone_name = tzname
    return {
        "timestamp": str(int(parsed.timestamp())),
        "timezone": default_timezone if timezone_name in {"UTC+08:00", "UTC+0800"} else timezone_name,
    }


def dump(payload: Any) -> None:
    print(json.dumps(payload, ensure_ascii=False, indent=2))
