# This script scans a local cache directory for PDF files belonging to base tariffs, uploads the PDFs to S3, writes the resulting URLs back into the MySQL database, and logs progress as well as errors to stdout.
import sys; sys.path.append("..")
import os
import datetime
from manager.S3Manager import S3Manager
from manager.MysqlManager import MysqlManager
from models.base_base import BaseBase
from models.deal_deal import DealDeal
from models.option_opti import OptionOpti
from models.provisiongroup_pgro import ProvisiongroupPgro  # zwingend, um Abhängigkeits-Mapping zu initialisieren

# The variable "cacheDir" stores the file‑system path that contains the PDF files waiting for upload.
cacheDir = "../cache"

# The variable "s3Manager" holds an instance that encapsulates S3 upload functionality.
s3Manager = S3Manager()

# The variable "dbSession" stores a SQLAlchemy session used to query and update the MySQL database.
dbSession = MysqlManager().getSession()

# The variable "pdfFiles" gathers all file names inside the cache directory whose names end with the ".pdf" extension, case‑insensitive.
pdfFiles = [f for f in os.listdir(cacheDir) if f.lower().endswith(".pdf")]

# The variable "pdfIdSet" collects distinct base identifiers by stripping the *_flyer or *_pib suffix from each file name stem.
pdfIdSet = set()
for name in pdfFiles:

    # The variable "stem" stores the file name without its extension and is converted to lowercase for uniformity.
    stem = name[:-4].lower()

    # This branch adds the identifier to the set when the file name ends with the flyer suffix.
    if stem.endswith("_flyer"):
        pdfIdSet.add(stem[:-6])

    # This branch adds the identifier to the set when the file name ends with the PIB suffix.
    elif stem.endswith("_pib"):
        pdfIdSet.add(stem[:-4])

# This branch terminates the script early when no matching PDF pairs were found in the cache directory.
if not pdfIdSet:
    print(f"INFO: Keine PDF-Paare in '{cacheDir}' gefunden.")
    dbSession.close()
    sys.exit(0)

# This loop iterates over each distinct base identifier in sorted order to process the associated PDFs.
for currentId in sorted(pdfIdSet):

    # The print statement marks the beginning of processing for the current identifier.
    print(f"\n--- Verarbeitung ID: {currentId} ---")

    # The variable "baseRecords" retrieves all BaseBase rows with a matching provider code so that multiple matches are processed consistently.
    baseRecords = dbSession.query(BaseBase).filter_by(providercode_base=currentId).all()

    # This branch skips the current identifier when no matching BaseBase row exists.
    if not baseRecords:
        print(f"WARNUNG: Kein BaseBase-Eintrag für providercode_base='{currentId}'.")
        continue

    # The variable "flyerPath" composes the absolute path to the flyer PDF for the current identifier.
    flyerPath = os.path.join(cacheDir, f"{currentId}_flyer.pdf")

    # The variable "pibPath" composes the absolute path to the PIB PDF for the current identifier.
    pibPath = os.path.join(cacheDir, f"{currentId}_pib.pdf")

    # The variable "flyerUrl" will store the public S3 URL of the flyer PDF or remain None when the upload fails or the file does not exist.
    flyerUrl = None

    # This branch uploads the flyer PDF when the file exists.
    if os.path.exists(flyerPath):

        # The variable "flyerKey" determines the destination key inside the S3 bucket.
        flyerKey = f"flyers/{currentId}_flyer.pdf"

        # The variable "flyerUrl" receives the URL returned by the upload method.
        flyerUrl = s3Manager.uploadFile(flyerPath, flyerKey)

        # This branch prints an error message when the upload failed and no URL was returned.
        if not flyerUrl:
            print(f"FEHLER: Flyer-Upload fehlgeschlagen für ID {currentId}")

    # The variable "pibUrl" will store the public S3 URL of the PIB PDF or remain None when the upload fails or the file does not exist.
    pibUrl = None

    # This branch uploads the PIB PDF when the file exists.
    if os.path.exists(pibPath):

        # The variable "pibKey" determines the destination key inside the S3 bucket.
        pibKey = f"pibs/{currentId}_pib.pdf"

        # The variable "pibUrl" receives the URL returned by the upload method.
        pibUrl = s3Manager.uploadFile(pibPath, pibKey)

        # This branch prints an error message when the upload failed and no URL was returned.
        if not pibUrl:
            print(f"FEHLER: PIB-Upload fehlgeschlagen für ID {currentId}")

    # This loop updates each BaseBase record so that both flyer and PIB URLs are stored without overwriting existing values.
    for base in baseRecords:

        # This branch writes the flyer URL into the database row when no URL has been stored before and a new URL is available.
        if base.flyerurl_base is None and flyerUrl:
            base.flyerurl_base = flyerUrl
            base.updated_base = datetime.datetime.now()
            print(f"INFO: flyerurl_base gesetzt: {flyerUrl}")

        # This branch writes the PIB URL into the database row when no URL has been stored before and a new URL is available.
        if base.piburl_base is None and pibUrl:
            base.piburl_base = pibUrl
            base.updated_base = datetime.datetime.now()
            print(f"INFO: piburl_base gesetzt: {pibUrl}")

    # The commit call atomically persists all changes performed for the current identifier.
    dbSession.commit()

# The database session is closed after all identifiers have been processed.
dbSession.close()

# The print statement confirms that the entire upload sequence finished successfully.
print("INFO: Upload-Vorgang abgeschlossen.")