#!/usr/bin/env python3
"""
VOSHA Framework CLI
Main entry point for the VOSHA framework command-line interface.
"""

import os
import sys
import json
import subprocess
import shutil
import time

# ANSI Colors
HIJAU = "\033[92m"
MERAH = "\033[91m"
KUNING = "\033[93m"
RESET = "\033[0m"

CONFIG_DIR = os.path.expanduser("~/.vosha")
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")

def load_config():
    """Load framework configuration."""
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, 'r') as f:
                return json.load(f)
        except:
            pass
    return {"lang": "id"} # Default to id

def save_config(config):
    """Save framework configuration."""
    os.makedirs(CONFIG_DIR, exist_ok=True)
    with open(CONFIG_FILE, 'w') as f:
        json.dump(config, f)

def status_v(pesan, warna=HIJAU, simbol="V"):
    return f"[{warna}{simbol}{RESET}] {pesan}"

def get_framework_dir():
    """Get the framework directory - works both installed and from source."""
    # If running from installed package
    try:
        import vosha_framework
        return os.path.dirname(vosha_framework.__file__)
    except ImportError:
        # If running from source (backward compatibility)
        return os.path.dirname(os.path.realpath(__file__))

def get_i18n(lang='id'):
    """Load language file."""
    framework_dir = get_framework_dir()
    try:
        with open(os.path.join(framework_dir, 'bahasa', f'{lang}.json'), 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        try:
            with open(os.path.join(framework_dir, 'bahasa', 'id.json'), 'r') as f:
                return json.load(f)
        except:
            return {}

def dapatkan_python():
    """Detect Python executable (venv-aware)."""
    jalur_venv = os.path.join(os.getcwd(), ".venv")
    if os.path.exists(jalur_venv):
        if os.name == 'nt':
            return os.path.join(jalur_venv, "Scripts", "python.exe")
        return os.path.join(jalur_venv, "bin", "python")
    return sys.executable

def cmd_buat(nama_project=None, frontend_count=None):
    """Create a new VOSHA project."""
    framework_dir = get_framework_dir()
    
    if not nama_project:
        nama_project = input("Masukkan nama proyek Anda: ")
    
    if frontend_count is None:
        try:
            fc = input("Berapa total Front-end yang ingin dibuat? (default: 1): ")
            frontend_count = int(fc) if fc else 1
        except ValueError:
            frontend_count = 1

    want_venv = input("Apakah ingin membuat Virtual Environment (venv)? (y/n): ").lower() == 'y'

    print(status_v(f"Membuat proyek '{nama_project}' dengan {frontend_count} frontend..."))
    
    # Get current language for UI localization
    config = load_config()
    lang = config.get("lang", "id")
    
    # UI Text based on language
    UI_TEXT = {
        "id": {
            "title": "Buat karya terbaikmu.",
            "desc": "Coba buat website mu lebih terstruktur dengan vosha framework.",
            "label_title": "Judul Proyek",
            "placeholder_title": "misal: Kampanye Musim Panas 2024",
            "label_desc": "Konten / Deskripsi",
            "placeholder_desc": "Jelaskan secara singkat tentang proyek ini...",
            "btn_create": "Buat Proyek",
            "visual_desc": "Alami sistem desain baru yang disesuaikan untuk kreator modern."
        },
        "en": {
            "title": "Create your next masterpiece.",
            "desc": "Try making your website more structured with vosha framework.",
            "label_title": "Project Title",
            "placeholder_title": "e.g., Summer Campaign 2024",
            "label_desc": "Content / Description",
            "placeholder_desc": "Briefly describe what this project is about...",
            "btn_create": "Create Project",
            "visual_desc": "Experience the new fluid design system tailored for modern creators."
        }
    }[lang]

    # Os makedirs and other basics...
    os.makedirs(os.path.join(nama_project, "Backend"), exist_ok=True)
    os.makedirs(os.path.join(nama_project, "Frontend"), exist_ok=True)
    os.makedirs(os.path.join(nama_project, "vosha_inti"), exist_ok=True)
    
    # Buat venv jika diminta
    if want_venv:
        print(status_v("Membuat venv dan memasang dependensi (ini mungkin memakan waktu)..."))
        subprocess.run([sys.executable, "-m", "venv", os.path.join(nama_project, ".venv")])
        pip_path = os.path.join(nama_project, ".venv", "bin", "pip") if os.name != 'nt' else os.path.join(nama_project, ".venv", "Scripts", "pip")
        subprocess.run([pip_path, "install", "fastapi", "uvicorn", "jinja2", "requests"])

    i18n = get_i18n()

    # --- BACKEND ---
    # data.py
    data_content = f"""{i18n.get('templates', {}).get('backend_comment', '# Backend Logic')}
import sqlite3
import os

DATABASE_PATH = "pusat_data.db"

def inisialisasi_db():
    koneksi = sqlite3.connect(DATABASE_PATH)
    kursor = koneksi.cursor()
    kursor.execute(\"\"\"
        CREATE TABLE IF NOT EXISTS catatan (
            id INTEGER PRIMARY KEY AUTOINCREMENT, 
            kelas INTEGER, 
            judul TEXT, 
            isi TEXT
        )
    \"\"\" )
    koneksi.commit()
    koneksi.close()

def ambil_data(kelas):
    koneksi = sqlite3.connect(DATABASE_PATH)
    kursor = koneksi.cursor()
    kursor.execute("SELECT id, judul, isi FROM catatan WHERE kelas = ?", (kelas,))
    hasil = kursor.fetchall()
    koneksi.close()
    return hasil

def tambah_data(kelas, judul, isi):
    koneksi = sqlite3.connect(DATABASE_PATH)
    kursor = koneksi.cursor()
    kursor.execute("INSERT INTO catatan (kelas, judul, isi) VALUES (?, ?, ?)", (kelas, judul, isi))
    koneksi.commit()
    koneksi.close()

def hapus_data(id_catatan):
    koneksi = sqlite3.connect(DATABASE_PATH)
    kursor = koneksi.cursor()
    kursor.execute("DELETE FROM catatan WHERE id = ?", (id_catatan,))
    koneksi.commit()
    koneksi.close()

inisialisasi_db()
"""
    with open(os.path.join(nama_project, "Backend", "data.py"), "w") as f:
        f.write(data_content)

    # jalur.py
    jalur_content = f"""from fastapi import FastAPI, Request
import sys, os
# Fix ModuleNotFoundError
sys.path.append(os.getcwd())
from Backend import data

app = FastAPI()

@app.get("/")
def beranda():
    return {{"status": "Dapur Aktif"}}

@app.get("/ambil/{{kelas}}")
def ambil(kelas: int):
    items = data.ambil_data(kelas)
    return {{"data": [{{"id": i[0], "judul": i[1], "isi": i[2]}} for i in items]}}

@app.post("/tambah")
async def tambah(req: Request):
    bodi = await req.json()
    data.tambah_data(bodi['kelas'], bodi['judul'], bodi['isi'])
    return {{"pesan": "Berhasil disimpan"}}

@app.delete("/hapus/{{id_catatan}}")
def hapus(id_catatan: int):
    data.hapus_data(id_catatan)
    return {{"pesan": "Berhasil dihapus"}}
"""
    with open(os.path.join(nama_project, "Backend", "jalur.py"), "w") as f:
        f.write(jalur_content)

    # dapur.py
    dapur_content = f"""import uvicorn
import sys, os
# Fix ModuleNotFoundError
sys.path.append(os.getcwd())
from Backend.jalur import app
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=6789, log_level="error")
"""
    with open(os.path.join(nama_project, "Backend", "dapur.py"), "w") as f:
        f.write(dapur_content)

    # --- VOSHA_INTI ---
    vosha_inti_content = """import http.server
import socketserver
import os
from jinja2 import Environment, FileSystemLoader

class TampilanHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        self.jinja_env = kwargs.pop('jinja_env', None)
        self.extra_data = kwargs.pop('extra_data', {})
        super().__init__(*args, **kwargs)

    def do_GET(self):
        if self.path == "/":
            self.render_halaman("index.html")
        else:
            return super().do_GET()

    def render_halaman(self, template_name):
        template = self.jinja_env.get_template(template_name)
        output = template.render(**self.extra_data)
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(output.encode('utf-8'))

    def log_message(self, format, *args):
        # Diam (Silencing separate logs)
        return

def jalankan_tampilan(port, template_dir, static_dir, data):
    env = Environment(loader=FileSystemLoader(template_dir))
    class CustomHandler(TampilanHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, jinja_env=env, extra_data=data, **kwargs)
    os.chdir(static_dir)
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("", port), CustomHandler) as httpd:
        httpd.serve_forever()
"""
    with open(os.path.join(nama_project, "vosha_inti", "server.py"), "w") as f:
        f.write(vosha_inti_content)
    with open(os.path.join(nama_project, "vosha_inti", "__init__.py"), "w") as f:
        f.write("from .server import jalankan_tampilan")

    # --- FRONTEND TEMPLATES ---
    for i in range(1, frontend_count + 1):
        port = 9870 + i
        tampilan_dir = os.path.join(nama_project, "Frontend", f"tampilan_{i}")
        os.makedirs(tampilan_dir, exist_ok=True)
        os.makedirs(os.path.join(tampilan_dir, "gaya"), exist_ok=True)
        os.makedirs(os.path.join(tampilan_dir, "tampilan"), exist_ok=True)
        
        # Copy logo to each frontend
        shutil.copy(os.path.join(framework_dir, "logo.png"), os.path.join(tampilan_dir, "gaya", "logo.png"))
        
        with open(os.path.join(tampilan_dir, "gaya", "utama.css"), "w") as f:
            f.write("""
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

:root {
    --utama: #004aad;
    --aksen: #0061ff;
    --latar: #eef2ff;
    --kartu: rgba(255, 255, 255, 0.7);
    --teks: #101622;
    --teks-muda: #636e72;
    --bayangan: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
    --glass-border: 1px solid rgba(255, 255, 255, 0.6);
}

body { 
    font-family: 'Poppins', sans-serif; 
    background: var(--latar); 
    color: var(--teks); 
    margin: 0; 
    line-height: 1.6;
    min-height: 100vh;
    overflow-x: hidden;
    position: relative;
}

/* Background orbs */
.body-glow {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
    overflow: hidden;
    pointer-events: none;
}

.orb-1 {
    position: absolute;
    top: -15%;
    left: -10%;
    width: 60vw;
    height: 60vw;
    background: radial-gradient(circle, rgba(0, 74, 173, 0.2) 0%, rgba(255, 255, 255, 0) 70%);
    border-radius: 50%;
    filter: blur(80px);
}

.orb-2 {
    position: absolute;
    bottom: -15%;
    right: -10%;
    width: 50vw;
    height: 50vw;
    background: radial-gradient(circle, rgba(0, 74, 173, 0.15) 0%, rgba(255, 255, 255, 0) 70%);
    border-radius: 50%;
    filter: blur(100px);
}

.navbar { 
    background: rgba(255, 255, 255, 0.7); 
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    border-bottom: var(--glass-border);
    padding: 0 50px; 
    height: 80px;
    display: flex; 
    justify-content: space-between;
    align-items: center;
    position: sticky;
    top: 0;
    z-index: 100;
}

.brand { 
    display: flex;
    align-items: center;
    gap: 12px;
    font-weight: 700; 
    color: var(--teks); 
    font-size: 1.5rem;
    letter-spacing: -0.5px;
}

.brand img {
    height: 40px;
    width: auto;
}

.nav-links a { 
    margin-left: 20px; 
    text-decoration: none; 
    color: var(--teks-muda); 
    font-weight: 500;
    font-size: 0.95rem;
    transition: 0.3s;
}

.nav-links a:hover { color: var(--utama); }

.wadah { 
    max-width: 1200px;
    margin: 60px auto;
    padding: 0 40px;
}

.grid-utama {
    display: grid;
    grid-template-columns: 1.1fr 0.9fr;
    gap: 60px;
    align-items: center;
}

@media (max-width: 968px) {
    .grid-utama { grid-template-columns: 1fr; gap: 40px; }
}

.glass-card { 
    background: var(--kartu); 
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    padding: 50px; 
    border-radius: 32px; 
    box-shadow: var(--bayangan); 
    border: var(--glass-border);
    transition: transform 0.3s ease;
}

.visual-box {
    position: relative;
    border-radius: 24px;
    overflow: hidden;
    height: 500px;
    box-shadow: var(--bayangan);
    border: var(--glass-border);
}

.visual-box img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.visual-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 30px;
    background: linear-gradient(to top, rgba(0,0,0,0.6), transparent);
    color: white;
}

h1 { 
    font-weight: 700; 
    margin-top: 0; 
    font-size: 2.8rem;
    line-height: 1.2;
    margin-bottom: 20px;
    color: var(--teks);
}

p.deskripsi {
    color: var(--teks-muda);
    font-size: 1.1rem;
    margin-bottom: 40px;
}

label {
    display: block;
    font-size: 0.9rem;
    font-weight: 600;
    margin-bottom: 10px;
    color: var(--teks);
}

input, textarea { 
    width: 100%; 
    padding: 16px 20px; 
    margin-bottom: 25px; 
    background: rgba(255,255,255,0.6);
    border: 1px solid rgba(0,0,0,0.08); 
    border-radius: 16px; 
    font-family: inherit;
    font-size: 1rem;
    box-sizing: border-box;
    transition: all 0.3s;
}

input:focus, textarea:focus {
    border-color: var(--utama);
    background: white;
    outline: none;
    box-shadow: 0 0 0 4px rgba(0, 74, 173, 0.15);
}

button.btn-utama { 
    background: var(--utama); 
    color: white; 
    border: none; 
    padding: 18px 30px; 
    border-radius: 16px; 
    font-weight: 600;
    font-size: 1.1rem;
    cursor: pointer; 
    transition: 0.3s;
    width: 100%;
    box-shadow: 0 12px 24px rgba(0, 74, 173, 0.25);
}

button.btn-utama:hover { 
    transform: translateY(-3px);
    box-shadow: 0 18px 30px rgba(0, 74, 173, 0.35);
    background: #003a8c;
}

.daftar-item {
    margin-top: 50px;
}

.kartu-item {
    background: rgba(255,255,255,0.8);
    padding: 25px;
    border-radius: 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 15px rgba(0,0,0,0.03);
    border: 1px solid rgba(255,255,255,0.8);
}

.btn-hapus {
    background: #fff0f0;
    color: #ff4757;
    border: none;
    padding: 10px 20px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    transition: 0.2s;
}

.btn-hapus:hover {
    background: #ff4757;
    color: white;
}
""")

        nav_links = "".join([f'<a href="http://localhost:{9870+j}/">Tampilan {j}</a>' for j in range(1, frontend_count + 1)])
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Tampilan {i}</title>
    <link rel="stylesheet" href="/gaya/utama.css">
</head>
<body>
    <div class="body-glow">
        <div class="orb-1"></div>
        <div class="orb-2"></div>
    </div>
    <div class="navbar">
        <div class="brand">
            <img src="/gaya/logo.png" alt="Logo">
            <span>Vosha</span>
        </div>
        <div class="nav-links">{nav_links}</div>
    </div>
    <div class="wadah">
        <div class="grid-utama">
            <div class="glass-card">
                <h1>{UI_TEXT['title']}</h1>
                <p class="deskripsi">{UI_TEXT['desc']}</p>
                
                <label>{UI_TEXT['label_title']}</label>
                <input type="text" id="judul" placeholder="{UI_TEXT['placeholder_title']}">
                
                <label>{UI_TEXT['label_desc']}</label>
                <textarea id="isi" placeholder="{UI_TEXT['placeholder_desc']}" rows="4"></textarea>
                
                <button class="btn-utama" onclick="simpan()">{UI_TEXT['btn_create']}</button>
                
                <div id="daftar" class="daftar-item"></div>
            </div>
            
            <div class="visual-box">
                <img src="/gaya/logo.png" alt="Visual Illustration">
                <div class="visual-overlay">
                    <h3 style="margin:0; font-size:1.5rem">Visual Inspiration</h3>
                    <p style="margin:5px 0 0; opacity:0.8; font-size:0.9rem">{UI_TEXT['visual_desc']}</p>
                </div>
            </div>
        </div>
    </div>
    <script>
        const API = 'http://localhost:6789';
        const KELAS = {i};
        async function muat() {{
            const r = await fetch(`${{API}}/ambil/${{KELAS}}`);
            const j = await r.json();
            document.getElementById('daftar').innerHTML = j.data.map(item => `
                <div class="kartu-item">
                    <div>
                        <strong style="display:block; font-size:1.1rem">${{item.judul}}</strong>
                        <small style="color:var(--teks-muda)">${{item.isi}}</small>
                    </div>
                    <button class="btn-hapus" onclick="hapus(${{item.id}})">Hapus</button>
                </div>
            `).join('');
        }}
        async function simpan() {{
            await fetch(`${{API}}/tambah`, {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{ kelas: KELAS, judul: document.getElementById('judul').value, isi: document.getElementById('isi').value }})
            }});
            muat();
        }}
        async function hapus(id) {{
            await fetch(`${{API}}/hapus/${{id}}`, {{ method: 'DELETE' }});
            muat();
        }}
        muat();
    </script>
</body>
</html>
"""
        with open(os.path.join(tampilan_dir, "tampilan", "index.html"), "w") as f:
            f.write(html_content)

        tampilan_logic = f"""{i18n.get('templates', {}).get('frontend_comment', '# UI Logic')}
import sys, os
sys.path.append(os.getcwd())
from vosha_inti import jalankan_tampilan
if __name__ == "__main__":
    jalankan_tampilan(port={port}, template_dir=os.path.join(os.path.dirname(__file__), "tampilan"), static_dir=os.path.dirname(__file__), data={{"idx": {i}}})
"""
        with open(os.path.join(tampilan_dir, "tampilan.py"), "w") as f:
            f.write(tampilan_logic)

    # jalankan.py
    orchestrator_content = f"""import subprocess, sys, time, os

HIJAU = "\\033[92m"
MERAH = "\\033[91m"
KUNING = "\\033[93m"
RESET = "\\033[0m"

def status_v(pesan, warna=HIJAU, simbol="V"):
    return f"[{{warna}}{{simbol}}{{RESET}}] {{pesan}}"

def dapatkan_python():
    v = os.path.join(os.path.dirname(__file__), ".venv")
    if os.path.exists(v):
        return os.path.join(v, "Scripts", "python.exe") if os.name == 'nt' else os.path.join(v, "bin", "python")
    return sys.executable

def jalankan():
    py = dapatkan_python()
    nama_proyek = os.path.basename(os.path.dirname(os.path.realpath(__file__)))
    print(f"\\n{{status_v(f'Menjalankan semua Host folder {{nama_proyek}} Di Framework Vosha')}}\\n")
    try:
        import fastapi, uvicorn, jinja2
    except ImportError:
        print(status_v("Library tidak ditemukan.", simbol="v", warna=KUNING))
        print(f"👉 Instal dependensi: pip install fastapi uvicorn jinja2 requests\\n")
        return

    ps = []
    try:
        # Jalankan Dapur tanpa log berisik di awal
        ps.append(subprocess.Popen([py, "Backend/dapur.py"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
        time.sleep(1)
        
        # Jalankan semua Tampilan tanpa log berisik di awal
        for i in range(1, {frontend_count + 1}):
            ps.append(subprocess.Popen([py, f"Frontend/tampilan_{{i}}/tampilan.py"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
        
        print(f"🔹 {{status_v('Dapur Aktif di', simbol='V')}}     : http://localhost:6789")
        for i in range(1, {frontend_count + 1}):
            print(f"🔹 {{status_v(f'Tampilan {{i}} Aktif di', simbol='V')}} : http://localhost:{{9870+i}}/")
        
        print(f"\\n{{status_v('Tekan Ctrl+C untuk berhenti.', simbol='V')}}\\n")
        
        while True: time.sleep(1)
    except KeyboardInterrupt:
        for p in ps: p.terminate()
        print(f"\\n{{status_v('Selesai.', simbol='V')}}\\n")
        sys.exit(0)

if __name__ == "__main__":
    try:
        jalankan()
    except KeyboardInterrupt:
        sys.exit(0)
"""
    with open(os.path.join(nama_project, "run.py"), "w") as f:
        f.write(orchestrator_content)

    print(status_v(f"Selesai! Proyek '{nama_project}' siap."))

def cmd_jalankan(targets=None):
    """Run VOSHA services."""
    if not os.path.exists("Backend"):
        print(status_v("Gagal: Harus di dalam folder proyek.", simbol="v", warna=MERAH))
        return
    
    py = dapatkan_python()
    if not targets:
        targets = ["semua"]
    
    nama_proyek = os.path.basename(os.getcwd())
    
    if "semua" in targets:
        try:
            # Panggil run.py yang sudah bersih
            subprocess.run([py, "run.py"])
        except KeyboardInterrupt:
            pass
        return

    print(f"\n{status_v(f'Menjalankan service {', '.join(targets)} di {nama_proyek}')}\n")
    ps = []
    if "dapur" in [t.lower() for t in targets]:
        p = subprocess.Popen([py, "Backend/dapur.py"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        ps.append(p)
        print(f"🔹 {status_v('Dapur Aktif di', simbol='V')}     : http://localhost:6789")

    for t in targets:
        if t.lower().startswith("tampilan"):
            idx = t.lower().replace("tampilan", "")
            path = f"Frontend/tampilan_{idx}/tampilan.py"
            if os.path.exists(path):
                p = subprocess.Popen([py, path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                ps.append(p)
                print(f"🔹 {status_v(f'Tampilan {idx} Aktif di', simbol='V')} : http://localhost:{9870+int(idx)}/")
    
    if ps:
        print(f"\n{status_v('Tekan Ctrl+C untuk berhenti.', simbol='V')}\n")
        try:
            while True: time.sleep(1)
        except KeyboardInterrupt:
            for p in ps: p.terminate()
            print(f"\n{status_v('Selesai.', simbol='V')}\n")

def cmd_info():
    """Display framework information."""
    framework_dir = get_framework_dir()
    
    print(f"\n === {status_v('INFORMASI VOSHA FRAMEWORK')} === ")
    print(f"🔹 Versi         : 1.3.0 (Pip Edition)")
    print(f"🔹 Folder Inti   : {framework_dir}")
    
    # Cek status instalasi
    try:
        import vosha_framework
        status_cli = status_v("Terinstal via pip")
    except ImportError:
        status_cli = status_v("Running dari source code", warna=KUNING, simbol="v")
    print(f"🔹 Status        : {status_cli}")
    
    # Cek Library
    deps = ["fastapi", "uvicorn", "jinja2", "requests"]
    missing = []
    for d in deps:
        try: __import__(d)
        except ImportError: missing.append(d)
    
    if not missing:
        print(f"🔹 Library       : {status_v('Lengkap (Semua dependensi aktif)')}")
    else:
        print(f"🔹 Library       : {status_v(f'Kurang: {', '.join(missing)}', warna=KUNING, simbol='v')}")
    
    print(f"\n{status_v('Gunakan vosha --help untuk bantuan perintah.', simbol='V')}\n")


def cmd_copot():
    """Uninstall VOSHA Framework."""
    print(f"\n === {status_v('MENGHAPUS VOSHA FRAMEWORK')} === ")
    
    # Check if confirming
    confirm = input("Apakah Anda yakin ingin menghapus VOSHA Framework? (y/n): ")
    if confirm.lower() != 'y':
        print(status_v("Dibatalkan.", warna=KUNING, simbol="!"))
        return

    # 1. Hapus symlink legacy jika ada
    files_to_remove = [
        os.path.expanduser("~/.local/bin/vosha"),
        "/usr/local/bin/vosha"
    ]
    
    for f in files_to_remove:
        # Check if file exists or is a broken symlink
        if os.path.exists(f) or os.path.islink(f):
            try:
                os.remove(f)
                print(status_v(f"Menghapus shortcut: {f}"))
            except Exception as e:
                # Permission denied likely
                print(status_v(f"Gagal menghapus {f}: {e}", warna=KUNING, simbol="!"))

    # 2. Uninstall package via pip
    print(status_v("Menjalankan pip uninstall..."))
    try:
        # Gunakan subprocess untuk memanggil pip
        subprocess.run([sys.executable, "-m", "pip", "uninstall", "vosha", "-y", "--break-system-packages"], check=True)
        print(f"\n{status_v('VOSHA Framework berhasil dihapus.', simbol='V')}\n")
    except subprocess.CalledProcessError:
        print(status_v("Gagal menghapus paket via pip.", warna=MERAH, simbol="X"))
        print("Silakan coba manual: pip uninstall vosha")

def cmd_pasang():
    """Install VOSHA Framework."""
    print(f"\n === {status_v('MEMASANG VOSHA FRAMEWORK')} === ")
    
    source_dir = os.path.dirname(get_framework_dir())
    if not os.path.exists(os.path.join(source_dir, "setup.py")):
        print(status_v("Gagal: setup.py tidak ditemukan. Pastikan Anda menjalankan perintah ini dari folder source framework.", warna=MERAH, simbol="X"))
        return

    print(status_v("Mulai proses instalasi..."))
    
    # Deteksi OS dan tentukan flag
    cmd = [sys.executable, "-m", "pip", "install", ".", "--upgrade"]
    if os.name != 'nt': # Linux/Mac
        cmd.append("--break-system-packages")
    
    try:
        subprocess.run(cmd, cwd=source_dir, check=True)
        print(f"\n{status_v('VOSHA Framework berhasil dipasang!', simbol='V')}")
        print(f"{status_v('Sekarang Anda dapat menggunakan perintah `vosha` di terminal mana saja.')}\n")
    except subprocess.CalledProcessError:
        print(f"\n{status_v('Gagal memasang paket.', warna=MERAH, simbol='X')}")
        print("Coba jalankan manual: pip install . --break-system-packages")

def cmd_bahasa(lang=None):
    """Set framework language."""
    if lang not in ["id", "en"]:
        if lang:
            print(status_v(f"Bahasa '{lang}' tidak didukung. Gunakan 'id' atau 'en'.", warna=MERAH, simbol="X"))
        print("\nBahasa saat ini: " + load_config().get("lang", "id"))
        print("Gunakan: vosha bahasa id | en\n")
        return

    config = load_config()
    config["lang"] = lang
    save_config(config)
    
    if lang == "id":
        print(status_v("Bahasa berhasil diubah ke Indonesia."))
        print(status_v("Sekarang kamu bisa pakai: buat, jalankan, pasang, copot"))
    else:
        print(status_v("Language successfully changed to English."))
        print(status_v("Now you can use: create, run, install, uninstall"))

def main():
    """Main CLI entry point."""
    import argparse
    
    config = load_config()
    lang = config.get("lang", "id")
    
    # Map command names based on language
    # [DisplayName, InternalCommand, HelpText]
    CMD_MAP = {
        "id": {
            "info": ["info", "info", "Tampilkan informasi framework"],
            "buat": ["buat", "buat", "Buat proyek baru"],
            "jalankan": ["jalankan", "jalankan", "Jalankan layanan proyek"],
            "pasang": ["pasang", "pasang", "Pasang VOSHA Framework"],
            "copot": ["copot", "copot", "Hapus VOSHA Framework"],
            "bahasa": ["bahasa", "bahasa", "Ubah bahasa CLI (id/en)"]
        },
        "en": {
            "info": ["info", "info", "Show framework information"],
            "buat": ["create", "buat", "Create a new project"],
            "jalankan": ["run", "jalankan", "Run project services"],
            "pasang": ["install", "pasang", "Install VOSHA Framework"],
            "copot": ["uninstall", "copot", "Uninstall VOSHA Framework"],
            "bahasa": ["language", "bahasa", "Change CLI language (id/en)"]
        }
    }
    
    curr_cmds = CMD_MAP[lang]
    
    # Reverse map for execution
    ALIASES = {v[0]: k for k, v in curr_cmds.items()}
    # Add English aliases even in Indo mode for flexibility if desired, 
    # but the user asked for strict "if id then id, if en then en".
    # However, 'info' and some others are same.
    
    parser = argparse.ArgumentParser(
        description="VOSHA Framework - Build web applications with ease",
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    subs = parser.add_subparsers(dest="display_command", help="Available commands")
    
    def add_sub(key):
        display, internal, htext = curr_cmds[key]
        return subs.add_parser(display, help=htext)

    # Info
    add_sub("info")
    
    # Buat / Create
    p_buat = add_sub("buat")
    p_buat.add_argument("nama", nargs="?", help="Project name")
    p_buat.add_argument("frontend_count", nargs="?", type=int, help="Number of frontends")
    
    # Jalankan / Run
    p_jalan = add_sub("jalankan")
    p_jalan.add_argument("target", nargs="*", help="Services to run")
    
    # Pasang / Install
    p_pasang = add_sub("pasang")
    # Add alias for compatibility
    if lang == "id": subs.add_parser("install", help="Alias for pasang")
    else: subs.add_parser("pasang", help="Alias for install")

    # Copot / Uninstall
    p_copot = add_sub("copot")
    if lang == "id": subs.add_parser("uninstall", help="Alias for copot")
    else: subs.add_parser("copot", help="Alias for uninstall")

    # Bahasa / Language
    p_lang = add_sub("bahasa")
    p_lang.add_argument("pilihan", nargs="?", choices=["id", "en"], help="Language choice")
    
    args = parser.parse_args()
    
    # Resolve internal command
    display_cmd = args.display_command
    if not display_cmd:
        parser.print_help()
        return

    # Normalize command name
    internal_cmd = ALIASES.get(display_cmd)
    if not internal_cmd:
        # Check aliases
        if display_cmd in ["install", "pasang"]: internal_cmd = "pasang"
        elif display_cmd in ["uninstall", "copot"]: internal_cmd = "copot"
    
    if internal_cmd == "info":
        cmd_info()
    elif internal_cmd == "buat":
        cmd_buat(args.nama, args.frontend_count)
    elif internal_cmd == "jalankan":
        cmd_jalankan(args.target if args.target else None)
    elif internal_cmd == "pasang":
        cmd_pasang()
    elif internal_cmd == "copot":
        cmd_copot()
    elif internal_cmd == "bahasa":
        cmd_bahasa(args.pilihan)
    else:
        parser.print_help()

def old_main_block_to_replace():
    # This is just to mark the end of the previous main() which I replaced above.
    pass

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        sys.exit(0)
