#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SAGA WEB - VALIDARE MASIVA FACTURI EMISE (IESIRI)
Validate issued invoices in SAGA - PASUL 2
- PASUL 2: Validate all invoices in the current period (Operatii - Iesiri)

NOTA: Pentru facturile emise (Iesiri) nu apar popup-uri suplimentare la validare.
"""

import time
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import configparser

# Colors
class Colors:
    GREEN = '\033[92m'
    RED = '\033[91m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    RESET = '\033[0m'
    BOLD = '\033[1m'

def print_colored(text, color):
    print(f"{color}{text}{Colors.RESET}")

# ============================================================================
# MAIN
# ============================================================================

print("\n" + "="*70)
print_colored("SAGA WEB - VALIDARE MASIVA FACTURI EMISE (IESIRI)", Colors.BOLD)
print_colored("PASUL 2", Colors.BOLD)
print("="*70 + "\n")

try:
    # 1. Conectare la Chrome existent (lansat de RUN_LOGIN.bat)
    print_colored("1. Conectare la Chrome existent (port 9222)...", Colors.BLUE)
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    try:
        driver = webdriver.Chrome(options=options)
    except Exception as e:
        print_colored("\n❌ EROARE: Nu pot conecta la Chrome pe port 9222.", Colors.RED)
        print_colored("   Ruleaza mai intai RUN_LOGIN.bat si lasa browser-ul deschis.", Colors.YELLOW)
        print_colored(f"   Detalii: {str(e)}", Colors.RED)
        sys.exit(1)
    wait = WebDriverWait(driver, 60)
    print_colored("   ✓ Conectat la Chrome (sesiunea de la login)", Colors.GREEN)

    # 10. Click on "Operatii" menu
    print_colored("\n10. Clickez pe Operatii...", Colors.BLUE)
    operatii_button = wait.until(EC.element_to_be_clickable((By.ID, "navbar_Operatii")))
    operatii_button.click()
    time.sleep(1)
    print_colored("   ✓ Meniu Operatii deschis", Colors.GREEN)

    # 11. Click on "Iesiri" submenu (FACTURI EMISE)
    print_colored("\n11. Clickez pe Iesiri (facturi emise)...", Colors.BLUE)
    try:
        iesiri_link = wait.until(EC.element_to_be_clickable((By.ID, "navbar_Iesiri")))
        iesiri_link.click()
        print_colored("   ✓ Link Iesiri apăsat", Colors.GREEN)
    except Exception as e:
        # Fallback: click via JS
        try:
            iesiri_link = wait.until(EC.presence_of_element_located((By.ID, "navbar_Iesiri")))
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", iesiri_link)
            time.sleep(0.3)
            driver.execute_script("arguments[0].click();", iesiri_link)
            print_colored("   ✓ Link Iesiri apăsat (fallback JS)", Colors.GREEN)
        except Exception as e2:
            # Fallback final: click direct prin URL
            print_colored(f"   ⚠ Click direct nu a funcționat, navighez prin URL...", Colors.YELLOW)
            current_url = driver.current_url
            base_url = current_url.split('/sagac/')[0] if '/sagac/' in current_url else "https://web3.sagasoft.ro"
            driver.get(f"{base_url}/sagac/Iesiri")
            print_colored("   ✓ Navigat la /sagac/Iesiri prin URL", Colors.GREEN)

    # 12. Wait for Iesiri page to load
    print_colored("\n12. Aștept pagina Iesiri...", Colors.BLUE)
    time.sleep(3)
    wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
    print_colored("   ✓ Pagina Iesiri încărcată", Colors.GREEN)

    # ===== PASUL 1: MODIFICARE PERIOADA (01.03.2026 - 31.03.2026) =====
    print_colored("\n" + "="*70, Colors.BLUE)
    print_colored("PASUL 1: MODIFICARE PERIOADA - Martie 2026 (01.03.2026 - 31.03.2026)", Colors.BLUE)
    print_colored("="*70, Colors.BLUE)

    # 13. Click pe Interval
    print_colored("\n13. Click pe Interval...", Colors.BLUE)
    interval_button = wait.until(EC.element_to_be_clickable((By.ID, "navbar_Interval")))
    interval_button.click()
    time.sleep(1)
    print_colored("   ✓ Meniu Interval deschis", Colors.GREEN)

    # 14. Data inceput (01.03.2026)
    print_colored("\n14. Completez data de început...", Colors.BLUE)
    interval_start = wait.until(EC.presence_of_element_located((By.ID, "navbar_IntervalStart")))
    interval_start.click()
    time.sleep(0.5)
    interval_start.send_keys(Keys.CONTROL + "a")
    time.sleep(0.2)
    interval_start.send_keys("01.03.2026")
    time.sleep(0.5)
    print_colored("   ✓ Data început: 01.03.2026", Colors.GREEN)

    # 15. Data final (31.03.2026)
    print_colored("\n15. Completez data de final...", Colors.BLUE)
    time.sleep(1)
    interval_end = wait.until(EC.presence_of_element_located((By.ID, "navbar_IntervalEnd")))
    interval_end.click()
    time.sleep(0.5)
    interval_end.send_keys(Keys.CONTROL + "a")
    time.sleep(0.2)
    interval_end.send_keys("31.03.2026")
    time.sleep(0.5)
    interval_end.send_keys(Keys.TAB)
    time.sleep(1)
    print_colored("   ✓ Data final: 31.03.2026", Colors.GREEN)

    # 16. Inchid dropdown cu Escape
    print_colored("\n16. Închid dropdown-ul Interval...", Colors.BLUE)
    time.sleep(0.5)
    driver.find_element(By.TAG_NAME, "body").send_keys(Keys.ESCAPE)
    time.sleep(1)
    print_colored("   ✓ Dropdown închis", Colors.GREEN)

    # 17. Astept aplicarea perioadei
    print_colored("\n17. Aștept aplicarea perioadei...", Colors.BLUE)
    time.sleep(2)
    print_colored("   ✓ Perioada aplicată", Colors.GREEN)

    # ===== PASUL 2: VALIDARE MASIVA =====
    print_colored("\n" + "="*70, Colors.CYAN)
    print_colored("PASUL 2: VALIDARE MASIVA A FACTURILOR EMISE (IESIRI)", Colors.CYAN)
    print_colored("="*70, Colors.CYAN)

    print_colored("\n18. Procesare facturi emise...", Colors.BLUE)
    time.sleep(2)

    validated_count = 0
    skipped_count = 0
    current_position = 1

    print_colored("\n   Numărare rânduri totale...", Colors.BLUE)
    time.sleep(1)

    # Get all invoice rows upfront (clasa pentru Iesiri)
    all_rows = driver.find_elements(
        By.XPATH,
        "//tr[contains(@class, 'rowSelectable_Iesiri')]"
    )
    total_rows = len(all_rows)

    print_colored(f"   ✓ Găsite {total_rows} rânduri în tabel", Colors.GREEN)

    # Process each row by index - this way we avoid stale element references
    for row_idx in range(total_rows):
        try:
            time.sleep(0.3)

            # Re-fetch all rows each time to avoid stale elements
            all_rows = driver.find_elements(
                By.XPATH,
                "//tr[contains(@class, 'rowSelectable_Iesiri')]"
            )

            if row_idx >= len(all_rows):
                print_colored(f"\n   ⚠ Rând {row_idx} nu mai există", Colors.YELLOW)
                break

            current_row = all_rows[row_idx]

            # Get invoice number
            try:
                invoice_num = current_row.find_element(By.XPATH, ".//span[@class='rowFieldText rowFieldText_NrDoc']").text
            except:
                invoice_num = ""

            # Skip rows with empty invoice numbers
            if not invoice_num or invoice_num.strip() == "":
                continue

            # Check if this row is unvalidated (has fa-unlock-alt)
            try:
                icon_element = current_row.find_element(By.XPATH, ".//i[contains(@class, 'fa-unlock-alt')]")
                is_unvalidated = True
            except:
                is_unvalidated = False

            if not is_unvalidated:
                # Already validated, skip
                skipped_count += 1
                continue

            # This is an unvalidated invoice with a number - validate it
            print_colored(f"\n   [{current_position}] Factura emisă NEVALIDATA ({invoice_num}) - Se validează...", Colors.YELLOW)
            current_position += 1

            # Scroll and click
            driver.execute_script("arguments[0].scrollIntoView(true);", current_row)
            time.sleep(0.3)

            try:
                clickable_cell = current_row.find_element(By.XPATH, ".//span[@class='rowFieldText rowFieldText_NrDoc']")
                driver.execute_script("arguments[0].click();", clickable_cell)
            except:
                driver.execute_script("arguments[0].click();", current_row)

            time.sleep(1)

            # Click Validez button
            # Încercăm întâi ID-ul standard, apoi fallback prin span-ul cu textul "Validez"
            validez_clicked = False
            try:
                validez_button = wait.until(EC.element_to_be_clickable((By.ID, "extratoolbarValidez")))
                driver.execute_script("arguments[0].click();", validez_button)
                print_colored(f"      ✓ Validare apăsată (by ID)", Colors.GREEN)
                validez_clicked = True
                time.sleep(1.5)
            except Exception:
                # Fallback 1: caută butonul care conține span-ul "Validez"
                try:
                    validez_button = wait.until(EC.element_to_be_clickable((
                        By.XPATH,
                        "//button[.//span[contains(@class, '__text') and normalize-space(.)='Validez']] | //*[self::a or self::div][.//span[contains(@class, '__text') and normalize-space(.)='Validez']]"
                    )))
                    driver.execute_script("arguments[0].click();", validez_button)
                    print_colored(f"      ✓ Validare apăsată (by span text)", Colors.GREEN)
                    validez_clicked = True
                    time.sleep(1.5)
                except Exception:
                    # Fallback 2: scurtătură ALT+V (V subliniat în "Validez")
                    try:
                        body = driver.find_element(By.TAG_NAME, "body")
                        body.send_keys(Keys.ALT + 'v')
                        print_colored(f"      ✓ Validare apăsată (ALT+V shortcut)", Colors.GREEN)
                        validez_clicked = True
                        time.sleep(1.5)
                    except Exception as e:
                        print_colored(f"      ❌ Nu s-a putut apasa Validez: {str(e)}", Colors.RED)
                        time.sleep(1)

            if validez_clicked:
                validated_count += 1
                time.sleep(0.5)

        except Exception as e:
            print_colored(f"\n   ❌ Eroare rând {row_idx}: {str(e)}", Colors.RED)
            continue

    print_colored(f"\n   ✓ Parcurgere completă - {current_position - 1} procesate", Colors.GREEN)

    # Count remaining validated invoices for summary
    all_rows = driver.find_elements(
        By.XPATH,
        "//tr[contains(@class, 'rowSelectable_Iesiri')]"
    )

    # Count only rows with actual invoice numbers (non-empty)
    total_invoices = 0
    already_validated = 0

    for row in all_rows:
        try:
            invoice_num = row.find_element(By.XPATH, ".//span[@class='rowFieldText rowFieldText_NrDoc']").text
            if invoice_num and invoice_num.strip() != "":
                total_invoices += 1
                # Check if this row is validated (has fa-lock)
                try:
                    row.find_element(By.XPATH, ".//i[contains(@class, 'fa-lock')]")
                    already_validated += 1
                except:
                    pass
        except:
            pass

    # Summary
    print_colored("\n" + "="*70, Colors.CYAN)
    print_colored("REZUMAT VALIDARE FACTURI EMISE (IESIRI)", Colors.CYAN)
    print_colored("="*70, Colors.CYAN)
    print_colored(f"Total facturi emise: {total_invoices}", Colors.BLUE)
    print_colored(f"Validate in aceasta rulare: {validated_count}", Colors.GREEN)
    print_colored(f"Total validate (inclusiv anterioare): {already_validated}", Colors.YELLOW)
    print_colored(f"Nevalidate ramase: {total_invoices - already_validated}", Colors.RED)

    print_colored("\n" + "="*70, Colors.CYAN)
    print_colored("✅ VALIDARE MASIVA FACTURI EMISE COMPLETĂ", Colors.GREEN)
    print_colored("="*70, Colors.CYAN)

    print_colored("\nBrowser rămâne deschis pentru rulari ulterioare", Colors.YELLOW)
    input("\nApasă Enter pentru a inchide aceasta consola (Chrome ramane deschis)...")
    # Nu apelam driver.quit() - Chrome ramane deschis pentru alte scripturi

except Exception as e:
    print_colored(f"\n❌ ERROR: {str(e)}", Colors.RED)
    import traceback
    traceback.print_exc()
    sys.exit(1)
