#!/usr/bin/env python3
"""
Deploy complete data quality validation infrastructure.

This unified script replaces:
- ensure_container.py (containers are auto-created)
- deploy_datamodels.py (data models are auto-created)
- deploy_function.py (function deployment)
- deploy_workflows.py (workflow deployment)
- deploy_timeseries_workflows.py (timeseries workflow deployment)

Usage:
    python scripts/deploy_infrastructure.py [--dry-run] [--force]
"""

import argparse
import json
import os
import sys

from cognite_data_quality import deploy_validation_infrastructure
from shared import create_client, get_repo_root


def main():
    parser = argparse.ArgumentParser(description="Deploy complete data quality validation infrastructure")
    parser.add_argument("--dry-run", action="store_true", help="Preview without deploying")
    parser.add_argument("--force", action="store_true", help="Force redeployment of everything (functions + workflows)")
    parser.add_argument("--force-workflows", action="store_true", help="Force workflow redeployment even if unchanged")
    parser.add_argument("--output", type=str, help="JSON output file for results")
    args = parser.parse_args()

    repo_root = get_repo_root()
    print(f"Repository root: {repo_root}")

    # Get config environment
    config_env = os.environ.get("CONFIG_ENV", "").strip() or None
    if not config_env:
        raise ValueError("CONFIG_ENV environment variable not set")

    print(f"\nDeploying infrastructure for environment: {config_env}")
    config_dir = repo_root / "config" / "environments" / config_env

    # Connect to CDF
    print("\nConnecting to CDF...")
    if args.dry_run:
        print("  [DRY RUN] Would connect to CDF")
        client = None
    else:
        client = create_client()
        print(f"  Connected to project: {client.config.project}")

    # Get credentials for function secrets (required by orchestrator for trigger creation)
    client_id = os.getenv("COGNITE_CLIENT_ID") or os.getenv("IDP_CLIENT_ID")
    client_secret = os.getenv("COGNITE_CLIENT_SECRET") or os.getenv("IDP_CLIENT_SECRET")
    function_secrets = None
    if client_id and client_secret:
        function_secrets = {"client-id": client_id, "client-secret": client_secret}
        print("  Function secrets: configured (orchestrator can create triggers)")
    else:
        print("  ⚠️  Function secrets: missing (orchestrator triggers will fail)")
        print("     Set COGNITE_CLIENT_ID and COGNITE_CLIENT_SECRET environment variables")

    # Deploy everything using the unified function
    print(f"\n{'=' * 60}")
    print("DEPLOYING DATA QUALITY VALIDATION INFRASTRUCTURE")
    print(f"{'=' * 60}\n")
    print("This will deploy:")
    print("  - Data quality containers (Records, OrchestrationState, FunctionValidationState)")
    print("  - Monitoring data models and views")
    print("  - Validation function (with secrets for orchestrator)")
    print("  - Instance validation workflows")
    print("  - Time series validation workflows")
    print("")

    results = deploy_validation_infrastructure(
        client=client,
        settings_path=config_dir / "settings.yaml",
        # Let the function resolve views_dir and timeseries_dir from settings.yaml
        # (relative to settings_path.parent)
        function_secrets=function_secrets,
        force=args.force,
        force_workflows=args.force_workflows,
        dry_run=args.dry_run,
    )

    # Summary
    print(f"\n{'=' * 60}")
    print("DEPLOYMENT SUMMARY")
    print(f"{'=' * 60}\n")

    # Function
    function_results = results.get("functions", {})
    func_result = function_results.get("function", {})
    func_status = func_result.get("status", "unknown")
    func_id = func_result.get("function", "N/A")
    print(f"Function: {func_id}")
    print(f"  Status: {func_status.upper()}")

    # Workflows
    workflows = results.get("workflows", [])
    deployed_wf = sum(1 for w in workflows if w.get("status") == "deployed")
    skipped_wf = sum(1 for w in workflows if w.get("status") == "skipped")
    print(f"\nInstance Validation Workflows: {len(workflows)} total")
    print(f"  Deployed: {deployed_wf}")
    print(f"  Skipped (up to date): {skipped_wf}")

    # Time series workflows
    ts_workflows = results.get("timeseries_workflows", [])
    if ts_workflows:
        deployed_ts = sum(1 for w in ts_workflows if w.get("status") == "deployed")
        skipped_ts = sum(1 for w in ts_workflows if w.get("status") == "skipped")
        print(f"\nTime Series Validation Workflows: {len(ts_workflows)} total")
        print(f"  Deployed: {deployed_ts}")
        print(f"  Skipped (up to date): {skipped_ts}")

    if args.dry_run:
        print("\n[DRY RUN] No changes were made")

    # Write output if requested
    if args.output:
        with open(args.output, "w") as f:
            json.dump(results, f, indent=2)
        print(f"\nResults written to: {args.output}")

    return 0


if __name__ == "__main__":
    sys.exit(main())
