import os
from github import Github
from datetime import datetime

class GitHubFileDelivery:
    def __init__(self, token, repo_name):
        self.github = Github(token)
        self.repo = self.github.get_repo(repo_name)
    
    def create_release(self, tag_name, release_name, description=""):
        try:
            release = self.repo.create_git_release(
                tag=tag_name,
                name=release_name,
                message=description,
                draft=False,
                prerelease=False
            )
            return release
        except Exception as e:
            print(f"Release oluşturma hatası: {e}")
            try:
                release = self.repo.get_release(tag_name)
                return release
            except:
                raise e
    
    def upload_files_to_release(self, release, file_paths):
        uploaded_urls = []
        
        for file_path in file_paths:
            try:
                asset = release.upload_asset(
                    file_path,
                    label=os.path.basename(file_path),
                    content_type="application/octet-stream"
                )
                uploaded_urls.append({
                    'name': os.path.basename(file_path),
                    'url': asset.browser_download_url,
                    'size': os.path.getsize(file_path)
                })
            except Exception as e:
                print(f"Dosya yükleme hatası ({file_path}): {e}")
        
        return uploaded_urls
    
    def prepare_product_delivery(self, product_id, file_paths):
        tag_name = f"product-{product_id}-{datetime.now().strftime('%Y%m%d%H%M%S')}"
        release_name = f"Product {product_id} - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        description = f"Encrypted files for Product ID: {product_id}"
        
        release = self.create_release(tag_name, release_name, description)
        
        upload_results = self.upload_files_to_release(release, file_paths)
        
        return {
            'tag': tag_name,
            'release_url': release.html_url,
            'files': upload_results
        }
    
    def get_download_links(self, tag_name):
        try:
            release = self.repo.get_release(tag_name)
            assets = release.get_assets()
            
            links = []
            for asset in assets:
                links.append({
                    'name': asset.name,
                    'url': asset.browser_download_url,
                    'size': asset.size
                })
            
            return links
        except Exception as e:
            print(f"Download link alma hatası: {e}")
            return []
