import os
import json
import base64
import urllib.request
import urllib.parse
import ssl

CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gdrive_config.json")

DEFAULT_CONFIG = {
    "account": "kegiatanpcnu@gmail.com",
    "folder_name": "Surat Masuk PCNU",
    "webhook_url": "",
    "enabled": True,
    "auto_backup": True
}

def load_config():
    if not os.path.exists(CONFIG_FILE):
        save_config(DEFAULT_CONFIG)
        return DEFAULT_CONFIG
    try:
        with open(CONFIG_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
            # Merge with default in case of missing keys
            for k, v in DEFAULT_CONFIG.items():
                if k not in data:
                    data[k] = v
            return data
    except Exception as e:
        print(f"[GDRIVE] Error loading config: {e}")
        return DEFAULT_CONFIG

def save_config(cfg):
    try:
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(cfg, f, indent=2, ensure_ascii=False)
        return True
    except Exception as e:
        print(f"[GDRIVE] Error saving config: {e}")
        return False

def test_connection():
    cfg = load_config()
    url = cfg.get("webhook_url", "").strip()
    if not url:
        return {
            "ok": False,
            "status": "unconfigured",
            "message": "URL Webhook Google Apps Script belum diisi."
        }
    
    try:
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE

        req = urllib.request.Request(url, headers={"User-Agent": "PCNU-SuperApp/1.0"})
        with urllib.request.urlopen(req, timeout=15, context=ctx) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            return {
                "ok": True,
                "status": "connected",
                "message": f"Terhubung ke Google Drive akun {cfg.get('account')}",
                "server_data": data
            }
    except Exception as e:
        return {
            "ok": False,
            "status": "error",
            "message": f"Gagal menghubungi Google Apps Script: {str(e)}"
        }

def upload_surat_to_gdrive(local_file_path, metadata):
    """
    Mengunggah berkas surat lokal ke Google Drive akun kegiatanpcnu@gmail.com
    ke dalam folder khusus 'Surat Masuk PCNU'.
    """
    cfg = load_config()
    if not cfg.get("enabled", True):
        return {"ok": False, "status": "disabled", "message": "Google Drive integration disabled"}

    webhook_url = cfg.get("webhook_url", "").strip()
    if not webhook_url:
        return {
            "ok": False,
            "status": "unconfigured",
            "message": "URL Webhook Google Drive belum diatur di gdrive_config.json"
        }

    if not os.path.exists(local_file_path):
        return {"ok": False, "status": "file_not_found", "message": f"Berkas lokal tidak ditemukan: {local_file_path}"}

    try:
        # Baca berkas dan encode ke base64
        with open(local_file_path, "rb") as f:
            file_bytes = f.read()

        base64_data = base64.b64encode(file_bytes).decode("utf-8")

        payload = {
            "fileName": os.path.basename(local_file_path),
            "mimeType": "application/pdf" if local_file_path.lower().endswith(".pdf") else "application/octet-stream",
            "fileData": base64_data,
            "folderName": cfg.get("folder_name", "Surat Masuk PCNU"),
            "noAgenda": metadata.get("nomor_agenda", ""),
            "nomorSurat": metadata.get("nomor_surat", ""),
            "tanggal": metadata.get("tanggal_surat", ""),
            "asal": metadata.get("asal_instansi", ""),
            "perihal": metadata.get("perihal", ""),
            "disposisi": metadata.get("disposisi", ""),
            "petugas": metadata.get("petugas", "Staf Kesekretariatan")
        }

        json_data = json.dumps(payload).encode("utf-8")
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE

        req = urllib.request.Request(
            webhook_url,
            data=json_data,
            headers={
                "Content-Type": "application/json",
                "User-Agent": "PCNU-SuperApp/1.0"
            },
            method="POST"
        )

        with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
            resp_body = resp.read().decode("utf-8")
            result = json.loads(resp_body)
            if result.get("status") == "success":
                return {
                    "ok": True,
                    "file_id": result.get("fileId"),
                    "file_url": result.get("fileUrl"),
                    "file_name": result.get("fileName"),
                    "folder_name": result.get("folderName"),
                    "folder_url": result.get("folderUrl")
                }
            else:
                return {
                    "ok": False,
                    "status": "gdrive_error",
                    "message": result.get("message", "Unknown error from Google Apps Script")
                }

    except Exception as e:
        print(f"[GDRIVE] Upload error: {e}")
        return {
            "ok": False,
            "status": "network_error",
            "message": str(e)
        }

