#!/usr/bin/env python3 import sys from pathlib import Path from dotenv import load_dotenv import os import json import pandas as pd load_dotenv() print("SNOWFLAKE_USER:", os.getenv("SNOWFLAKE_USER")) # Ensure imports sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from core.scenarios.sql_mapping_builder import build_sql_mapping from core.profiling.profiler_engine import ( ensure_recordid, detect_column_types, detect_column_roles, generate_pattern_buckets, select_coverage_rows, compute_coverage_metrics, detect_variance_patterns ) from core.snowflake.target_validation import validate_scenario, execute_scenario, snowflake_connection from core.scenarios.target_scenarios_builder import build_target_scenarios from core.snowflake.target_metadata_resolver import resolve_target_metadata from core.snowflake.load_raw_to_snowflake import sync_all_tables from core.scenarios.ai_scenario_manager import analyze_changes # ------------------------------------------------- # PATHS # ------------------------------------------------- PROJECT_ROOT = Path(__file__).resolve().parents[1] DATA_DIR = PROJECT_ROOT / "data" PROFILED_DATA_DIR = DATA_DIR / "profiled" RAW_DATA_DIR = DATA_DIR / "raw" REFERENCE_DATA_DIR = DATA_DIR / "raw" / "reference_tables" MAPPING_DIR = DATA_DIR / "mapping_document" SCENARIOS_DIR = DATA_DIR / "scenarios" OUTPUT_DIR = DATA_DIR / "output" MAPPING_PATH = os.environ.get( "MAPPING_PATH", str(MAPPING_DIR / "New_Dummy_mapping_doc_v1.xlsx") ) # 🔥 Detect version automatically MAPPING_VERSION = "v2" if "v2" in MAPPING_PATH.lower() else "v1" # Snowflake target TARGET_DATABASE = os.environ.get("SNOWFLAKE_DATABASE", "AI_TEST") TARGET_SCHEMA = os.environ.get("SNOWFLAKE_SCHEMA", "TARGET") TARGET_TABLE = "TARGET_ORDERS_FACT" # Ensure directories exist for d in [PROFILED_DATA_DIR, OUTPUT_DIR, SCENARIOS_DIR]: d.mkdir(parents=True, exist_ok=True) # ------------------------------------------------- # DQ PIPELINE # ------------------------------------------------- def run_profiler_pipeline(table: str, df: pd.DataFrame) -> pd.DataFrame: print(f"\n🔬 PROFILING → {table}") df = ensure_recordid(df) column_types = detect_column_types(df) roles = detect_column_roles(df, column_types) buckets = generate_pattern_buckets(df, column_types, roles) coverage_rows = select_coverage_rows(df, buckets, column_types) variance = detect_variance_patterns(df, coverage_rows, column_types) coverage_metrics = compute_coverage_metrics(buckets, coverage_rows, column_types) print("RAW ROWS:", len(df)) print("PROFILED ROWS:", len(coverage_rows)) print("COVERAGE:", coverage_metrics) out_path = Path(PROFILED_DATA_DIR) / f"{table}_profiled.csv" coverage_rows.to_csv(out_path, index=False) print(f"💾 Saved profiled data → {out_path}") return coverage_rows # ------------------------------------------------- # LOAD SCENARIOS # ------------------------------------------------- def load_scenarios_from_dir(base_dir: Path): scenarios = [] if not base_dir.exists(): return scenarios for json_file in base_dir.rglob("*.json"): if json_file.name == "scenario_summary.json": continue with open(json_file) as f: scenarios.append(json.load(f)) return scenarios # ------------------------------------------------- # MAIN # ------------------------------------------------- def main(): # ------------------------------------------------- # 0️⃣ SYNC SNOWFLAKE # ------------------------------------------------- print("\n☁️ Syncing Snowflake schema and loading data...") sync_all_tables() print("✅ Snowflake sync complete\n") # ------------------------------------------------- # 1️⃣ BUILD MAPPING # ------------------------------------------------- print("🔍 Building SQL mapping...") mapping = build_sql_mapping(MAPPING_PATH) print("*"*100) print("Sample mapping rows:") print(mapping) print("*"*100) # ------------------------------------------------- # 2️⃣ RUN DQ # ------------------------------------------------- for table in mapping["source_tables"]: raw_path = Path(RAW_DATA_DIR) / f"{table}.csv" if not raw_path.exists(): ref_path = Path(REFERENCE_DATA_DIR) / f"{table}.csv" if ref_path.exists(): raw_path = ref_path else: print(f"⚠️ Missing data for {table}, skipping") continue df = pd.read_csv(raw_path) run_profiler_pipeline(table, df) print("\n✅ DQ COMPLETE") # ------------------------------------------------- # 3️⃣ TARGET META # ------------------------------------------------- print("\n🎯 Resolving target metadata from Snowflake...") target_meta = resolve_target_metadata( database=TARGET_DATABASE, schema=TARGET_SCHEMA, table=TARGET_TABLE, mapping=mapping, ) print(json.dumps(target_meta, indent=2)) # ------------------------------------------------- # 4️⃣ LOAD EXISTING SCENARIOS # ------------------------------------------------- print("\n🔍 Loading existing scenarios...") if MAPPING_VERSION == "v2": existing_path = SCENARIOS_DIR / "mapping_v1" / TARGET_TABLE else: existing_path = SCENARIOS_DIR / "mapping_v1" / TARGET_TABLE # first run, empty anyway all_scenarios = load_scenarios_from_dir(existing_path) print(f"Loaded {len(all_scenarios)} existing scenarios from {existing_path}") # ------------------------------------------------- # 5️⃣ AI CHANGE DETECTION # ------------------------------------------------- print("\n🧠 Running AI change detection...") change_plan = analyze_changes(mapping, all_scenarios) print("\n🧠 AI CHANGE PLAN") print(change_plan) # ------------------------------------------------- # 6️⃣ BUILD / REUSE SCENARIOS # ------------------------------------------------- execution_log = {} scenario_dir = SCENARIOS_DIR / f"mapping_{MAPPING_VERSION}" / TARGET_TABLE scenario_dir.mkdir(parents=True, exist_ok=True) execution_log = {} if change_plan["create"] or change_plan["update"]: print("\n🆕 Creating/Updating scenarios...") result_df, scenario_dir, execution_log = build_target_scenarios( mapping_path=MAPPING_PATH, target_meta=target_meta, output_dir=scenario_dir ) else: print("\n♻️ Reusing existing scenarios") result_df = None # Save output if result_df is not None: output_path = OUTPUT_DIR / "final_target_result.csv" result_df.to_csv(output_path, index=False) print(f"💾 Saved final result → {output_path}") print(f"📁 Scenario directory → {scenario_dir}") print("\n📊 EXECUTION LOG") if execution_log: print("\n📊 EXECUTION LOG") print(json.dumps(execution_log.get("coverage", {}), indent=2)) print(json.dumps(execution_log.get("scenarios_generated", {}), indent=2)) print(json.dumps(execution_log["scenarios_generated"], indent=2)) # ------------------------------------------------- # 7️⃣ VALIDATION (FIXED) # ------------------------------------------------- print("\n🧪 Executing scenarios...") validation_scenarios = load_scenarios_from_dir(scenario_dir) print(f"Validating {len(validation_scenarios)} scenarios") results = [] conn = snowflake_connection() cursor = conn.cursor() cursor.execute(f""" TRUNCATE TABLE {TARGET_DATABASE}.{TARGET_SCHEMA}.{TARGET_TABLE} """) conn.commit() cursor.close() conn.close() for scenario in validation_scenarios: try: if "tables" in scenario: before = {} after = {} for table_data in scenario["tables"].values(): if table_data.get("before"): before.update(table_data["before"]) if table_data.get("after"): after.update(table_data["after"]) scenario_for_validation = { "operation": scenario.get("operation"), "before_image": before, "after_image": after } else: scenario_for_validation = scenario execute_scenario(scenario, target_meta) res = validate_scenario( scenario=scenario_for_validation, target_meta=target_meta ) status = res.get("status", "FAIL") except Exception as e: print("Execution error:", e) status = "FAIL" print(f"{scenario.get('operation')} → {status}") results.append({ "operation": scenario.get("operation"), "status": status }) # ------------------------------------------------- # SUMMARY # ------------------------------------------------- if not results: print("\n⚠️ No validation results produced") return summary_df = pd.DataFrame(results) print("\n📊 VALIDATION SUMMARY") print(summary_df["status"].value_counts()) print("\n🎯 FINAL RESULT") print("PASS:", (summary_df["status"] == "PASS").sum()) print("FAIL:", (summary_df["status"] == "FAIL").sum()) # ------------------------------------------------- if __name__ == "__main__": main()