#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SAGA WEB - PAS 0: LOGIN + SELECTIE FIRMA
==========================================
Acest script:
1. Deschide Chrome cu remote debugging activ pe portul 9222
2. Face login pe SAGA Web cu credentialele din config_v2.txt
3. Selecteaza firma BONO FINTECH - TEST SAGA S.R.L.
4. Apasa Conectare
5. LASA Chrome deschis pentru a fi reutilizat de toate celelalte scripturi

Dupa rulare, poti porni orice alt script (validare/jurnal banca) si va
folosi acest Chrome existent — nu se va mai loga din nou.

IMPORTANT: Nu inchide Chrome-ul cat timp vrei sa rulezi alte scripturi.
"""

import time
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
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


# ─── Culori consola ─────────────────────────────────────────
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 - PAS 0: LOGIN + SELECTIE FIRMA", Colors.BOLD)
print_colored("Chrome ramane deschis pe port 9222 pentru alte scripturi", Colors.YELLOW)
print("=" * 70 + "\n")

try:
    # 1. Config
    print_colored("1. Citesc configurare...", Colors.BLUE)
    config = configparser.ConfigParser()
    config.read('config_v2.txt', encoding='utf-8')
    username = config.get('SAGA', 'saga_username')
    password = config.get('SAGA', 'saga_password')
    print_colored(f"   ✓ Username: {username}", Colors.GREEN)

    # 2. Lansez Chrome cu remote debugging
    print_colored("\n2. Lansez Chrome cu remote debugging pe port 9222...", Colors.BLUE)
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_argument('--remote-debugging-port=9222')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    # CRUCIAL: detach=True face ca Chrome sa ramana deschis cand scriptul iese
    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    wait = WebDriverWait(driver, 60)
    print_colored("   ✓ Chrome deschis (port 9222, detach activ)", Colors.GREEN)

    # 3. Navigate la SAGA
    print_colored("\n3. Navighez la SAGA Web...", Colors.BLUE)
    driver.get("https://web3.sagasoft.ro")
    time.sleep(2)
    print_colored("   ✓ Pagina incarcata", Colors.GREEN)

    # 4. Login
    print_colored("\n4. Introduc username/password...", Colors.BLUE)
    f = wait.until(EC.presence_of_element_located((By.ID, "wl_username")))
    f.clear(); f.send_keys(username)
    f = wait.until(EC.presence_of_element_located((By.ID, "wl_password")))
    f.clear(); f.send_keys(password)
    wait.until(EC.element_to_be_clickable(
        (By.XPATH, "//button[.//span[contains(text(),'Autentificare')]]")
    )).click()
    time.sleep(2)
    print_colored("   ✓ Autentificat", Colors.GREEN)

    # 5. Astept pagina de selectie firma
    print_colored("\n5. Astept pagina de selectie firma...", Colors.BLUE)
    time.sleep(2)
    print_colored("   ✓ Pagina firme afisata", Colors.GREEN)

    # 6. Selecteaza BONO FINTECH - TEST SAGA S.R.L.
    # Cautam dupa 'BONO FINTECH - TEST SAGA' ca sa fie unic
    # (in caz ca exista mai multe firme cu 'BONO FINTECH' in nume).
    print_colored("\n6. Selectez firma BONO FINTECH - TEST SAGA S.R.L. ...", Colors.BLUE)
    try:
        bono_row = wait.until(EC.element_to_be_clickable((
            By.XPATH,
            "//div[contains(@class, 'rowSelectable')]"
            "[.//span[contains(@class, 'firmaNume') and "
            "contains(translate(normalize-space(.), '.', ''), 'BONO FINTECH - TEST SAGA')]]"
        )))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", bono_row)
        time.sleep(0.3)
        try:
            bono_row.click()
        except Exception:
            driver.execute_script("arguments[0].click();", bono_row)
        time.sleep(0.5)
        print_colored("   ✓ BONO FINTECH - TEST SAGA S.R.L. selectat", Colors.GREEN)
    except Exception:
        # Fallback: click pe span direct
        try:
            bono_span = wait.until(EC.element_to_be_clickable((
                By.XPATH,
                "//span[contains(@class, 'firmaNume') and "
                "contains(translate(normalize-space(.), '.', ''), 'BONO FINTECH - TEST SAGA')]"
            )))
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", bono_span)
            time.sleep(0.3)
            driver.execute_script("arguments[0].click();", bono_span)
            time.sleep(0.5)
            print_colored("   ✓ BONO FINTECH - TEST SAGA S.R.L. selectat (fallback)", Colors.GREEN)
        except Exception as e2:
            print_colored(f"   ⚠ Nu s-a putut selecta BONO FINTECH - TEST SAGA S.R.L.: {str(e2)}", Colors.YELLOW)
            raise

    # 7. Conectare la firma
    print_colored("\n7. Apas Conectare...", Colors.BLUE)
    wait.until(EC.element_to_be_clickable((By.ID, "btnConectare"))).click()
    time.sleep(4)
    print_colored("   ✓ Conectat la firma", Colors.GREEN)

    # ─── Mesaj final ─────────────────────────────────────────
    print_colored("\n" + "=" * 70, Colors.GREEN)
    print_colored("✓ READY · Chrome ramane deschis pe port 9222", Colors.GREEN + Colors.BOLD)
    print_colored("=" * 70, Colors.GREEN)
    print_colored("\nAcum poti rula orice alt script — se va conecta la acest Chrome:", Colors.CYAN)
    print_colored("  · RUN_VALIDARE_MASIVA.bat", Colors.CYAN)
    print_colored("  · RUN_VALIDARE_MASIVA_IESIRI.bat", Colors.CYAN)
    print_colored("  · RUN_VALIDARE_MASIVA_VALUTA.bat", Colors.CYAN)
    print_colored("  · RUN_jurnal_banca_complet.bat", Colors.CYAN)
    print_colored("  · RUN_jurnal_banca_pas1_scanare.bat", Colors.CYAN)
    print_colored("  · RUN_jurnal_banca_pas2_reconciliere.bat", Colors.CYAN)
    print_colored("\nIMPORTANT:", Colors.YELLOW)
    print_colored("  - NU inchide Chrome-ul cat timp vrei sa rulezi scripturi.", Colors.YELLOW)
    print_colored("  - Poti inchide aceasta consola — Chrome ramane deschis (detach activ).", Colors.YELLOW)
    print_colored("  - Cand termini, inchide Chrome manual.", Colors.YELLOW)
    print_colored("\nApasa Enter pentru a inchide aceasta consola (Chrome ramane deschis)...", Colors.YELLOW)
    input()

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