from playwright.sync_api import sync_playwright
import os
import cloudconvert
import tempfile

class BaseConvertor:
    def convert(self, *args, **kwargs):
        ...


class CloudConvertor(BaseConvertor):
    def __init__(self, api_key: str):
        super().__init__()
        self.api_key = api_key
        cloudconvert.configure(api_key=self.api_key)

    def convert(self, path, format, output_path):
        job = cloudconvert.Job.create(payload={
            "tasks": {
                "upload-my-file": {
                    "operation": "import/upload"
                },
                "convert-my-file": {
                    "operation": "convert",
                    "input": "upload-my-file",
                    "output_format": "pdf",
                    "engine": "chrome",
                    "page_format": format
                },
                "export-my-file": {
                    "operation": "export/url",
                    "input": "convert-my-file"
                }
            }
        })

        upload_task = [t for t in job['tasks'] if t['name'] == 'upload-my-file'][0]
        
        cloudconvert.Task.upload(file_name=path, task=upload_task)
        finished_job = cloudconvert.Job.wait(job['id'])

        export_task = [t for t in finished_job['tasks'] if t['name'] == 'export-my-file'][0]
        file_info = export_task['result']['files'][0]
        
        cloudconvert.download(url=file_info['url'], filename=output_path)

class BrowserConvertor(BaseConvertor):
    def __init__(self):
        super().__init__()

    def convert(self, html_content, format, output_path):
        with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False, encoding='utf-8') as temp_file:
            temp_file.write(html_content)
            temp_file_path = temp_file.name

        try:
            with sync_playwright() as p:
                with p.chromium.launch() as browser:
                    context = browser.new_context(
                        viewport={'width': 3179, 'height': 4494},
                        device_scale_factor=1
                    )
                    
                    page = context.new_page()
                    
                    # Загружаем файл по абсолютному пути через file://
                    page.goto(f"file://{os.path.abspath(temp_file_path)}", wait_until="networkidle")
                    
                    page.emulate_media(media="print")
                    
                    page.pdf(
                        path=output_path,
                        format=format,
                        print_background=True,  
                        prefer_css_page_size=True 
                    )
        finally:
            # Гарантированно удаляем временный файл после генерации PDF
            if os.path.exists(temp_file_path):
                os.remove(temp_file_path)
                