import os
import sys
import glob
import time
import hashlib
import mimetypes
import configparser
import getpass
import datetime
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
from uuid import uuid4

PYPI_UPLOAD_URL = "https://upload.pypi.org/legacy/"
CONFIG_PATH = os.path.expanduser("~/.pypirc")

class Colors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'

def log(msg, type="info"):
    if type == "info":
        print(f"{Colors.OKBLUE}[Fiber]{Colors.ENDC} {msg}")
    elif type == "success":
        print(f"{Colors.OKGREEN}[Fiber]{Colors.ENDC} {msg}")
    elif type == "warn":
        print(f"{Colors.WARNING}[Warn]{Colors.ENDC} {msg}")
    elif type == "error":
        print(f"{Colors.FAIL}[Error]{Colors.ENDC} {msg}")

class ProjectValidator:
    @staticmethod
    def validate():
        """Mengecek kelengkapan file proyek (README & LICENSE)"""
        if not (os.path.exists("setup.py") or os.path.exists("pyproject.toml")):
            return

        ProjectValidator._check_readme()
        ProjectValidator._check_license()

    @staticmethod
    def _check_readme():
        filename = "README.md"
        if not os.path.exists(filename) or os.stat(filename).st_size == 0:
            log(f"{filename} kosong atau tidak ditemukan. Membuat default...", "warn")
            
            project_name = os.path.basename(os.getcwd()).capitalize()
            content = f"""# {project_name}

This project was uploaded using **Fiber**.

## Author
**Eternals**

---
*Generated automatically by Fiber.*
"""
            with open(filename, "w") as f:
                f.write(content)
            log(f"{filename} berhasil dibuat.", "success")

    @staticmethod
    def _check_license():
        license_files = glob.glob("LICENSE*") + glob.glob("COPYING*")
        if license_files:
            return

        log("File LICENSE tidak ditemukan!", "warn")
        print(f"{Colors.BOLD}Pilih Lisensi untuk proyek ini:{Colors.ENDC}")
        print("1. MIT License (Recommended)")
        print("2. Apache License 2.0")
        print("3. GNU GPLv3")
        print("4. The Unlicense (Public Domain)")
        print("5. Skip (Jangan buat)")
        
        try:
            choice = input(f"{Colors.OKCYAN}Pilihan [1-5]: {Colors.ENDC}")
        except KeyboardInterrupt:
            print()
            return

        year = datetime.datetime.now().year
        holder = "Eternals"
        
        content = ""
        if choice == '1':
            content = f"""MIT License

Copyright (c) {year} {holder}

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
        elif choice == '2':
            content = f"""Apache License 2.0
Copyright {year} {holder}

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
        elif choice == '3':
            content = f"Copyright (C) {year} {holder}\n\nThis program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.\nThis is free software, and you are welcome to redistribute it\nunder certain conditions; type 'show c' for details.\n\n(Full GPLv3 text is too long for generated stub. Please replace with full text.)"
        elif choice == '4':
            content = f"This is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans."
        
        if content:
            with open("LICENSE", "w") as f:
                f.write(content)
            log(f"LICENSE ({holder}) berhasil dibuat.", "success")


class AuthManager:
    def get_token(self):
        config = configparser.ConfigParser()
        if os.path.exists(CONFIG_PATH):
            config.read(CONFIG_PATH)
            if "pypi" in config and "password" in config["pypi"]:
                return config["pypi"]["password"]
        
        print(f"\n{Colors.BOLD}Konfigurasi Fiber (Pertama Kali){Colors.ENDC}")
        log("Token PyPI tidak ditemukan di ~/.pypirc", "warn")
        print("Silakan masukkan API Token PyPI Anda (dimulai dengan 'pypi-')")
        
        token = getpass.getpass(f"{Colors.OKCYAN}Token: {Colors.ENDC}").strip()
        
        if not token:
            log("Token tidak boleh kosong.", "error")
            sys.exit(1)

        save = input(f"Simpan token ini untuk upload selanjutnya? (y/n): ").lower()
        if save == 'y':
            self.save_token(token)
        return token

    def save_token(self, token):
        config = configparser.ConfigParser()
        if os.path.exists(CONFIG_PATH):
            config.read(CONFIG_PATH)
        
        if "distutils" not in config:
            config["distutils"] = {"index-servers": "pypi"}
        
        if "pypi" not in config:
            config["pypi"] = {}
            
        config["pypi"]["username"] = "__token__"
        config["pypi"]["password"] = token
        
        with open(CONFIG_PATH, 'w') as configfile:
            config.write(configfile)
        log(f"Token disimpan di {CONFIG_PATH}", "success")

class PackageFile:
    def __init__(self, filepath):
        self.filepath = filepath
        self.filename = os.path.basename(filepath)
        self.content = None
        
        if self.filename.endswith('.whl'):
            self.filetype = 'bdist_wheel'
            parts = self.filename.split('-')
            self.name = parts[0]
            self.version = parts[1]
            
        elif self.filename.endswith('.tar.gz'):
            self.filetype = 'sdist'
            clean_name = self.filename[:-7]
            if '-' in clean_name:
                parts = clean_name.rsplit('-', 1)
                self.name = parts[0]
                self.version = parts[1]
            else:
                raise ValueError(f"Format nama file sdist tidak valid: {self.filename}")
            
        else:
            self.filetype = 'unknown'
            self.name = None
            self.version = None

    def get_hash(self):
        sha256 = hashlib.sha256()
        with open(self.filepath, 'rb') as f:
            while True:
                data = f.read(65536)
                if not data: break
                sha256.update(data)
        return sha256.hexdigest()

class Uploader:
    def __init__(self, token):
        self.token = token
        self.boundary = uuid4().hex

    def _build_multipart_body(self, fields, file_obj):
        body = []
        for key, value in fields.items():
            body.append(f'--{self.boundary}'.encode())
            body.append(f'Content-Disposition: form-data; name="{key}"'.encode())
            body.append(b'')
            body.append(str(value).encode('utf-8'))

        mime_type = mimetypes.guess_type(file_obj.filename)[0] or 'application/octet-stream'
        body.append(f'--{self.boundary}'.encode())
        body.append(f'Content-Disposition: form-data; name="content"; filename="{file_obj.filename}"'.encode())
        body.append(f'Content-Type: {mime_type}'.encode())
        body.append(b'')
        
        with open(file_obj.filepath, 'rb') as f:
            body.append(f.read())

        body.append(f'--{self.boundary}--'.encode())
        body.append(b'')
        return b'\r\n'.join(body)

    def upload(self, package):
        log(f"Memproses: {Colors.BOLD}{package.filename}{Colors.ENDC}")
        sha256 = package.get_hash()
        
        fields = {
            ":action": "file_upload",
            "protocol_version": "1",
            "metadata_version": "2.1",
            "name": package.name,
            "version": package.version,
            "filetype": package.filetype,
            "pyversion": "source" if package.filetype == 'sdist' else "py3",
            "sha256_digest": sha256,
        }

        data = self._build_multipart_body(fields, package)
        req = Request(PYPI_UPLOAD_URL, data=data, method="POST")
        req.add_header("Content-Type", f"multipart/form-data; boundary={self.boundary}")
        req.add_header("Authorization", f"Bearer {self.token}")
        req.add_header("User-Agent", "Fiber/1.1 (Termux-Optimized)")

        try:
            log(f"Mengunggah {package.filename} ({len(data)/1024:.1f} KB)...", "info")
            start_time = time.time()
            with urlopen(req) as response:
                if response.status == 200:
                    elapsed = time.time() - start_time
                    log(f"Berhasil! ({elapsed:.2f}s)", "success")
                    log(f"Link: https://pypi.org/project/{package.name}/{package.version}/")
        except HTTPError as e:
            error_body = e.read().decode()
            log(f"Gagal mengunggah: HTTP {e.code}", "error")
            print(f"{Colors.FAIL}{error_body}{Colors.ENDC}")
        except URLError as e:
            log(f"Koneksi error: {e.reason}", "error")

def main():
    print(f"""
{Colors.OKCYAN}   ___{Colors.ENDC}
{Colors.OKCYAN}  / _/ib{Colors.ENDC}{Colors.BOLD}er{Colors.ENDC}
{Colors.OKCYAN} / _/   {Colors.ENDC}  Lightweight PyPI Uploader
{Colors.OKCYAN}/_/     {Colors.ENDC}  v1.1.0
    """)
    
    if len(sys.argv) < 2:
        print("Usage: fiber dist/*")
        sys.exit(1)
    
    ProjectValidator.validate()

    files = []
    for arg in sys.argv[1:]:
        files.extend(glob.glob(arg))
    
    if not files:
        log("Tidak ada file yang ditemukan untuk diupload.", "error")
        sys.exit(1)

    auth = AuthManager()
    token = auth.get_token()
    uploader = Uploader(token)
    
    print("-" * 40)
    for f in files:
        if not os.path.isfile(f): continue
        try:
            pkg = PackageFile(f)
            if pkg.filetype == 'unknown':
                log(f"Skipping {f} (unknown type)", "warn")
                continue
            uploader.upload(pkg)
        except Exception as e:
            log(f"Error pada {f}: {e}", "error")
    print("-" * 40)

