#!/usr/bin/env python3
from pathlib import Path
import shutil, csv
from datetime import datetime

DL = Path.home()/"Downloads"
OUT = Path('/Users/ahmad/.openclaw/workspace/data/ads')
OUT.mkdir(parents=True, exist_ok=True)


def score_meta(p: Path):
    n = p.name.lower()
    s = 0
    if 'meta' in n or 'facebook' in n or 'ads manager' in n: s += 2
    try:
        with p.open('r', encoding='utf-8', errors='ignore') as f:
            head = f.read(2000).lower()
        if 'amount spent' in head or 'ad set name' in head: s += 3
    except Exception:
        pass
    return s


def score_google(p: Path):
    n = p.name.lower()
    s = 0
    if 'google' in n or 'ads editor' in n or 'campaign performance' in n: s += 2
    try:
        with p.open('r', encoding='utf-8', errors='ignore') as f:
            head = f.read(2000).lower()
        if 'impressions' in head and 'clicks' in head: s += 3
    except Exception:
        pass
    return s


def latest_csv():
    return sorted([p for p in DL.glob('*.csv') if p.is_file()], key=lambda p: p.stat().st_mtime, reverse=True)


def pick(scoring):
    best = None
    best_score = -1
    for p in latest_csv()[:60]:
        sc = scoring(p)
        if sc > best_score:
            best = p; best_score = sc
    return best, best_score


def main():
    meta, sm = pick(score_meta)
    goog, sg = pick(score_google)
    copied = []
    if meta and sm >= 3:
        dst = OUT/'meta_latest.csv'
        shutil.copy2(meta, dst)
        copied.append(f"meta:{meta.name}")
    if goog and sg >= 3:
        dst = OUT/'google_latest.csv'
        shutil.copy2(goog, dst)
        copied.append(f"google:{goog.name}")

    status = OUT/'ads_sync_status.md'
    status.write_text(
        "# Ads Export Sync Status\n"
        f"- Time: {datetime.now().isoformat(timespec='seconds')}\n"
        f"- Meta source: {meta.name if meta else 'none'} (score {sm})\n"
        f"- Google source: {goog.name if goog else 'none'} (score {sg})\n"
        f"- Copied: {', '.join(copied) if copied else 'none'}\n",
        encoding='utf-8'
    )
    print(status)


if __name__ == '__main__':
    main()
