import logging
import pandas as pd
from typing import Callable, Any
from .client import CortifClient
from .config import get_project_config
from .metrics.calculator import getMetrics_local
from .utils import (
    create_metrics_entries,
    create_run_metadata,
    create_alerts,
)

logger = logging.getLogger(__name__)

def run_local_analysis(
    model_func: Callable,
    reference_data_path: str,
):
    try:
        print("Running Cortif local analysis...")
        config = get_project_config()
        if not config:
            logger.error("`cortif.json` not found. Run 'cortif init' first.")
            return
            
        project_id = config.get("project_id")
        
        client = CortifClient()
        project_details_response = client.get_project_details(project_id)
        if not project_details_response or not project_details_response.get("success"):
            logger.error(f"Failed to fetch project details for {project_id}.")
            return
            
        project_data = project_details_response["data"]
        runner_config = project_data.get("runner_config", {})
        thresholds = runner_config.get("thresholds", {})
        try:
            reference_df = pd.read_csv(reference_data_path)
        except Exception as e:
            logger.error(f"Failed to load reference data from {reference_data_path}: {e}")
            return

        logger.info("Starting Cortif local analysis...")
        print("Calculating metrics...")
        metrics = getMetrics_local(
            local_model_func=model_func,
            reference_df=reference_df,
            thresholds=thresholds,
        )
        print("Metrics calculated:")
        for metric_name, metric_info in metrics.items():
            print(f" - {metric_name}: {metric_info}")
        logger.info("Metrics calculation complete.")
        
        # Get organization ID from config
        organization_id = config.get("organization_id")
        run_id_template = config.get("run_id_template", "local_run")
        
        # Generate a unique run ID using the template and timestamp
        from datetime import datetime
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        run_id = f"{run_id_template}_{timestamp}"
        
        project = {"id": project_id, "organization_id": organization_id}
        
        metrics_to_create = create_metrics_entries(run_id, project_id, metrics)
        run_metadata = create_run_metadata(run_id, metrics, thresholds)
        alerts_to_create = create_alerts(run_id, project, metrics, thresholds)
        
        payload = {
            "project_id": project_id,
            "run_metadata": run_metadata,
            "metrics_to_create": metrics_to_create,
            "alerts_to_create": alerts_to_create,
            "status": "completed",
        }
        print("Submitting run results to Cortif...")
        print("Payload:")
        print(payload)

        logger.info("Submitting run results to Cortif...")
        response = client.submit_run(payload)
        
        if response and response.get("success"):
            run_id = response.get("data", {}).get("run_id")
            logger.info(f"Successfully submitted local run. View results at run_id: {run_id}")
        else:
            logger.error("Failed to submit run results.")

    except Exception as e:
        logger.error(f"Error during Cortif local analysis: {e}")
        try:
            client = CortifClient()
            config = get_project_config()
            project_id = config.get("project_id") if config else None
            if project_id:
                client.submit_run({
                    "project_id": project_id,
                    "status": "failed",
                    "error_message": str(e),
                })
                logger.info("Successfully submitted 'failed' run report.")
        except Exception as submit_e:
            logger.error(f"Failed to submit failure report: {submit_e}")
