import os
import sys

# Ensure package imports work when running as a script.
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

from app.models.user import User, Secret
from app.repositories.user_repository import create
import re
import uuid
from datetime import datetime, UTC
from app.models.hospital import Hospital
from app.models.test import Test, SubTest
from app.repositories.hospital_repository import create as create_hospital, find_by_tracking_id
from app.repositories.test_repository import create as create_test



def parse_and_store_blood_work(filepath: str, patient_id):
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        
    hospital_name = "Unknown Hospital"
    subtests = []
    
    for line in lines:
        line = line.strip()
        if line.startswith("Healthcare Facility:"):
            split_line = line.split("Healthcare Facility:", 1)
            if len(split_line) > 1:
                hospital_name = split_line[1].strip()
            continue
        if line.startswith('<') or line.startswith('>'):
            if subtests:
                limit_match = re.search(r'^([<>])\s*(\d+(?:,\d+)?)', line)
                if limit_match:
                    op = limit_match.group(1)
                    val = float(limit_match.group(2).replace(',', '.'))
                    last_test = subtests[-1]
                    if op == '<':
                        last_test.refMax = val
                    elif op == '>':
                        last_test.refMin = val
            continue
            
        # regex matches lines of form (v) Kalsiyum (Ca) 9,3 mg/dL 8,4-10,2 and so on.
        match = re.search(r'^(?:iv\)|v\)|rt\)|g |\(v\))?\s*([a-zA-Z].*?)\s+(\d+(?:,\d+)?)\s+([a-zA-Z0-9/%#\.]+(?:/[a-zA-Z0-9]+)?)\s*([<>\d,\-\s]+)?$', line)
        if match:
            name = match.group(1).strip()
            value_str = match.group(2).replace(',', '.')
            unit = match.group(3).strip()
            ref_str = match.group(4)
            
            value = float(value_str)
            ref_min = None
            ref_max = None
            
            if ref_str:
                ref_str = ref_str.strip()
                if ref_str.startswith('<') or ref_str.startswith('>'):
                    limit_match = re.search(r'^([<>])\s*(\d+(?:,\d+)?)', ref_str)
                    if limit_match:
                        op = limit_match.group(1)
                        val = float(limit_match.group(2).replace(',', '.'))
                        if op == '<':
                            ref_max = val
                        elif op == '>':
                            ref_min = val
                elif '-' in ref_str:
                    parts = ref_str.split('-')
                    if len(parts) == 2:
                        try:
                            if parts[0].strip():
                                ref_min = float(parts[0].replace(',', '.').strip())
                            if parts[1].strip():
                                ref_max = float(parts[1].replace(',', '.').strip())
                        except ValueError:
                            pass
            
            subtests.append(SubTest(
                name=name if name else "Unknown",
                value=value,
                unit=unit,
                refMin=ref_min,
                refMax=ref_max
            ))

    tracking_id = re.sub(r'[^a-zA-Z0-9]', '_', hospital_name).strip('_').upper()
    if not tracking_id:
        tracking_id = "UNKNOWN_HOSP"
        
    hospital = find_by_tracking_id(tracking_id)
    if not hospital:
        hospital = Hospital(
            trackingId=tracking_id,
            name=hospital_name,
            address="Unknown Address"
        )
        hospital = create_hospital(hospital)

    test_obj = Test(
        testId=str(uuid.uuid4()),
        sutCode="UNKNOWN_SUT",
        name="Combined Blood Work",
        date=datetime.now(UTC),
        subtests=subtests,
        patientId=patient_id,
        practitioner="Unknown"
    )
    create_test(test_obj)
# Using combined.txt from the same directory for testing
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'combined.txt')
if os.path.exists(file_path):
    parse_and_store_blood_work(file_path, "69ad71c8a4702fae20232a73")
