"""dbt execution helper for local workflows."""
from __future__ import annotations

import json
import os
import subprocess
from pathlib import Path
from typing import Dict, Optional

from .project_generator import DbtProjectGenerator


def ensure_profiles_yml(profile_name: str = "databridge_demo") -> Path:
    """Create ~/.dbt/profiles.yml if it does not exist."""
    home = Path.home()
    profiles_dir = home / ".dbt"
    profiles_dir.mkdir(parents=True, exist_ok=True)
    profiles_path = profiles_dir / "profiles.yml"

    if profiles_path.exists():
        return profiles_path

    generator = DbtProjectGenerator()
    project = generator.get_project(profile_name)
    if not project:
        project = generator.create_project(
            name=profile_name,
            profile=profile_name,
            target_database=os.environ.get("SNOWFLAKE_DATABASE", "ANALYTICS"),
            target_schema=os.environ.get("SNOWFLAKE_SCHEMA", "PUBLIC"),
        )
    content = generator.generate_profiles_yml(project)
    profiles_path.write_text(content, encoding="utf-8")
    return profiles_path


def run_dbt_command(
    command: str,
    project_dir: Path,
    profiles_dir: Optional[Path] = None,
) -> Dict[str, str]:
    """Run a dbt command and capture stdout/stderr."""
    profiles_dir = profiles_dir or Path.home() / ".dbt"
    dbt_bin = os.environ.get("DBT_BIN", "dbt")
    result = subprocess.run(
        [dbt_bin, *command.split()],
        cwd=str(project_dir),
        capture_output=True,
        text=True,
        env={**os.environ, "DBT_PROFILES_DIR": str(profiles_dir)},
    )
    return {
        "command": command,
        "returncode": str(result.returncode),
        "stdout": result.stdout.strip(),
        "stderr": result.stderr.strip(),
    }


def load_run_results(project_dir: Path) -> Dict[str, int]:
    """Parse dbt run_results.json to summarize pass/fail counts."""
    run_results_path = project_dir / "target" / "run_results.json"
    if not run_results_path.exists():
        return {"success": 0, "error": 0, "skipped": 0, "warn": 0}

    data = json.loads(run_results_path.read_text(encoding="utf-8"))
    counts = {"success": 0, "error": 0, "skipped": 0, "warn": 0}
    for res in data.get("results", []):
        status = res.get("status", "unknown")
        if status in counts:
            counts[status] += 1
    return counts
