import unittest
import os
import sys
from unittest.mock import MagicMock, patch

# Adjust path to allow importing from backend
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from backend.services.classification import ClassificationService
from backend.database import Company, Industry, RoboticsCategory, Session

class TestHospitalMetricFinal(unittest.TestCase):

    def setUp(self):
        self.service = ClassificationService()
        self.mock_db = MagicMock(spec=Session)
        
        self.mock_company = Company(id=8, name="Klinikum Landkreis Erding")
        self.mock_industry_hospital = Industry(
            id=1,
            name="Healthcare - Hospital",
            scraper_search_term="Anzahl Betten",
            standardization_logic="wert * 100",
            primary_category=RoboticsCategory(name="Reinigungsroboter"),
            secondary_category=RoboticsCategory(name="Serviceroboter"),
        )
        self.mock_website_content = "Ein langer Text, der die 100-Zeichen-Prüfung besteht."

    @patch('backend.services.classification.ClassificationService._generate_marketing_opener')
    @patch('backend.services.classification.ClassificationService._extract_and_calculate_metric_cascade')
    @patch('backend.services.classification.ClassificationService._find_direct_area')
    @patch('backend.services.classification.ClassificationService._run_llm_classification_prompt')
    @patch('backend.services.classification.ClassificationService._get_website_content_and_url')
    @patch('backend.services.classification.ClassificationService._load_industry_definitions')
    def test_final_hospital_logic(
        self, 
        mock_load_industries, 
        mock_get_website, 
        mock_classify, 
        mock_find_direct_area, 
        mock_extract_cascade, 
        mock_generate_opener
    ):
        print("\n--- Running Final Hospital Logic Test ---")

        # --- MOCK SETUP ---
        mock_load_industries.return_value = [self.mock_industry_hospital]
        mock_get_website.return_value = (self.mock_website_content, "http://mock.com")
        mock_classify.return_value = "Healthcare - Hospital"
        mock_find_direct_area.return_value = None # STAGE 1 MUST FAIL
        
        proxy_metric_result = {
            "calculated_metric_name": "Anzahl Betten",
            "calculated_metric_value": 352.0,
            "calculated_metric_unit": "Betten",
            "standardized_metric_value": 35200.0,
            "standardized_metric_unit": "m²",
            "metric_source": "wikipedia",
        }
        mock_extract_cascade.return_value = proxy_metric_result
        mock_generate_opener.side_effect = ["Primary Opener", "Secondary Opener"]

        # --- EXECUTION ---
        updated_company = self.service.classify_company_potential(self.mock_company, self.mock_db)

        # --- ASSERTIONS ---
        mock_find_direct_area.assert_called_once()
        mock_extract_cascade.assert_called_once()

        self.assertEqual(updated_company.calculated_metric_name, "Anzahl Betten")
        self.assertEqual(updated_company.calculated_metric_value, 352.0)
        self.assertEqual(updated_company.standardized_metric_value, 35200.0)
        print("   ✅ Metrics from Stage 2 correctly applied.")

        self.assertEqual(updated_company.ai_opener, "Primary Opener")
        self.assertEqual(updated_company.ai_opener_secondary, "Secondary Opener")
        print("   ✅ Openers correctly applied.")

        print("\n--- ✅ PASSED: Final Hospital Logic Test. ---")

if __name__ == '__main__':
    unittest.main()
