#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
fix_robots_txt.py — Perbaikan robots.txt StudioSoft
====================================================
FIX: typo pada baris Sitemap
  SALAH  : Sitemap: https://studiost.id/sitemap_index.xml  (missing 'o')
  BENAR  : Sitemap: https://studiosoft.id/sitemap_index.xml

Cara pakai:
  1) GENERATE KONTEN BENAR  : python3 fix_robots_txt.py generate
     -> menampilkan konten robots.txt yang sudah benar (fix typo sitemap)
  2) VERIFIKASI URL SITEMAP : python3 fix_robots_txt.py cek
     -> cek apakah URL sitemap benar-benar nyala (HTTP 200)
  3) TULIS KE FILE LOKAL   : python3 fix_robots_txt.py tulis
     -> membuat robots.txt lokal (untuk di-upload via FTP/cPanel/file manager)
  4) DEPLOY VIA FTP        : python3 fix_robots_txt.py deploy --host 103.175.217.138 \
        --user USER --pass PASS --path /public_html/robots.txt
     -> upload otomatis kalau ada kredensial FTP

CATATAN:
- File robots.txt StudioSoft adalah FILE FISIK di server, bukan virtual Yoast.
- Karena SSH port 22 tertutup, perlu akses FTP/cPanel/File Manager untuk menimpa.
- Konten di bawah mempertahankan semua aturan asli, hanya typo sitemap yang dibetulkan.
"""

import sys
import urllib.request
import urllib.error

# --- Konten robots.txt yang BENAR (fix typo) -------------------------------
# Konten asli dipertahankan 100%, HANYA baris Sitemap yang dikoreksi.
ROBOTS_BENAR = """# Allow all search engines
User-agent: *

# Disallow admin, login, and internal pages
Disallow: /wp-admin/
Disallow: /wp-login.php
Disallow: /wp-json/
Disallow: /xmlrpc.php
Disallow: /wp-includes/

# Disallow parameter pages (common for WordPress)
Disallow: /*?s=
Disallow: /*?orderby=
Disallow: /*?add-to-cart=

# Disallow duplicate / internal content
Disallow: /wp-content/uploads/wpcf7_captcha/
Disallow: /wp-content/cache/
Disallow: /cgi-bin/

# Allow main content and media (adjust if needed)
Allow: /wp-content/uploads/

# Disallow private or staging URLs (if any)
Disallow: /staging/
Disallow: /test/

# Allow sitemap (change URL if needed)
Sitemap: https://studiosoft.id/sitemap_index.xml
"""

SITE = "https://studiosoft.id"


def cek_url(url: str) -> str:
    """Cek status HTTP sebuah URL."""
    try:
        req = urllib.request.Request(url, method="GET", headers={"User-Agent": "Mozilla/5.0"})
        with urllib.request.urlopen(req, timeout=15) as resp:
            code = resp.getcode()
            final = resp.geturl()
            return f"{code} OK (-> {final})"
    except urllib.error.HTTPError as e:
        return f"{e.code} ({e.reason})"
    except Exception as e:
        return f"ERROR {e}"


def cmd_generate():
    print("#" * 60)
    print("# KONTEN robots.txt yang BENAR (fix typo sitemap)")
    print("#" * 60)
    print()
    print(ROBOTS_BENAR, end="")
    print("#" * 60)
    print("# Simpan konten di atas sebagai 'robots.txt' lalu deploy ke server.")
    print("#" * 60)


def cmd_cek():
    print("=== Verifikasi URL sitemap ===")
    urls = [
        "https://studiosoft.id/sitemap_index.xml",   # yang BENAR (dipakai sekarang)
        "https://studiost.id/sitemap_index.xml",     # yang SALAH (typo lama)
        "https://studiosoft.id/robots.txt",          # robots.txt itu sendiri
    ]
    for u in urls:
        print(f"  {u:55} -> {cek_url(u)}")


def cmd_tulis(path="robots.txt"):
    with open(path, "w", encoding="utf-8") as f:
        f.write(ROBOTS_BENAR)
    print(f"✔ Konten robots.txt yang benar ditulis ke: {path}")
    print("  Upload file ini ke server (ganti file robots.txt lama) via FTP/File Manager.")


def cmd_deploy(host, user, pwd, path="/public_html/robots.txt"):
    """Upload via FTP (ftplib bawaan Python)."""
    import ftplib
    import io
    print(f"Connecting FTP {host} ...")
    ftp = ftplib.FTP(host)
    ftp.login(user, pwd)
    ftp.cwd("/")
    buf = io.BytesIO(ROBOTS_BENAR.encode("utf-8"))
    ftp.storbinary(f"STOR {path}", buf)
    ftp.quit()
    print(f"✔ robots.txt di-upload ke {host}:{path}")
    print(f"  Verifikasi: {cek_url(SITE + '/robots.txt')}")


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(0)

    cmd = sys.argv[1].lower()

    if cmd == "generate":
        cmd_generate()
    elif cmd == "cek":
        cmd_cek()
    elif cmd == "tulis":
        path = sys.argv[2] if len(sys.argv) > 2 else "robots.txt"
        cmd_tulis(path)
    elif cmd == "deploy":
        args = {}
        for a in sys.argv[2:]:
            if a.startswith("--host="):
                args["host"] = a.split("=", 1)[1]
            elif a.startswith("--user="):
                args["user"] = a.split("=", 1)[1]
            elif a.startswith("--pass="):
                args["pwd"] = a.split("=", 1)[1]
            elif a.startswith("--path="):
                args["path"] = a.split("=", 1)[1]
        if "host" not in args or "user" not in args or "pwd" not in args:
            print("Kurang argumen. Contoh:\n"
                  "  python3 fix_robots_txt.py deploy --host IP --user USER --pass PASS --path /public_html/robots.txt")
            sys.exit(1)
        cmd_deploy(args.get("host"), args.get("user"), args.get("pwd"),
                   args.get("path", "/public_html/robots.txt"))
    else:
        print(f"Perintah tidak dikenal: {cmd}")
        print("Gunakan: generate | cek | tulis | deploy")
        sys.exit(1)


if __name__ == "__main__":
    main()
