import json
import os
import requests
from datetime import datetime
import subprocess
from dotenv import load_dotenv
import sys
import traceback

# Import the prompt generator
from prompt_generator import generate_prompt

def main():
    # Get the directory of the current script
    script_dir = os.path.dirname(os.path.abspath(__file__))

    # Load environment variables from the .env file in the script's directory
    dotenv_path = os.path.join(script_dir, '.env')
    if not os.path.isfile(dotenv_path):
        print(f"Error: '.env' file not found in {script_dir}.")
        sys.exit(1)
    load_dotenv(dotenv_path)

    # Generate the image
    image_path = generate_image(script_dir)
    if image_path:
        print("Running logo overlay script...")
        if overlay_logo(image_path, script_dir):
            print("Image generation and logo overlay process completed successfully.")
        else:
            print("Image generated successfully, but logo overlay failed.")
    else:
        print("Image generation failed. Logo overlay not attempted.")

def generate_image(script_dir):
    # Path to company_info.json
    company_info_path = os.path.join(script_dir, 'data', 'company_info.json')
    if not os.path.isfile(company_info_path):
        print(f"Error: '{company_info_path}' file not found.")
        return None

    # Generate the prompt
    try:
        prompt = generate_prompt(company_info_path)
    except Exception as e:
        print(f"Error generating prompt: {e}")
        traceback.print_exc()
        return None

    # Prepare the payload
    payload = {
        "inputs": prompt,
        # Include any other options required by the API
    }

    # Hugging Face API setup
    API_URL = os.getenv('API_URL')
    API_KEY = os.getenv('HF_API_KEY')

    if not API_URL:
        print("Error: 'API_URL' not set in .env file.")
        return None
    if not API_KEY:
        print("Error: 'HF_API_KEY' not set in .env file.")
        return None

    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    try:
        print(f"Sending request to API with payload: {payload}")
        response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
        response.raise_for_status()

        # Verify response content is an image
        content_type = response.headers.get('Content-Type', '')
        if 'image' not in content_type:
            print(f"Error: Unexpected content type in response: {content_type}")
            print(f"Response content: {response.text}")
            return None

        # Save the image
        output_dir = os.path.join(script_dir, 'output', 'ads')
        os.makedirs(output_dir, exist_ok=True)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        image_path = os.path.join(output_dir, f'ad_base_{timestamp}.png')

        with open(image_path, 'wb') as f:
            f.write(response.content)

        print(f"Image generated successfully: {image_path}")
        return image_path

    except requests.exceptions.RequestException as e:
        print(f"Error making request to Hugging Face API: {e}")
        return None
    except Exception as e:
        print(f"Unexpected error generating image: {e}")
        traceback.print_exc()
        return None

def overlay_logo(image_path, script_dir):
    try:
        logo_script_path = os.path.join(script_dir, 'scripts', '4_logo.py')
        if not os.path.isfile(logo_script_path):
            print(f"Error: '{logo_script_path}' script not found.")
            return False

        # Run the logo overlay script with the image path as an argument
        result = subprocess.run(['python', logo_script_path, image_path],
                                check=True, capture_output=True, text=True)
        print("Logo overlay completed successfully.")
        print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error running logo overlay script:\n{e.stderr}")
        return False
    except Exception as e:
        print(f"Unexpected error during logo overlay: {e}")
        traceback.print_exc()
        return False

if __name__ == "__main__":
    main()