#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Template Automation Script
Copy this file and implement the abstract methods to create a new automation script.

Usage:
  python template_automation.py <csv_file> <output_dir> <job_id> [api_base_url] [user_id] [credits_used]
"""

import sys
import os

# Add parent directory to path to import shared utilities
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from automation_scripts.shared.base_automation import BaseAutomation
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class TemplateAutomation(BaseAutomation):
    """Template automation class. Implement login() and process_row() methods."""
    
    def __init__(self, csv_file, output_dir, job_id, api_base_url=None, user_id=None, credits_used=0.0):
        """Initialize template automation.
        
        Args:
            csv_file: Path to input CSV file
            output_dir: Base output directory
            job_id: Unique job identifier
            api_base_url: Optional API base URL
            user_id: Optional user ID
            credits_used: Credits used for this job
        """
        super().__init__(
            service_name="template_service",  # Change this to your service name
            csv_file=csv_file,
            output_dir=output_dir,
            job_id=job_id,
            api_base_url=api_base_url,
            user_id=user_id,
            credits_used=credits_used
        )
        
        # Add service-specific configuration
        self.login_url = self.service_config.get('login_url', 'https://example.com/login')
        self.headless_after_login = self.service_config.get('headless_after_login', True)
        self.login_headless = self.service_config.get('login_headless', False)
    
    def login(self, driver) -> bool:
        """Perform login. Must be implemented.
        
        Args:
            driver: WebDriver instance
            
        Returns:
            True if login successful, False otherwise
        """
        try:
            self.logger.info("Navigating to login page...")
            driver.get(self.login_url)
            self.wait_for_page_load()
            
            # TODO: Implement login logic
            # Example:
            # username_field = self.wait_for_element(By.ID, "username")
            # username_field.send_keys("your_username")
            # password_field = self.wait_for_element(By.ID, "password")
            # password_field.send_keys("your_password")
            # login_button = self.wait_for_clickable(By.ID, "login_button")
            # login_button.click()
            # self.wait_for_page_load()
            
            # Verify login success
            # if "dashboard" in driver.current_url.lower():
            #     self.logger.info("✓ Login successful")
            #     return True
            # else:
            #     self.logger.error("✗ Login failed - not redirected to dashboard")
            #     return False
            
            self.logger.info("✓ Login successful")
            return True
            
        except Exception as e:
            self.logger.error(f"✗ Login failed: {e}")
            return False
    
    def process_row(self, driver, row, index, total) -> bool:
        """Process a single CSV row. Must be implemented.
        
        Args:
            driver: WebDriver instance
            row: CSV row data (dictionary)
            index: Row index (1-based)
            total: Total number of rows
            
        Returns:
            True if processing successful, False otherwise
        """
        try:
            self.logger.info(f"Processing row {index}/{total}")
            
            # TODO: Implement row processing logic
            # Example:
            # field1 = row.get('Field1', '').strip()
            # field2 = row.get('Field2', '').strip()
            # 
            # if not field1 or not field2:
            #     self.logger.warning(f"Row {index}: Missing required fields")
            #     return False
            # 
            # # Navigate to processing page
            # driver.get("https://example.com/process")
            # self.wait_for_page_load()
            # 
            # # Fill form fields
            # input1 = self.wait_for_element(By.ID, "input1")
            # input1.clear()
            # input1.send_keys(field1)
            # 
            # input2 = self.wait_for_element(By.ID, "input2")
            # input2.clear()
            # input2.send_keys(field2)
            # 
            # # Submit form
            # submit_button = self.wait_for_clickable(By.ID, "submit")
            # submit_button.click()
            # self.wait_for_page_load()
            # 
            # # Verify success
            # success_indicator = self.wait_for_element(By.CLASS_NAME, "success")
            # if success_indicator:
            #     self.logger.info(f"✓ Row {index} processed successfully")
            #     return True
            # else:
            #     self.logger.warning(f"✗ Row {index} processing failed - no success indicator")
            #     return False
            
            self.logger.info(f"✓ Row {index} processed successfully")
            return True
            
        except Exception as e:
            self.logger.error(f"✗ Error processing row {index}: {e}")
            return False


def main():
    """Main entry point."""
    if len(sys.argv) < 4:
        print("❌ Usage: python template_automation.py <csv_file> <output_dir> <job_id> [api_base_url] [user_id] [credits_used]")
        sys.exit(1)
    
    csv_file = sys.argv[1]
    output_dir = sys.argv[2]
    job_id = sys.argv[3]
    api_base_url = sys.argv[4] if len(sys.argv) > 4 else None
    user_id = sys.argv[5] if len(sys.argv) > 5 else None
    credits_used = float(sys.argv[6]) if len(sys.argv) > 6 and sys.argv[6] else 0.0
    
    # Create and run automation
    automation = TemplateAutomation(
        csv_file=csv_file,
        output_dir=output_dir,
        job_id=job_id,
        api_base_url=api_base_url,
        user_id=user_id,
        credits_used=credits_used
    )
    
    success = automation.run()
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()

