#!/usr/bin/env python3
"""
Sync lesson JSON files to Airtable 'Lessons' table.
Run: python3 /data/chief/sync_lessons.py

Requirements: pip install pyairtable
"""
import os
import re
import json
import logging
from pathlib import Path
from pyairtable import Table
from pyairtable.formulas import match

# Configuration (from subagent task)
API_TOKEN = "patyTRuhaTzNTzN5Z.15df8e29226aa79a04b14520b914a2f1daf7485afe95df7540dd28336070241d"
BASE_ID = "app4DkahU1S8ACrJJ"
TABLE_NAME = "Lessons"

LESSONS_DIR = Path("/data/.openclaw/agents/course-builder/workspace/lessons/")
FILENAME_RE = re.compile(r"lesson-(?P<module>\d+)\.(?P<lesson_number>\d+)\.json$")

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("sync_lessons")


def load_json(path: Path):
    try:
        with path.open("r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception as e:
        logger.exception("Failed to load JSON %s: %s", path, e)
        return None


def parse_filename(filename: str):
    m = FILENAME_RE.search(filename)
    if not m:
        return None
    return int(m.group("module")), int(m.group("lesson_number"))


def combine_content(content_en, content_es):
    parts = []
    if content_en:
        parts.append("EN:\n" + content_en.strip())
    if content_es:
        parts.append("ES:\n" + content_es.strip())
    return "\n\n".join(parts) if parts else ""


def normalize_bool(v):
    if isinstance(v, bool):
        return v
    if v is None:
        return False
    if isinstance(v, (int, float)):
        return bool(v)
    s = str(v).strip().lower()
    return s in ("1", "true", "yes", "y", "si")


def sync_lesson(table: Table, filepath: Path):
    logger.info("Processing %s", filepath)
    data = load_json(filepath)
    if data is None:
        logger.error("Skipping %s due to load failure", filepath)
        return

    parsed = parse_filename(filepath.name)
    if not parsed:
        logger.error("Filename does not match pattern lesson-X.Y.json: %s", filepath.name)
        return
    module, lesson_number = parsed

    title = data.get("title") or data.get("title_en") or ""
    title_es = data.get("title_es") or data.get("titleSpanish") or ""
    content_en = data.get("content_en") or data.get("content") or ""
    content_es = data.get("content_es") or data.get("contentSpanish") or ""

    combined = combine_content(content_en, content_es)

    duration = data.get("duration") or data.get("estimated_duration") or data.get("Duration")
    video_url = data.get("video_url") or data.get("video") or data.get("Video URL") or ""
    free = normalize_bool(data.get("free") if "free" in data else data.get("Free"))

    # Prepare fields for Airtable
    fields = {
        "Content": combined,
        "Duration": duration,
        "Video URL": video_url,
        "Free": free,
        "Module": module,
        "Lesson Number": lesson_number,
        "Title": title,
        "Title Es": title_es,
    }

    # Try to find existing record by Module + Lesson Number or Title
    try:
        formula = match({"Module": module, "Lesson Number": lesson_number})
        records = table.all(formula=formula)
        if records:
            # Update first match
            rec_id = records[0]["id"]
            logger.info("Updating existing record %s for %s", rec_id, filepath.name)
            table.update(rec_id, fields)
        else:
            # create new
            logger.info("Creating new record for %s", filepath.name)
            table.create(fields)
    except Exception as e:
        logger.exception("Airtable operation failed for %s: %s", filepath.name, e)


def main():
    if not LESSONS_DIR.exists():
        logger.error("Lessons directory does not exist: %s", LESSONS_DIR)
        return

    try:
        table = Table(API_TOKEN, BASE_ID, TABLE_NAME)
    except Exception as e:
        logger.exception("Failed to connect to Airtable: %s", e)
        return

    json_files = sorted(LESSONS_DIR.glob("lesson-*.json"))
    if not json_files:
        logger.info("No lesson JSON files found in %s", LESSONS_DIR)
        return

    for path in json_files:
        try:
            sync_lesson(table, path)
        except Exception as e:
            logger.exception("Unexpected error processing %s: %s", path, e)


if __name__ == "__main__":
    main()
