"""
Seed-Script: Legt Firma KPT-Consulting + User Florian an
und importiert das LV-KPT-Proj+Doku-2024ff inkl. Langtexte.
"""
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from app import create_app
from app.extensions import db
from app.models.company import Company
from app.models.user import User
from app.models.lv import LVPosition
from app.models.contract import Contract
from datetime import date

app = create_app()

LV_NAME = 'LV-KPT-Proj+Doku-2024ff'
FLATFILE = os.path.join('..', 'daten', 'LV', f'{LV_NAME}.txt')
LANGFOLDER = os.path.join('..', 'daten', 'LV', LV_NAME)

def run():
    with app.app_context():
        # 1. Firma anlegen
        company = Company.query.filter_by(slug='kpt-consulting').first()
        if not company:
            company = Company(
                name='KPT-Consulting', slug='kpt-consulting',
                strasse='Musterstr. 1', plz='88045', ort='Friedrichshafen',
                telefon='+49 7541 123456', email='info@kpt-consulting.de'
            )
            db.session.add(company)
            db.session.flush()
            print(f'Firma angelegt: {company.name} (ID {company.id})')
        else:
            print(f'Firma existiert bereits: {company.name} (ID {company.id})')

        # 2. User Florian Kramer anlegen
        user = User.query.filter_by(email='fk@kpt-consulting.de').first()
        if not user:
            user = User(
                company_id=company.id, email='fk@kpt-consulting.de',
                vorname='Florian', nachname='Kramer', rolle='firmadmin',
                darf_projekte_anlegen=True, darf_lv_verwalten=True,
                darf_preise_sehen=True, darf_aufmass_verwalten=True,
            )
            user.set_password('kpt2024')
            db.session.add(user)
            db.session.flush()
            print(f'User angelegt: {user.full_name} ({user.email})')
        else:
            print(f'User existiert bereits: {user.full_name}')

        # 3. Vertrag anlegen
        contract = Contract.query.filter_by(company_id=company.id, belegnummer='4650014601').first()
        if not contract:
            contract = Contract(
                company_id=company.id,
                name='SW Proj+Doku 2024ff',
                belegnummer='4650014601',
                beleg_datum=date(2025, 12, 16),
                laufzeit_start=date(2024, 6, 1),
                laufzeit_ende=date(2026, 5, 31),
                status='Angenommen',
            )
            db.session.add(contract)
            db.session.flush()
            print(f'Vertrag angelegt: {contract.name}')
        else:
            print(f'Vertrag existiert bereits: {contract.name}')

        # 4. LV-Positionen importieren
        if not os.path.exists(FLATFILE):
            print(f'FEHLER: Flatfile nicht gefunden: {FLATFILE}')
            return

        existing = LVPosition.query.filter_by(company_id=company.id, lv_name=LV_NAME).count()
        if existing > 0:
            print(f'LV {LV_NAME} bereits importiert ({existing} Positionen). Überspringe.')
            return

        # Encoding automatisch erkennen (UTF-16-BE/LE oder UTF-8)
        with open(FLATFILE, 'rb') as f:
            raw = f.read()
        if raw[:2] in (b'\xff\xfe', b'\xfe\xff'):
            enc = 'utf-16'
        else:
            enc = 'utf-8'
        text = raw.decode(enc, errors='replace').strip('\ufeff').replace('\r\n', '\n').replace('\r', '\n')
        lines = text.split('\n')

        count = 0
        for idx, line in enumerate(lines):
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            parts = [p.strip() for p in line.split('|')]
            if len(parts) < 2:
                continue
            pos_nr = parts[0]
            kurztext = parts[1] if len(parts) > 1 else ''
            einheit = parts[2] if len(parts) > 2 else 'ST'
            preis_str = parts[3] if len(parts) > 3 else '0'
            einzelpreis = float(preis_str.replace(',', '.')) if preis_str else 0.0

            # Langtext aus Einzeldatei lesen
            langtext = ''
            txt_path = os.path.join(LANGFOLDER, f'{pos_nr}.txt')
            if os.path.exists(txt_path):
                with open(txt_path, 'rb') as tf:
                    raw_txt = tf.read()
                if raw_txt[:2] in (b'\xff\xfe', b'\xfe\xff'):
                    enc_txt = 'utf-16'
                else:
                    enc_txt = 'utf-8'
                langtext = raw_txt.decode(enc_txt, errors='replace').strip()

            pos = LVPosition(
                company_id=company.id, contract_id=contract.id, lv_name=LV_NAME,
                pos_nr=pos_nr, order_index=idx + 1,
                kurztext=kurztext, langtext=langtext,
                einheit=einheit, einzelpreis=einzelpreis,
            )
            db.session.add(pos)
            count += 1

        db.session.commit()
        print(f'{count} LV-Positionen importiert (mit Langtext aus {LANGFOLDER})')

if __name__ == '__main__':
    run()
