from pathlib import Path
import datetime
import json
import os
import urllib.parse
import urllib.request
from zoneinfo import ZoneInfo

values = dict(os.environ)
for line in (Path.home() / ".config/gac-mai-audio/postiz.env").read_text().splitlines():
    if line and not line.lstrip().startswith("#") and "=" in line:
        key, value = line.split("=", 1)
        values[key.strip()] = value.strip().strip('"').strip("'")
base = values["POSTIZ_BASE_URL"].rstrip("/")
api_key = values["POSTIZ_API_KEY"]
expected = {
    "facebook": values["POSTIZ_FACEBOOK_INTEGRATION_ID"],
    "youtube": values["POSTIZ_YOUTUBE_INTEGRATION_ID"],
}

def get(path):
    request = urllib.request.Request(base + path, headers={"Authorization": api_key})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)

assert get("/is-connected").get("connected") is True
raw = get("/integrations")
rows = raw if isinstance(raw, list) else raw.get("integrations", raw.get("data", []))
selected = []
for platform, integration_id in expected.items():
    match = next((row for row in rows if str(row.get("id")) == integration_id), None)
    assert match is not None
    assert str(match.get("name")) == "Gác Mái Audio"
    # Platform identity is pinned by separate configured IDs; this API omits provider fields.
    assert match.get("disabled") is False
    selected.append({"platform": platform, "id": integration_id, "name": match.get("name")})

timezone = ZoneInfo("Asia/Ho_Chi_Minh")
now = datetime.datetime.now(timezone)
start = now.replace(minute=0, second=0, microsecond=0) + datetime.timedelta(hours=1)
end = start + datetime.timedelta(days=14)
params = urllib.parse.urlencode({
    "startDate": start.astimezone(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
    "endDate": end.astimezone(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
})
raw_posts = get("/posts?" + params)
posts = raw_posts if isinstance(raw_posts, list) else raw_posts.get("posts", raw_posts.get("data", []))
target_ids = set(expected.values())
busy = set()
target_count = 0
for post in posts:
    ids = {str(item.get("id")) for item in post.get("integration", []) if isinstance(item, dict)}
    ids.add(str(post.get("integrationId", "")))
    if ids & target_ids:
        target_count += 1
        if post.get("date"):
            busy.add(post["date"][:16])
slot = None
for offset in range(14):
    date = (now + datetime.timedelta(days=offset)).date()
    for hour, minute in ((9, 20), (19, 0)):
        candidate = datetime.datetime.combine(date, datetime.time(hour, minute), timezone)
        if candidate <= now + datetime.timedelta(hours=2):
            continue
        key = candidate.astimezone(datetime.timezone.utc).isoformat(timespec="minutes").replace("+00:00", "")
        if key not in busy:
            slot = candidate
            break
    if slot:
        break
assert slot is not None
print(json.dumps({
    "identity_gate": "PASS",
    "integrations": selected,
    "now_local": now.isoformat(),
    "candidate_slot_local": slot.isoformat(),
    "candidate_slot_utc": slot.astimezone(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
    "target_posts_in_scan": target_count,
}, ensure_ascii=False))
