#!/usr/bin/env python3
"""
MosaicEarth Official WebODM & NodeODM Connector (v2.1)
Pushes finished Orthophotos (COG/GeoTIFF), DSMs, 3D Models (OBJ/GLB) and Point Clouds (LAZ)
from a local WebODM or NodeODM instance directly into your MosaicEarth MyEarth Hierarchy
(Project -> Survey -> Task -> Asset), or keeps them indexed locally.
"""
import argparse
import json
import os
import sys
import urllib.request

DEFAULT_CLOUD_URL = os.environ.get("MOSAICEARTH_URL", "https://next.mosaicearth.app")

def sync_webodm_task_to_myearth(cloud_url: str, email: str, password: str, project_name: str, survey_name: str, task_name: str, file_path: str, lat: float, lon: float):
    endpoint = f"{cloud_url.rstrip('/')}/api/v2/connectors/sync"
    payload = {
        "email": email,
        "password": password,
        "connector": "webodm",
        "project_name": project_name,
        "survey_name": survey_name,
        "task_name": task_name,
        "asset_title": os.path.basename(file_path) if file_path else task_name,
        "source_format": os.path.splitext(file_path)[1].lstrip(".").upper() if file_path else "TIF",
        "latitude": lat,
        "longitude": lon,
        "size_bytes": os.path.getsize(file_path) if (file_path and os.path.isfile(file_path)) else 0,
    }
    req = urllib.request.Request(
        endpoint,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json", "User-Agent": "MosaicEarth-WebODM-Connector/2.1"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.loads(resp.read().decode("utf-8"))

def main():
    parser = argparse.ArgumentParser(description="MosaicEarth WebODM / NodeODM Connector")
    parser.add_argument("--url", default=DEFAULT_CLOUD_URL, help="MosaicEarth server URL")
    parser.add_argument("--email", required=True, help="Your MosaicEarth account email")
    parser.add_argument("--password", required=True, help="Your MosaicEarth account password")
    parser.add_argument("--project", default="WebODM Captures", help="Target Level-1 Project name in MyEarth")
    parser.add_argument("--survey", default="01 Field Survey", help="Target Level-2 Survey name in MyEarth")
    parser.add_argument("--task", default="WebODM Photogrammetry", help="Target Level-3 Task name in MyEarth")
    parser.add_argument("--file", default="", help="Path to local orthophoto.tif, pointcloud.laz or 3d_model.obj")
    parser.add_argument("--lat", type=float, default=41.9794, help="WGS84 Latitude")
    parser.add_argument("--lon", type=float, default=2.8214, help="WGS84 Longitude")
    args = parser.parse_args()
    res = sync_webodm_task_to_myearth(args.url, args.email, args.password, args.project, args.survey, args.task, args.file, args.lat, args.lon)
    print(json.dumps(res, indent=2))

if __name__ == "__main__":
    main()
