"""Copy Facebook Page insights from Pozy into PostgreSQL. Run it once a day."""
import os
import time
from datetime import date, timedelta

import psycopg
import requests

API = "https://api.pozy.ai/v1"
KEY = os.environ["POZY_API_KEY"]            # a read-only Pozy key
PAGES = [p.strip() for p in os.environ["POZY_FACEBOOK_ACCOUNTS"].split(",") if p.strip()]
ADS = [a.strip() for a in os.environ.get("POZY_ADS_ACCOUNTS", "").split(",") if a.strip()]  # optional
DB = os.environ["DATABASE_URL"]             # postgresql://user:password@host:5432/dbname
DAYS_BACK = int(os.environ.get("DAYS_BACK", "7"))
METRICS = ("page_media_view,page_total_media_view_unique,page_views_total,"
           "page_post_engagements,page_video_views,page_follows,"
           "followers_gained,followers_lost")

TABLES = """
create table if not exists facebook_page_daily (
  account_id text not null,
  day        date not null,
  metric     text not null,
  value      numeric not null,
  synced_at  timestamptz not null default now(),
  primary key (account_id, day, metric)
);
create table if not exists facebook_posts (
  post_id      text primary key,
  account_id   text not null,
  url          text,
  published_at timestamptz,
  caption      text,
  impressions  bigint, reach bigint, views bigint, likes bigint,
  comments     bigint, shares bigint, clicks bigint,
  synced_at    timestamptz not null default now()
);
create table if not exists ads_daily (
  account_id  text not null,
  day         date not null,
  currency    text not null,
  spend       numeric, impressions bigint, clicks bigint,
  conversions numeric, purchase_value numeric,
  synced_at   timestamptz not null default now(),
  primary key (account_id, day, currency)
);
"""


def get(path, **params):
    """One read from Pozy. Waits and retries when Pozy says slow down."""
    while True:
        r = requests.get(API + path, params=params, timeout=60,
                         headers={"Authorization": f"Bearer {KEY}"})
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "5")))
            continue
        r.raise_for_status()
        return r.json()


def windows(start, end, size=88):
    """Pozy answers 89 days of page insights at a time, so cut long ranges up."""
    while start <= end:
        stop = min(start + timedelta(days=size), end)
        yield start, stop
        start = stop + timedelta(days=1)


def sync_page(db, page_id, start, end):
    rows = 0
    for a, b in windows(start, end):
        data = get("/analytics/facebook/page-insights", accountId=page_id,
                   metricType="time_series", metrics=METRICS,
                   fromDate=a, toDate=b)
        for metric, series in data["metrics"].items():
            for point in series.get("values", []):
                if point.get("value") is None:
                    continue
                db.execute(
                    """insert into facebook_page_daily (account_id, day, metric, value)
                       values (%s, %s, %s, %s)
                       on conflict (account_id, day, metric)
                       do update set value = excluded.value, synced_at = now()""",
                    (page_id, point["date"], metric, point["value"]))
                rows += 1
    return rows


def sync_posts(db, page_id, start, end):
    rows, page = 0, 1
    while True:
        data = get("/analytics", accountId=page_id, platform="facebook",
                   fromDate=start, toDate=end, limit=100, page=page)
        for post in data["posts"]:
            n = post.get("analytics") or {}
            db.execute(
                """insert into facebook_posts (post_id, account_id, url, published_at, caption,
                     impressions, reach, views, likes, comments, shares, clicks)
                   values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                   on conflict (post_id) do update set
                     impressions = excluded.impressions, reach = excluded.reach,
                     views = excluded.views, likes = excluded.likes,
                     comments = excluded.comments, shares = excluded.shares,
                     clicks = excluded.clicks, synced_at = now()""",
                (post["_id"], page_id, post.get("platformPostUrl"), post.get("publishedAt"),
                 post.get("content"), n.get("impressions"), n.get("reach"), n.get("views"),
                 n.get("likes"), n.get("comments"), n.get("shares"), n.get("clicks")))
            rows += 1
        if page >= data["pagination"]["pages"]:
            return rows
        page += 1


def sync_ads(db, account, start, end):
    data = get("/ads/timeline", accountId=account, fromDate=start, toDate=end)
    for row in data["rows"]:
        db.execute(
            """insert into ads_daily (account_id, day, currency, spend, impressions,
                 clicks, conversions, purchase_value)
               values (%s, %s, %s, %s, %s, %s, %s, %s)
               on conflict (account_id, day, currency) do update set
                 spend = excluded.spend, impressions = excluded.impressions,
                 clicks = excluded.clicks, conversions = excluded.conversions,
                 purchase_value = excluded.purchase_value, synced_at = now()""",
            (account, row["date"], row.get("currency") or "", row.get("spend"),
             row.get("impressions"), row.get("clicks"), row.get("conversions"),
             row.get("purchaseValue")))
    return len(data["rows"])


if __name__ == "__main__":
    end = date.today()
    start = end - timedelta(days=DAYS_BACK)
    # a post keeps collecting views for weeks, so posts are read at least 90 days back
    posts_start = end - timedelta(days=max(DAYS_BACK, 90))
    with psycopg.connect(DB, autocommit=True) as db:
        db.execute(TABLES)
        for page_id in PAGES:
            print("page rows:", sync_page(db, page_id, start, end))
            print("post rows:", sync_posts(db, page_id, posts_start, end))
        for account in ADS:
            print("ads rows:", sync_ads(db, account, start, end))
